From 6d2638493fff40d4863507b89c40ad672092e205 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:46:00 -0800 Subject: [PATCH 01/20] fix(schema): refuse sets of struct-stored user classes --- .zed/rules | 3 + CLAUDE.md | 3 + changelog.d/ITL-922.md | 5 + docs/concepts/function-pods.md | 4 + docs/concepts/logical-type-identifiers.md | 4 + docs/concepts/your-own-data-types.md | 5 + docs/dev/design_issues/ITL-922-SU1.md | 12 +++ docs/reference/database-types.md | 3 + docs/reference/hashing.md | 4 + src/orcapod/core/datagrams/datagram.py | 5 + src/orcapod/core/nodes/source_node.py | 28 +++++- src/orcapod/core/sources/polling_source.py | 4 + src/orcapod/logical_types/protocols.py | 4 + .../logical_types/user_class_logical_type.py | 19 +++- src/orcapod/pipeline/graph.py | 1 + src/orcapod/semantic_types/nested_storage.py | 99 ++++++++++++++++++- .../semantic_types/universal_converter.py | 2 + .../test_nested_logical_type_refusal.py | 74 ++++++++++++++ .../test_structural_dataclass.py | 10 +- 19 files changed, 276 insertions(+), 13 deletions(-) create mode 100644 changelog.d/ITL-922.md create mode 100644 docs/dev/design_issues/ITL-922-SU1.md diff --git a/.zed/rules b/.zed/rules index c42e2dddc..8cd9f015b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -470,6 +470,9 @@ 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, refuse `set[T]` of a struct-stored user class at definition, including nested + declarations (`nested_storage.require_supported_sets`, ITL-922). Name the column or field + and direct users to `list[T]`. Canonical ordering for those sets is deferred. - 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 the extension metadata; together they are the logical type identifier. A nested diff --git a/CLAUDE.md b/CLAUDE.md index 88233057c..5d8d0b1d1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -481,6 +481,9 @@ 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, refuse `set[T]` of a struct-stored user class at definition, including nested + declarations (`nested_storage.require_supported_sets`, ITL-922). Name the column or field + and direct users to `list[T]`. Canonical ordering for those sets is deferred. - 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 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..0af38aebe --- /dev/null +++ b/changelog.d/ITL-922.md @@ -0,0 +1,5 @@ +### Breaking changes and migration + +- Orcapod rejects declarations of sets of struct-stored user classes, including ordinary + dataclasses, pydantic models and `orcapod.dataclass` classes. Use `list[T]` and supply the + elements in the order you want stored. Canonical ordering for these sets is deferred. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 943874132..03da0c2b1 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -285,6 +285,10 @@ 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's parameter or output declaration also refuses sets of user classes stored as +structs in Orcapod 0.4.0, including nested sets. The `NestedTypeNotStorableError` +names the parameter, output or field. Use `list[T]` to pass or return those values. + 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 4503148a5..a8fd12971 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -150,6 +150,10 @@ 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 `set[T]` of a user class stored as a struct when the type is declared, +including declarations nested inside other types. Use `list[T]` for these classes. +Sets of primitives and scalar-stored logical types such as `Path` and `UUID` are supported. + ```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 87f903309..06b5ac6aa 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -45,6 +45,11 @@ 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 refuses `set[T]` when `T` is a user class stored as an Arrow struct. +This includes ordinary dataclasses, `op.dataclass` classes and pydantic models, even when +the set is nested in another type or declared as a field. Use `list[T]` and supply the +items in the order you want stored. A canonical order for these sets is deferred. + ## `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..c38187b11 --- /dev/null +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -0,0 +1,12 @@ +## `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:** open +**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. + +Orcapod 0.4.0 refuses these sets at definition, including nested declarations, and directs +users to `list[T]`. The canonical storage order for these sets remains to be designed. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index acba19b4c..eab17ff1e 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -288,6 +288,9 @@ fields is not covered: a struct whose fields are in another order is another typ | `user class, exact (dataclass)` | kept | kept | refused | refused | | `user class, structural (orcapod.dataclass)` | kept | kept | refused | refused | +Orcapod 0.4.0 refuses declarations of sets of struct-stored user classes before storage. +Use `list[T]` for those classes. + ## Library value type | Type | in-memory | Delta | SQLite | PostgreSQL | diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 1867eb84b..d0ea6438d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1110,6 +1110,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 new `set[T]` declarations when `T` is a user class stored as a +struct. A canonical storage order for those elements is deferred. Use `list[T]` and +choose the element order before handing the list to Orcapod. + **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/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index f5d74dac2..a6b1a91e6 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -37,6 +37,7 @@ from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.semantic_types.canonical_order import canonical_python_value +from orcapod.semantic_types.nested_storage import require_supported_schema_sets from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils @@ -172,6 +173,10 @@ def _init_from_dict( data_columns[k] = v super().__init__(data_context=data_context or extracted_context) + if python_schema is not None: + require_supported_schema_sets( + python_schema, self.data_context.type_converter.get_logical_type + ) self._datagram_uuid = record_uuid self._data_dict: dict[str, DataValue] | None = data_columns diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 903dd3fd0..44228bb9a 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -59,6 +59,7 @@ from orcapod.errors import SourceSpecMismatchError, UnboundSourceError from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.logical_types.user_class_identity import equivalent_hints +from orcapod.semantic_types.nested_storage import require_supported_schema_sets from orcapod.system_constants import constants from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, Schema @@ -554,6 +555,8 @@ def __init__( label: str | None = None, config: OrcapodConfig | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, + *, + _from_saved: bool = False, ) -> None: super().__init__(label=label, data_context=data_context, config=config) if isinstance(tag_schema, pa.Schema) or isinstance(data_schema, pa.Schema): @@ -594,9 +597,11 @@ def __init__( # together (ITL-640). self._saved_arrow_texts: dict[str, Any] | None = None if arrow_schemas is None: - missing = _columns_without_arrow_type( - tag_schema, data_schema, self.data_context.type_converter - ) + converter = self.data_context.type_converter + if not _from_saved: + require_supported_schema_sets(tag_schema, converter.get_logical_type) + require_supported_schema_sets(data_schema, converter.get_logical_type) + missing = _columns_without_arrow_type(tag_schema, data_schema, converter) if missing: raise _no_arrow_type_error(name, missing) @@ -1603,6 +1608,8 @@ def from_stream( if isinstance(stream, SourceNodeBase) else typed_arrow_schemas(stream) ), + _from_saved=isinstance(stream, SourceNodeBase) + and stream._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another ) if isinstance(stream, SourceNodeBase): # A loaded job's slot keeps all its saved state (ITL-1138, ITL-640), @@ -1656,6 +1663,8 @@ def __init__( bound_source: StreamProtocol | None = None, data_context: str | contexts.DataContext | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, + *, + _from_saved: bool = False, ) -> None: from orcapod.pipeline.source_consistency import ( binding_dependency_error, @@ -1678,6 +1687,14 @@ def __init__( # source's types (CodeRabbit on PR 454). source_tag, source_data = typed_arrow_schemas(bound_source) converter = contexts.resolve_context(data_context).type_converter + if tag_schema is not None: + require_supported_schema_sets( + tag_schema, converter.get_logical_type + ) + if data_schema is not None: + require_supported_schema_sets( + data_schema, converter.get_logical_type + ) arrow_schemas = ( source_tag if tag_schema is None @@ -1696,6 +1713,7 @@ def __init__( data_schema=data_schema, data_context=data_context, arrow_schemas=arrow_schemas, + _from_saved=_from_saved, ) self._bound_source: StreamProtocol | None = None self._declared_form: _DeclaredForm | None = None @@ -2323,6 +2341,7 @@ def from_stream( tag_schema=stream.tag_schema, data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another + _from_saved=stream._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=stream.bound_source, ) node._take_saved_state_of(stream) @@ -2334,6 +2353,7 @@ def from_stream( tag_schema=stream.tag_schema, data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another + _from_saved=stream._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=None, ) node._take_saved_state_of(stream) @@ -2385,6 +2405,7 @@ def _from_loaded_slot( tag_schema=slot.tag_schema, data_schema=slot.data_schema, arrow_schemas=slot._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another + _from_saved=slot._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another ) node._take_saved_state_of(slot) if bound_source is not None: @@ -2402,6 +2423,7 @@ def as_node(self) -> SourceNode: tag_schema=self._tag_schema, data_schema=self._data_schema, arrow_schemas=self._given_arrow_schemas, + _from_saved=self._saved_arrow_texts is not None, ) node._take_saved_state_of(self) return node diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index a2f154dec..b6fdd7bb0 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -46,6 +46,7 @@ RowIdentifierError, SchemaInconsistencyError, ) +from orcapod.semantic_types.nested_storage import require_supported_schema_sets from orcapod.system_constants import constants from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils @@ -368,6 +369,9 @@ def __init__( {k: v for k, v in unified_schema.items() if k not in tag_cols_set} ) if self._declared_arrow is None: + require_supported_schema_sets( + unified_schema, self.data_context.type_converter.get_logical_type + ) self._declared_arrow = declared_arrow_schema( unified_schema, self.data_context.type_converter ) diff --git a/src/orcapod/logical_types/protocols.py b/src/orcapod/logical_types/protocols.py index 89e399622..177d8461e 100644 --- a/src/orcapod/logical_types/protocols.py +++ b/src/orcapod/logical_types/protocols.py @@ -26,6 +26,10 @@ class TypeConverterProtocol(Protocol): ``UniversalTypeConverter`` is the canonical implementation. """ + def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": + """Look up an existing logical type without synthesizing one.""" + ... + def register_python_class(self, annotation: Any) -> "pa.DataType": """Ensure a ``LogicalType`` is registered for ``annotation`` and return the Arrow column data type. diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 7f9578b3b..983ff1303 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -20,6 +20,7 @@ from __future__ import annotations import logging +from contextvars import ContextVar from typing import TYPE_CHECKING, Any import polars as pl @@ -34,7 +35,10 @@ require_restorable_none, with_context, ) -from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError +from orcapod.semantic_types.nested_storage import ( + NestedTypeNotStorableError, + require_supported_sets, +) from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, @@ -45,6 +49,9 @@ logger = logging.getLogger(__name__) +_reconstructing_user_class: ContextVar[bool] = ContextVar( + "_reconstructing_user_class", default=False +) # Extension type classes per (identity string, storage type, metadata). Two class objects # with one identity (a class defined again, two structural classes of one type) must @@ -282,6 +289,8 @@ def create_for_python_type( TypeError: If the class refers back to itself (directly or through other classes), naming the field path, or a field type cannot be stored. """ + if not _reconstructing_user_class.get(): + require_supported_sets(python_type, converter.get_logical_type) record = uci.class_record(python_type, converter) storage_type, field_annotations = self._storage(python_type, converter) identity = uci.identity_string(record) @@ -398,7 +407,13 @@ def reconstruct_from_arrow( raise except (TypeError, ValueError) as exc: raise TypeIdentityError(str(exc)) from exc - _ = converter.register_python_class(cls) + # Rebuilding an existing logical type uses the same factory registration + # as a new declaration, including registration of any nested classes. + token = _reconstructing_user_class.set(True) + try: + _ = converter.register_python_class(cls) + finally: + _reconstructing_user_class.reset(token) lt = converter.get_logical_type_for_python_type(cls) if not isinstance(lt, UserClassLogicalType): raise TypeIdentityError( diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 46937b262..5f845b9af 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -484,6 +484,7 @@ def load(cls, path: str | Path) -> "Pipeline": data_schema=data_schema, data_context=saved_context, arrow_schemas=arrow_schemas, + _from_saved=True, ) # The saved hashes, and the saved type text of a column whose # class this process has not registered yet (ITL-1138). diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 37ee98ba6..f22b30bb3 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -12,16 +12,111 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from collections.abc import Callable +import typing +from types import UnionType +from typing import TYPE_CHECKING, Any, get_args, get_origin if TYPE_CHECKING: import pyarrow as pa + from orcapod.logical_types.protocols import LogicalTypeProtocol + from orcapod.types import SchemaLike + _FOLLOW_UP = "ITL-1150" class NestedTypeNotStorableError(ValueError): - """A logical type is declared where storage cannot keep it (ITL-1150).""" + """A nested type is declared where storage cannot represent it faithfully.""" + + +def require_supported_sets( + annotation: object, + get_logical_type: Callable[[type], LogicalTypeProtocol | None], +) -> None: + """Refuse declared sets of struct-stored user classes (ITL-922). + + Args: + annotation: A declared Python type, possibly a nested container or union. + get_logical_type: Look up existing logical types without registering new ones. + + Raises: + NestedTypeNotStorableError: If a set has a struct-stored user class element. + """ + from orcapod.logical_types import user_class_identity as uci + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType + from orcapod.semantic_types.nested_none import with_context + + seen: set[type] = set() + + def visit(declared: object) -> None: + """Check a generic's arguments or the stored fields of a user class.""" + origin: object = get_origin(declared) + args: tuple[object, ...] = get_args(declared) + if origin is set and args: + element = args[0] + if get_origin(element) in (typing.Union, UnionType): + members = tuple( + arg for arg in get_args(element) if arg is not type(None) + ) + if len(members) == 1: + element = members[0] + if isinstance(element, type) and uci.class_kind(element) is not None: + import pyarrow as pa + + logical_type = get_logical_type(element) + if logical_type is None or pa.types.is_struct( + logical_type.get_arrow_extension_type().storage_type + ): + raise NestedTypeNotStorableError( + "Sets of user classes are not supported in this version. " + f"Use list[{element.__qualname__}] instead (ITL-922)." + ) + if origin in (list, set, dict, tuple, typing.Union, UnionType): + for arg in args: + visit(arg) + return + if ( + not isinstance(declared, type) + or declared in seen + or uci.class_kind(declared) is None + ): + return + seen.add(declared) + logical_type = get_logical_type(declared) + if logical_type is not None and not isinstance( + logical_type, UserClassLogicalType + ): + return + try: + hints = uci.type_hints(declared) + except ValueError: + # Class registration reports unresolved hints when it builds the type. + return + for name in uci.stored_field_names(declared): + field: object = hints.get(name, Any) + try: + visit(field) + except NestedTypeNotStorableError as exc: + raise with_context( + f"{declared.__qualname__}.{name} ({field})", exc + ) from exc + + visit(annotation) + + +def require_supported_schema_sets( + schema: SchemaLike, + get_logical_type: Callable[[type], LogicalTypeProtocol | None], +) -> None: + """Check set declarations in a Python schema, naming the affected column.""" + from orcapod.semantic_types.nested_none import with_context + + for name, annotation in schema.items(): + try: + require_supported_sets(annotation, get_logical_type) + except NestedTypeNotStorableError as exc: + raise with_context(f"Column {name!r} ({annotation})", exc) from exc def require_storable_in_struct_field(arrow_type: pa.DataType) -> None: diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 678270275..1f8a664b6 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -47,6 +47,7 @@ from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, require_storable_in_struct_field, + require_supported_sets, ) from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data from orcapod.types import DataType, Schema, SchemaLike @@ -334,6 +335,7 @@ def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: for schema in schemas: for name, annotation in schema.items(): try: + require_supported_sets(annotation, self.get_logical_type) self._register_annotation(annotation) except ( NestedNoneNotRestorableError, diff --git a/tests/test_logical_types/test_nested_logical_type_refusal.py b/tests/test_logical_types/test_nested_logical_type_refusal.py index 63b22d468..7bc8597fb 100644 --- a/tests/test_logical_types/test_nested_logical_type_refusal.py +++ b/tests/test_logical_types/test_nested_logical_type_refusal.py @@ -29,8 +29,12 @@ import pytest import orcapod as op +from orcapod.contexts import get_default_context +from orcapod.core.datagrams import Data from orcapod.databases import InMemoryArrowDatabase +from orcapod.logical_types.protocols import TypeConverterProtocol from orcapod.operators import MapData +from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError from orcapod.sources import DictSource # A declared type whose value would not read back as declared -> one value of it. @@ -165,12 +169,82 @@ def test_the_refusal_says_how_to_keep_the_value() -> None: assert "dict[str, list[int]]" in message +@dataclasses.dataclass(frozen=True) +class SetPoint: + x: int + + +@op.dataclass(frozen=True) +class StructuralSetPoint: + x: int + + +class ModelSetPoint(pydantic.BaseModel, frozen=True): + x: int + + +@dataclasses.dataclass +class HoldsPointSet: + points: set[SetPoint] + + +@pytest.mark.parametrize("point_type", [SetPoint, StructuralSetPoint, ModelSetPoint]) +def test_a_source_rejects_sets_of_user_classes(point_type: type) -> None: + with pytest.raises( + NestedTypeNotStorableError, + match=rf"'points'.*Use list\[{point_type.__name__}\]", + ): + _ = DictSource( + [{"points": set()}], + data_schema={"points": set[point_type]}, + source_id="user_class_set", + ) + + +@pytest.mark.parametrize( + "declared", + [ + list[set[SetPoint]], + set[SetPoint] | None, + dict[str, set[SetPoint]], + HoldsPointSet, + ], +) +def test_data_rejects_nested_sets_in_the_declared_schema(declared: Any) -> None: + with pytest.raises( + NestedTypeNotStorableError, match=r"'points'.*Use list\[SetPoint\]" + ): + _ = Data({"points": None}, python_schema={"points": declared}) + + +def test_registering_a_class_rejects_a_set_field() -> None: + converter = get_default_context().type_converter + assert isinstance(converter, TypeConverterProtocol) + with pytest.raises( + NestedTypeNotStorableError, match=r"HoldsPointSet\.points.*Use list\[SetPoint\]" + ): + _ = converter.register_python_class(HoldsPointSet) + + +def test_a_pod_rejects_a_set_of_user_classes_at_definition() -> None: + with pytest.raises( + NestedTypeNotStorableError, match=r"'got'.*Use list\[SetPoint\]" + ): + _consumer(set[SetPoint]) + with pytest.raises( + NestedTypeNotStorableError, match=r"'out'.*Use list\[SetPoint\]" + ): + _producer(set[SetPoint], set()) + + # --------------------------------------------------------------------------- # Accepted: the positions that keep the declared type # --------------------------------------------------------------------------- ACCEPTED: dict[str, tuple[Any, Any]] = { "set_int": (set[int], {3, 1, 2}), + "set_path": (set[Path], {Path("/a"), Path("/b")}), + "list_of_user_classes": (list[SetPoint], [SetPoint(2), SetPoint(1)]), "list_of_sets": (list[set[int]], [{2, 1}, {3}]), "list_of_paths": (list[Path], [Path("/a"), Path("/b")]), "dict_of_lists": (dict[str, list[int]], {"a": [2, 1]}), diff --git a/tests/test_user_types/test_structural_dataclass.py b/tests/test_user_types/test_structural_dataclass.py index 23227d932..b1bbf5e0d 100644 --- a/tests/test_user_types/test_structural_dataclass.py +++ b/tests/test_user_types/test_structural_dataclass.py @@ -643,12 +643,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"]))) @@ -687,8 +687,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) """ @@ -716,8 +715,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], } ] From cbe2329f9f10e75dafe96c2c83c39317d5ff08c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:07:39 -0800 Subject: [PATCH 02/20] docs(database): generate the user-class set restriction --- docs/reference/database-types.md | 6 +++--- tests/test_databases/type_matrix.py | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index eab17ff1e..a342d5823 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 declarations of sets of struct-stored user classes before 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 @@ -288,9 +291,6 @@ fields is not covered: a struct whose fields are in another order is another typ | `user class, exact (dataclass)` | kept | kept | refused | refused | | `user class, structural (orcapod.dataclass)` | kept | kept | refused | refused | -Orcapod 0.4.0 refuses declarations of sets of struct-stored user classes before storage. -Use `list[T]` for those classes. - ## Library value type | Type | in-memory | Delta | SQLite | PostgreSQL | diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index ef47aba82..158d39d68 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 declarations of sets of struct-stored user classes before 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 From 4be401a6a8417b75eb7b1653bf88c341531d5595 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:35:49 -0800 Subject: [PATCH 03/20] docs(schema): track deferred user-class set ordering --- changelog.d/ITL-922.md | 3 ++- docs/concepts/your-own-data-types.md | 2 +- docs/reference/hashing.md | 4 ++-- src/orcapod/semantic_types/nested_storage.py | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 0af38aebe..429e3d014 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -2,4 +2,5 @@ - Orcapod rejects declarations of sets of struct-stored user classes, including ordinary dataclasses, pydantic models and `orcapod.dataclass` classes. Use `list[T]` and supply the - elements in the order you want stored. Canonical ordering for these sets is deferred. + elements in the order you want stored. Canonical ordering for these sets is deferred to + ITL-1691. diff --git a/docs/concepts/your-own-data-types.md b/docs/concepts/your-own-data-types.md index 06b5ac6aa..425dc9dac 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -48,7 +48,7 @@ constructs a model. Orcapod 0.4.0 refuses `set[T]` when `T` is a user class stored as an Arrow struct. This includes ordinary dataclasses, `op.dataclass` classes and pydantic models, even when the set is nested in another type or declared as a field. Use `list[T]` and supply the -items in the order you want stored. A canonical order for these sets is deferred. +items in the order you want stored. A canonical order for these sets is deferred to ITL-1691. ## `op.dataclass` in a notebook diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index d0ea6438d..3a2275fbc 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1111,8 +1111,8 @@ of affected inputs, and changing storage order would move row hashes and what a by this rule. Orcapod 0.4.0 refuses new `set[T]` declarations when `T` is a user class stored as a -struct. A canonical storage order for those elements is deferred. Use `list[T]` and -choose the element order before handing the list to Orcapod. +struct. A canonical storage order for those elements is deferred to ITL-1691. Use +`list[T]` and choose the element order before handing the list to Orcapod. **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/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index f22b30bb3..b61537d73 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -70,7 +70,7 @@ def visit(declared: object) -> None: ): raise NestedTypeNotStorableError( "Sets of user classes are not supported in this version. " - f"Use list[{element.__qualname__}] instead (ITL-922)." + f"Use list[{element.__qualname__}] instead." ) if origin in (list, set, dict, tuple, typing.Union, UnionType): for arg in args: From 21223299f2ee07e3b7a8baaf38e3b6886a1f5a8a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:06:17 -0800 Subject: [PATCH 04/20] fix(schema): limit user-class set checks to declarations --- .zed/rules | 4 +- CLAUDE.md | 4 +- docs/concepts/logical-type-identifiers.md | 2 + src/orcapod/core/cached_function_pod.py | 8 +- src/orcapod/core/data_function.py | 25 +- src/orcapod/core/datagrams/datagram.py | 31 +- src/orcapod/core/datagrams/tag_data.py | 75 +++-- src/orcapod/core/function_pod.py | 34 ++- src/orcapod/core/nodes/source_node.py | 70 +++-- src/orcapod/core/sources/dict_source.py | 13 + src/orcapod/core/sources/list_source.py | 9 + src/orcapod/core/sources/polling_source.py | 23 +- .../list_logical_type_factory.py | 2 +- src/orcapod/logical_types/protocols.py | 16 +- .../logical_types/user_class_identity.py | 2 +- .../logical_types/user_class_logical_type.py | 25 +- src/orcapod/pipeline/graph.py | 5 +- src/orcapod/semantic_types/nested_storage.py | 100 ++++--- .../semantic_types/universal_converter.py | 52 ++-- src/orcapod/utils/schema_utils.py | 4 +- .../test_user_class_set_declarations.py | 269 ++++++++++++++++++ 21 files changed, 600 insertions(+), 173 deletions(-) create mode 100644 tests/test_logical_types/test_user_class_set_declarations.py diff --git a/.zed/rules b/.zed/rules index 1360e0a66..069fc28ef 100644 --- a/.zed/rules +++ b/.zed/rules @@ -472,7 +472,9 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 only the declared class fields enter storage. Unrelated look-alike classes are refused. - For 0.4.0, refuse `set[T]` of a struct-stored user class at definition, including nested declarations (`nested_storage.require_supported_sets`, ITL-922). Name the column or field - and direct users to `list[T]`. Canonical ordering for those sets is deferred. + and direct users to `list[T]`. Resolve storage through the active converter and its + factories. Run the guard once at a user declaration. Inferred, converted and restored + schemas go through their existing storage paths. Canonical ordering is deferred. - 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 the extension metadata; together they are the logical type identifier. A nested diff --git a/CLAUDE.md b/CLAUDE.md index 27d2bf071..7c3e4c37b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -483,7 +483,9 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 only the declared class fields enter storage. Unrelated look-alike classes are refused. - For 0.4.0, refuse `set[T]` of a struct-stored user class at definition, including nested declarations (`nested_storage.require_supported_sets`, ITL-922). Name the column or field - and direct users to `list[T]`. Canonical ordering for those sets is deferred. + and direct users to `list[T]`. Resolve storage through the active converter and its + factories. Run the guard once at a user declaration. Inferred, converted and restored + schemas go through their existing storage paths. Canonical ordering is deferred. - 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 the extension metadata; together they are the logical type identifier. A nested diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index a8fd12971..ecfcb2ee1 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -153,6 +153,8 @@ name names is refused with `LogicalTypeIdentifierError`. Orcapod 0.4.0 refuses `set[T]` of a user class stored as a struct when the type is declared, including declarations nested inside other types. Use `list[T]` for these classes. Sets of primitives and scalar-stored logical types such as `Path` and `UUID` are supported. +The declaration rule uses the storage type selected by the registered logical type or factory. +Existing Arrow data and saved schemas can still be read. ```python from orcapod.sources import DictSource diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 30c1d0570..a1c31f83e 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -243,12 +243,12 @@ def process_data( ) if output is not None: pf = self._function_pod.data_function - var_dg = Datagram( + var_dg = Datagram._from_typed_dict( pf.get_function_variation_data(), python_schema=pf.get_function_variation_data_schema(), data_context=pf.data_context, ) - exec_dg = Datagram( + exec_dg = Datagram._from_typed_dict( pf.get_execution_data(), python_schema=pf.get_execution_data_schema(), data_context=pf.data_context, @@ -312,12 +312,12 @@ async def _async_compute_and_store( ) if output is not None: pf = self._function_pod.data_function - var_dg = Datagram( + var_dg = Datagram._from_typed_dict( pf.get_function_variation_data(), python_schema=pf.get_function_variation_data_schema(), data_context=pf.data_context, ) - exec_dg = Datagram( + exec_dg = Datagram._from_typed_dict( pf.get_execution_data(), python_schema=pf.get_execution_data_schema(), data_context=pf.data_context, diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 286c6a0ea..8192f7c3b 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -52,6 +52,11 @@ check_conformance, normalize_output_numbers, ) +from orcapod.semantic_types.nested_storage import ( + build_from_existing, + checking_declarations, + require_supported_sets, +) from orcapod.types import ContentHash, DataValue, Schema, SchemaLike from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names @@ -919,6 +924,13 @@ def __init__( output_typespec=output_schema, ) + if checking_declarations(): + require_supported_sets( + self.data_context.type_converter.get_logical_type_for_python_type, + self._input_schema, + self._output_schema, + ) + # get git info for the function # TODO: turn this into optional addition env_info = get_git_info_for_python_object(self._function, try_cwd=True) @@ -1106,7 +1118,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: source_info = output_source_info(self.uri, new_record_uuid.hex, output_data) if not output_data: - return Data( + return Data._from_function_output( output_data, source_info=source_info, record_uuid=new_record_uuid, @@ -1122,7 +1134,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: ) for key, value in output_data.items() } - return Data( + return Data._from_function_output( normalized, python_schema=output_schema, source_info=source_info, @@ -1418,9 +1430,10 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": import importlib inner = config.get("config", config) - module = importlib.import_module(inner["module_path"]) + module = build_from_existing(importlib.import_module, inner["module_path"]) func = getattr(module, inner["callable_name"]) - return cls( + return build_from_existing( + cls, function=func, output_keys=inner.get("output_keys"), version=inner.get("version", "v0.0"), @@ -1627,12 +1640,12 @@ def result_database(self) -> ArrowDatabaseProtocol: def _build_metadata_datagrams(self) -> tuple[Datagram, Datagram]: """Build variation and execution Datagrams for cache storage.""" - variation_datagram = Datagram( + variation_datagram = Datagram._from_typed_dict( self.get_function_variation_data(), python_schema=self.get_function_variation_data_schema(), data_context=self.data_context, ) - execution_datagram = Datagram( + execution_datagram = Datagram._from_typed_dict( self.get_execution_data(), python_schema=self.get_execution_data_schema(), data_context=self.data_context, diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index a6b1a91e6..c38ace605 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -37,7 +37,10 @@ from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.semantic_types.canonical_order import canonical_python_value -from orcapod.semantic_types.nested_storage import require_supported_schema_sets +from orcapod.semantic_types.nested_storage import ( + checking_declarations, + require_supported_sets, +) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils @@ -151,6 +154,28 @@ def __init__( data, python_schema, meta_info, data_context, record_uuid ) + if python_schema is not None and checking_declarations(): + self._check_declared_schema(python_schema) + + def _check_declared_schema(self, python_schema: SchemaLike) -> None: + """Validate a Python schema passed to a public constructor.""" + require_supported_sets( + self.data_context.type_converter.get_logical_type_for_python_type, + python_schema, + ) + + @classmethod + def _from_typed_dict( + cls, + data: Mapping[str, DataValue], + python_schema: SchemaLike, + data_context: str | contexts.DataContext | None = None, + ) -> Self: + """Build a datagram with its already established Python types.""" + datagram = cls.__new__(cls) + datagram._init_from_dict(data, python_schema, None, data_context, None) + return datagram + def _init_from_dict( self, data: Mapping[str, DataValue], @@ -173,10 +198,6 @@ def _init_from_dict( data_columns[k] = v super().__init__(data_context=data_context or extracted_context) - if python_schema is not None: - require_supported_schema_sets( - python_schema, self.data_context.type_converter.get_logical_type - ) self._datagram_uuid = record_uuid self._data_dict: dict[str, DataValue] | None = data_columns diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 15a2a086f..39e5da187 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -27,6 +27,7 @@ from orcapod.core.datagrams.datagram import Datagram, context_key_field from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants +from orcapod.semantic_types.nested_storage import checking_declarations from orcapod.types import ( ColumnConfig, ContentHash, @@ -39,6 +40,7 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: + from orcapod.config import OrcapodConfig from orcapod.protocols.core_protocols import DataProtocol logger = logging.getLogger(__name__) @@ -97,6 +99,7 @@ def __init__( # self._data_table (same pattern as the legacy ArrowTag). super().__init__( data, + python_schema=python_schema, meta_info=meta_info, data_context=data_context, record_uuid=record_uuid, @@ -337,7 +340,7 @@ def as_datagram( ) -> Datagram: data = self.as_dict(columns=columns, all_info=all_info) python_schema = self.schema(columns=columns, all_info=all_info) - return Datagram( + return Datagram._from_typed_dict( data, python_schema=python_schema, data_context=self._data_context ) @@ -414,7 +417,7 @@ class Data(Datagram): input are automatically extracted. """ - def __init__( + def __init__( # pyright: ignore[reportMissingSuperCall] # the unchecked initializer also builds function outputs self, data: "Mapping[str, DataValue] | pa.Table | pa.RecordBatch", meta_info: "Mapping[str, DataValue] | None" = None, @@ -424,6 +427,46 @@ def __init__( record_uuid: "uuid.UUID | None" = None, **kwargs, ) -> None: + self._init_data( + data, + meta_info, + source_info, + python_schema, + data_context, + record_uuid, + **kwargs, + ) + if python_schema is not None and checking_declarations(): + self._check_declared_schema(python_schema) + + @classmethod + def _from_function_output( + cls, + data: "Mapping[str, DataValue]", + python_schema: "SchemaLike", + source_info: "Mapping[str, SourceInfoValue]", + record_uuid: "uuid.UUID", + data_context: "contexts.DataContext", + ) -> Self: + """Build a function output using the function's established schema.""" + row = cls.__new__(cls) + row._init_data( + data, None, source_info, python_schema, data_context, record_uuid + ) + return row + + def _init_data( + self, + data: "Mapping[str, DataValue] | pa.Table | pa.RecordBatch", + meta_info: "Mapping[str, DataValue] | None" = None, + source_info: "Mapping[str, SourceInfoValue] | None" = None, + python_schema: "SchemaLike | None" = None, + data_context: "str | contexts.DataContext | None" = None, + record_uuid: "uuid.UUID | None" = None, + *, + config: "OrcapodConfig | None" = None, + ) -> None: + """Initialize a data row and split off its source info.""" import pyarrow as _pa if isinstance(data, _pa.RecordBatch): @@ -443,13 +486,7 @@ def __init__( } data_table, si_table = self._data_and_source_info_tables(data, source_info) - super().__init__( - data_table, - meta_info=meta_info, - data_context=data_context, - record_uuid=record_uuid, - **kwargs, - ) + self._init_from_table(data_table, meta_info, data_context, record_uuid) self._source_info: dict[str, SourceInfoValue] = self._source_info_of_row( si_table ) @@ -469,13 +506,8 @@ def __init__( for k, v in data.items() if k.startswith(constants.SOURCE_PREFIX) } - super().__init__( - data_only, - python_schema=python_schema, - meta_info=meta_info, - data_context=data_context, - record_uuid=record_uuid, - **kwargs, + self._init_from_dict( + data_only, python_schema, meta_info, data_context, record_uuid ) self._source_info = {**contained_source_info, **(source_info or {})} @@ -1047,7 +1079,7 @@ def as_datagram( ) -> Datagram: data = self.as_dict(columns=columns, all_info=all_info) python_schema = self.schema(columns=columns, all_info=all_info) - return Datagram( + return Datagram._from_typed_dict( data=data, python_schema=python_schema, data_context=self._data_context ) @@ -1183,7 +1215,7 @@ class EmptyData(Data): record_uuid: Optional explicit UUID for this token. """ - def __init__( + def __init__( # pyright: ignore[reportMissingSuperCall] # a cached token carries an already established output schema self, cached_content_hash: ContentHash | None = None, source_info: "Mapping[str, SourceInfoValue] | None" = None, @@ -1192,12 +1224,7 @@ def __init__( record_uuid: uuid.UUID | None = None, ) -> None: # Initialise the parent with an empty dict — no payload columns. - super().__init__( - {}, - python_schema=python_schema, - data_context=data_context, - record_uuid=record_uuid, - ) + self._init_data({}, None, None, python_schema, data_context, record_uuid) self._cached_content_hash: ContentHash | None = cached_content_hash self._source_info = dict(source_info or {}) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index fd8910acb..27492f261 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -23,7 +23,11 @@ from orcapod.config import OrcapodConfig import orcapod.core.row_ids as row_ids from orcapod.core.base import TraceableBase -from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.data_function import ( + CachedDataFunction, + DataFunctionBase, + PythonDataFunction, +) from orcapod.core.datagrams import Data from orcapod.core.data_tags import ( materialization_diagnostic_off, @@ -67,6 +71,11 @@ from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants +from orcapod.semantic_types.nested_storage import ( + build_from_existing, + checking_declarations, + require_supported_sets, +) from orcapod.types import ( ColumnConfig, PipelineConfig, @@ -126,6 +135,8 @@ def __init__( data_context: str | contexts.DataContext | None = None, config: OrcapodConfig | None = None, ctx_arg_name: str | None = None, + *, + declare_schema: bool = False, ) -> None: super().__init__( label=label, @@ -146,6 +157,17 @@ def __init__( f"(schema keys: {list(data_function.input_data_schema.keys())})" ) self._ctx_arg_name: str | None = ctx_arg_name + if declare_schema and checking_declarations(): + context = ( + data_function.data_context + if isinstance(data_function, DataFunctionBase) + else self.data_context + ) + require_supported_sets( + context.type_converter.get_logical_type_for_python_type, + self.input_data_schema, + data_function.output_data_schema, + ) # Register types for schema validation, excluding ctx (not a data column). self.data_context.type_converter.ensure_types_registered_for_schemas( self.input_data_schema, @@ -935,6 +957,7 @@ def __init__( super().__init__( data_function, ctx_arg_name=ctx_arg_name, + declare_schema=True, **kwargs, ) self._pod_config = pod_config or PodConfig() @@ -974,7 +997,8 @@ def from_fn( Returns: A new ``FunctionPod``. """ - data_function = PythonDataFunction( + data_function = build_from_existing( + PythonDataFunction, fn, output_keys=output_keys, function_name=name or getattr(fn, "__name__", "unknown"), @@ -1102,7 +1126,8 @@ def from_config( if config.get("pod_config") is not None: pod_config = PodConfig(**config["pod_config"]) - return cls( + return build_from_existing( + cls, data_function=data_function, pod_config=pod_config, ctx_arg_name=config.get("ctx_arg_name"), @@ -1976,7 +2001,8 @@ def decorator(func: Callable) -> CallableWithPodProtocol: if func.__name__ == "": raise ValueError("Lambda functions cannot be used with function_pod") - data_function = PythonDataFunction( + data_function = build_from_existing( + PythonDataFunction, func, output_keys=output_keys, function_name=function_name or func.__name__, diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5bc50d08e..76bedcb60 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -62,7 +62,11 @@ from orcapod.errors import SourceSpecMismatchError, UnboundSourceError from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.logical_types.user_class_identity import equivalent_hints -from orcapod.semantic_types.nested_storage import require_supported_schema_sets +from orcapod.semantic_types.nested_storage import ( + build_from_existing, + checking_declarations, + require_supported_sets, +) from orcapod.system_constants import constants from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, Schema @@ -558,8 +562,6 @@ def __init__( label: str | None = None, config: OrcapodConfig | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, - *, - _from_saved: bool = False, ) -> None: super().__init__(label=label, data_context=data_context, config=config) if isinstance(tag_schema, pa.Schema) or isinstance(data_schema, pa.Schema): @@ -583,6 +585,12 @@ def __init__( arrow_schemas = (tag_schema, data_schema) tag_schema = Schema(converter.arrow_schema_to_python_schema(tag_schema)) data_schema = Schema(converter.arrow_schema_to_python_schema(data_schema)) + elif checking_declarations(): + require_supported_sets( + self.data_context.type_converter.get_logical_type_for_python_type, + tag_schema, + data_schema, + ) self._name = name self._tag_schema = tag_schema self._data_schema = data_schema @@ -601,9 +609,6 @@ def __init__( self._saved_arrow_texts: dict[str, Any] | None = None if arrow_schemas is None: converter = self.data_context.type_converter - if not _from_saved: - require_supported_schema_sets(tag_schema, converter.get_logical_type) - require_supported_schema_sets(data_schema, converter.get_logical_type) missing = _columns_without_arrow_type(tag_schema, data_schema, converter) if missing: raise _no_arrow_type_error(name, missing) @@ -1602,7 +1607,8 @@ def from_stream( slot_name = name if name is not None else slot_name_for(stream) if not isinstance(stream, SourceNodeBase): _require_stream_arrow_types(stream, slot_name) - node = cls( + node = build_from_existing( + cls, name=slot_name, tag_schema=tag_schema, data_schema=data_schema, @@ -1611,8 +1617,6 @@ def from_stream( if isinstance(stream, SourceNodeBase) else typed_arrow_schemas(stream) ), - _from_saved=isinstance(stream, SourceNodeBase) - and stream._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another ) if isinstance(stream, SourceNodeBase): # A loaded job's slot keeps all its saved state (ITL-1138, ITL-640), @@ -1658,7 +1662,7 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): *bound_source* is ``None``. """ - def __init__( + def __init__( # pyright: ignore[reportMissingSuperCall] # passes the base initializer schemas already checked here self, name: str, tag_schema: Schema | None = None, @@ -1666,8 +1670,6 @@ def __init__( bound_source: StreamProtocol | None = None, data_context: str | contexts.DataContext | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, - *, - _from_saved: bool = False, ) -> None: from orcapod.pipeline.source_consistency import ( binding_dependency_error, @@ -1676,6 +1678,19 @@ def __init__( if (dependency := independent_source_dependency(bound_source)) is not None: raise binding_dependency_error(dependency, name) + if checking_declarations(): + declared_schemas = tuple( + schema + for schema in (tag_schema, data_schema) + if schema is not None and not isinstance(schema, pa.Schema) + ) + if declared_schemas: + require_supported_sets( + contexts.resolve_context( + data_context + ).type_converter.get_logical_type_for_python_type, + *declared_schemas, + ) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1690,14 +1705,6 @@ def __init__( # source's types (CodeRabbit on PR 454). source_tag, source_data = typed_arrow_schemas(bound_source) converter = contexts.resolve_context(data_context).type_converter - if tag_schema is not None: - require_supported_schema_sets( - tag_schema, converter.get_logical_type - ) - if data_schema is not None: - require_supported_schema_sets( - data_schema, converter.get_logical_type - ) arrow_schemas = ( source_tag if tag_schema is None @@ -1710,13 +1717,13 @@ def __init__( tag_schema = derived_tag if data_schema is None: data_schema = derived_data - super().__init__( + build_from_existing( + super().__init__, name=name, tag_schema=tag_schema, data_schema=data_schema, data_context=data_context, arrow_schemas=arrow_schemas, - _from_saved=_from_saved, ) self._bound_source: StreamProtocol | None = None self._declared_form: _DeclaredForm | None = None @@ -2339,24 +2346,24 @@ def from_stream( # Case 1: copy — preserve bound_source, do NOT wrap the SJN itself. # The copy states the slot's Arrow schemas from the start: its bound # source is validated against them as it is constructed (ITL-640). - node = cls( + node = build_from_existing( + cls, name=name if name is not None else stream.name, tag_schema=stream.tag_schema, data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another - _from_saved=stream._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=stream.bound_source, ) node._take_saved_state_of(stream) return node case SourceNode(): # Case 2: unbound — schema placeholder; SJN hash = SourceNode hash. - node = cls( + node = build_from_existing( + cls, name=name if name is not None else stream.name, tag_schema=stream.tag_schema, data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another - _from_saved=stream._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=None, ) node._take_saved_state_of(stream) @@ -2378,7 +2385,8 @@ def from_stream( tag_schema, data_schema = stream.output_schema() slot_name = name if name is not None else slot_name_for(stream) _require_stream_arrow_types(stream, slot_name) - return cls( + return build_from_existing( + cls, name=slot_name, tag_schema=tag_schema, data_schema=data_schema, @@ -2403,12 +2411,12 @@ def _from_loaded_slot( Raises: SourceSpecMismatchError: If *bound_source* does not fit the slot. """ - node = cls( + node = build_from_existing( + cls, name=slot.name, tag_schema=slot.tag_schema, data_schema=slot.data_schema, arrow_schemas=slot._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another - _from_saved=slot._saved_arrow_texts is not None, # pyright: ignore[reportPrivateUsage] # one slot copied into another ) node._take_saved_state_of(slot) if bound_source is not None: @@ -2421,12 +2429,12 @@ def as_node(self) -> SourceNode: Returns: A new ``SourceNode`` with the same name and schemas. """ - node = SourceNode( + node = build_from_existing( + SourceNode, name=self._name, tag_schema=self._tag_schema, data_schema=self._data_schema, arrow_schemas=self._given_arrow_schemas, - _from_saved=self._saved_arrow_texts is not None, ) node._take_saved_state_of(self) return node diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 26eefb169..26ec41064 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -10,6 +10,10 @@ float32_column_names, warn_first_python_float, ) +from orcapod.semantic_types.nested_storage import ( + checking_declarations, + require_supported_sets, +) from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, @@ -64,6 +68,15 @@ def __init__( **kwargs: Any, ) -> None: super().__init__(source_id=source_id, **kwargs) + if ( + data_schema is not None + and not isinstance(data_schema, pa.Schema) + and checking_declarations() + ): + require_supported_sets( + self.data_context.type_converter.get_logical_type_for_python_type, + data_schema, + ) tag_columns = _normalize_column_list(tag_columns) # Read the first input row before its origin is erased by dict(row). diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 1433cbc71..69ece78d0 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -9,6 +9,10 @@ float32_column_names, warn_first_python_float, ) +from orcapod.semantic_types.nested_storage import ( + checking_declarations, + require_supported_sets, +) from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, @@ -84,6 +88,11 @@ def __init__( **kwargs: Passed on to ``RootSource``. """ super().__init__(source_id=source_id, **kwargs) + if data_schema is not None and checking_declarations(): + require_supported_sets( + self.data_context.type_converter.get_logical_type_for_python_type, + data_schema, + ) self.name = name self._elements = list(data) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 54caf84de..e53ee4dcb 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -47,7 +47,11 @@ RowIdentifierError, SchemaInconsistencyError, ) -from orcapod.semantic_types.nested_storage import require_supported_schema_sets +from orcapod.semantic_types.nested_storage import ( + build_from_existing, + checking_declarations, + require_supported_sets, +) from orcapod.system_constants import constants from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils @@ -370,9 +374,11 @@ def __init__( {k: v for k, v in unified_schema.items() if k not in tag_cols_set} ) if self._declared_arrow is None: - require_supported_schema_sets( - unified_schema, self.data_context.type_converter.get_logical_type - ) + if checking_declarations(): + require_supported_sets( + self.data_context.type_converter.get_logical_type_for_python_type, + unified_schema, + ) self._declared_arrow = declared_arrow_schema( unified_schema, self.data_context.type_converter ) @@ -755,7 +761,7 @@ def from_config( """ import importlib - module = importlib.import_module(config["impl_module"]) + module = build_from_existing(importlib.import_module, config["impl_module"]) # Walk dotted qualname to support nested classes (e.g. "Outer.Inner") impl_class: Any = module for part in config["impl_class"].split("."): @@ -763,14 +769,15 @@ def from_config( impl_config = config.get("impl_config") if impl_config is None: - impl = impl_class() + impl = build_from_existing(impl_class) else: - impl = impl_class.from_config(impl_config) + impl = build_from_existing(impl_class.from_config, impl_config) polling_config = PollingConfig(**config.get("polling_config", {})) return cls._from_saved_name( config, - lambda name: cls( + lambda name: build_from_existing( + cls, impl=impl, tag_columns=config["tag_columns"], polling_config=polling_config, diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index accb1f88a..69975b29b 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -487,7 +487,7 @@ def create_for_python_type( # A set of a plain Arrow type is a native container too (ITL-611). Its # element Python type is that of the element Arrow type, as on the read # path, never the annotation (``Literal[1, 2]`` reads as ``int``). - element_arrow_type = converter.register_python_class(element_annotation) + element_arrow_type = converter._register_python_class(element_annotation) return ListLogicalType( ArrowElement( converter.arrow_type_to_python_type(element_arrow_type), diff --git a/src/orcapod/logical_types/protocols.py b/src/orcapod/logical_types/protocols.py index 177d8461e..96f25561f 100644 --- a/src/orcapod/logical_types/protocols.py +++ b/src/orcapod/logical_types/protocols.py @@ -9,6 +9,7 @@ from __future__ import annotations +from contextvars import ContextVar from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.types import DataType @@ -18,6 +19,13 @@ import pyarrow as pa +# Share cycle detection with factory callbacks. An active resolution has already +# passed its declaration check, or was requested by storage without one. +python_type_resolution: ContextVar[set[type] | None] = ContextVar( + "python_type_resolution", default=None +) + + @runtime_checkable class TypeConverterProtocol(Protocol): """Minimal protocol exposing what factories and logical types need from the converter. @@ -26,10 +34,6 @@ class TypeConverterProtocol(Protocol): ``UniversalTypeConverter`` is the canonical implementation. """ - def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": - """Look up an existing logical type without synthesizing one.""" - ... - def register_python_class(self, annotation: Any) -> "pa.DataType": """Ensure a ``LogicalType`` is registered for ``annotation`` and return the Arrow column data type. @@ -54,6 +58,10 @@ def register_python_class(self, annotation: Any) -> "pa.DataType": """ ... + def _register_python_class(self, annotation: Any) -> "pa.DataType": + """Resolve a Python type for conversion or restoration.""" + ... + def register_storage_type(self, arrow_type: "pa.DataType") -> "pa.DataType": """Traverse an Arrow type bottom-up, registering extension types, and return a storage-safe type. diff --git a/src/orcapod/logical_types/user_class_identity.py b/src/orcapod/logical_types/user_class_identity.py index c18a9a0b8..dc6bc9d41 100644 --- a/src/orcapod/logical_types/user_class_identity.py +++ b/src/orcapod/logical_types/user_class_identity.py @@ -497,7 +497,7 @@ def _type_token( if isinstance(annotation, type) and origin is None: if class_kind(annotation) is not None: return {"class": class_record(annotation, converter, path)} - _ = converter.register_python_class(annotation) # raises for unsupported types + _ = converter._register_python_class(annotation) # raises for unsupported types lt = converter.get_logical_type_for_python_type(annotation) if lt is not None: return {"logical": logical_type_identifier(lt).text} diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 983ff1303..0c27b6284 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -20,7 +20,6 @@ from __future__ import annotations import logging -from contextvars import ContextVar from typing import TYPE_CHECKING, Any import polars as pl @@ -30,6 +29,7 @@ import orcapod.logical_types.user_class_identity as uci from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.structural_class import class_for_record +from orcapod.logical_types.protocols import python_type_resolution from orcapod.semantic_types.nested_none import ( NestedNoneNotRestorableError, require_restorable_none, @@ -37,6 +37,7 @@ ) from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, + checking_declarations, require_supported_sets, ) from orcapod.logical_types.registry import ( @@ -49,10 +50,6 @@ logger = logging.getLogger(__name__) -_reconstructing_user_class: ContextVar[bool] = ContextVar( - "_reconstructing_user_class", default=False -) - # Extension type classes per (identity string, storage type, metadata). Two class objects # with one identity (a class defined again, two structural classes of one type) must # give Arrow types that compare equal, and pyarrow compares the type's Python class. @@ -289,8 +286,12 @@ def create_for_python_type( TypeError: If the class refers back to itself (directly or through other classes), naming the field path, or a field type cannot be stored. """ - if not _reconstructing_user_class.get(): - require_supported_sets(python_type, converter.get_logical_type) + # A direct factory call declares a class. A converter dispatch is + # resolving a type for either an already-checked declaration or storage. + if python_type_resolution.get() is None and checking_declarations(): + require_supported_sets( + converter.get_logical_type_for_python_type, annotation=python_type + ) record = uci.class_record(python_type, converter) storage_type, field_annotations = self._storage(python_type, converter) identity = uci.identity_string(record) @@ -329,7 +330,7 @@ def _storage( for field_name in uci.stored_field_names(python_type): annotation = hints.get(field_name, Any) try: - arrow_type = converter.register_python_class(annotation) + arrow_type = converter._register_python_class(annotation) # A field is a nested position: its None must be readable (ITL-1144). require_restorable_none( annotation, @@ -407,13 +408,7 @@ def reconstruct_from_arrow( raise except (TypeError, ValueError) as exc: raise TypeIdentityError(str(exc)) from exc - # Rebuilding an existing logical type uses the same factory registration - # as a new declaration, including registration of any nested classes. - token = _reconstructing_user_class.set(True) - try: - _ = converter.register_python_class(cls) - finally: - _reconstructing_user_class.reset(token) + _ = converter._register_python_class(cls) lt = converter.get_logical_type_for_python_type(cls) if not isinstance(lt, UserClassLogicalType): raise TypeIdentityError( diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 5f845b9af..5161d3778 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -345,6 +345,7 @@ def load(cls, path: str | Path) -> "Pipeline": ) from orcapod.core.nodes import FunctionNode, OperatorNode from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass + from orcapod.semantic_types.nested_storage import build_from_existing from orcapod.types import Schema path = Path(path) @@ -478,13 +479,13 @@ def load(cls, path: str | Path) -> "Pipeline": ) except (ValueError, TypeError, KeyError): arrow_schemas = None - node = SourceNodeClass( + node = build_from_existing( + SourceNodeClass, name=node_name, tag_schema=tag_schema, data_schema=data_schema, data_context=saved_context, arrow_schemas=arrow_schemas, - _from_saved=True, ) # The saved hashes, and the saved type text of a column whose # class this process has not registered yet (ITL-1138). diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index b61537d73..4a19dd4a4 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -13,9 +13,11 @@ from __future__ import annotations from collections.abc import Callable +from contextvars import ContextVar import typing from types import UnionType -from typing import TYPE_CHECKING, Any, get_args, get_origin +from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, get_args, get_origin + if TYPE_CHECKING: import pyarrow as pa @@ -30,19 +32,46 @@ class NestedTypeNotStorableError(ValueError): """A nested type is declared where storage cannot represent it faithfully.""" +_checking_declarations: ContextVar[bool] = ContextVar( + "_checking_declarations", default=True +) +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def checking_declarations() -> bool: + """Return whether a constructor is receiving a new declaration.""" + return _checking_declarations.get() + + +def build_from_existing( + build: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> _T: + """Build an object from schemas that are saved, derived or already checked.""" + token = _checking_declarations.set(False) + try: + return build(*args, **kwargs) + finally: + _checking_declarations.reset(token) + + def require_supported_sets( - annotation: object, - get_logical_type: Callable[[type], LogicalTypeProtocol | None], + resolve: Callable[[type], LogicalTypeProtocol | None], + *schemas: SchemaLike, + annotation: object = None, ) -> None: - """Refuse declared sets of struct-stored user classes (ITL-922). + """Refuse sets of struct-stored user classes in one Python declaration (ITL-922). Args: - annotation: A declared Python type, possibly a nested container or union. - get_logical_type: Look up existing logical types without registering new ones. + resolve: Resolve an element using the converter's registry and factories. + *schemas: Declared column types. + annotation: A Python type declared directly, outside a schema. Raises: NestedTypeNotStorableError: If a set has a struct-stored user class element. """ + import pyarrow as pa + from orcapod.logical_types import user_class_identity as uci from orcapod.logical_types.user_class_logical_type import UserClassLogicalType from orcapod.semantic_types.nested_none import with_context @@ -62,10 +91,8 @@ def visit(declared: object) -> None: if len(members) == 1: element = members[0] if isinstance(element, type) and uci.class_kind(element) is not None: - import pyarrow as pa - - logical_type = get_logical_type(element) - if logical_type is None or pa.types.is_struct( + logical_type = resolve(element) + if logical_type is not None and pa.types.is_struct( logical_type.get_arrow_extension_type().storage_type ): raise NestedTypeNotStorableError( @@ -82,41 +109,38 @@ def visit(declared: object) -> None: or uci.class_kind(declared) is None ): return - seen.add(declared) - logical_type = get_logical_type(declared) - if logical_type is not None and not isinstance( - logical_type, UserClassLogicalType - ): - return try: hints = uci.type_hints(declared) except ValueError: # Class registration reports unresolved hints when it builds the type. return - for name in uci.stored_field_names(declared): - field: object = hints.get(name, Any) + seen.add(declared) + try: + for name in uci.stored_field_names(declared): + field: object = hints.get(name, Any) + try: + visit(field) + except NestedTypeNotStorableError as exc: + # A custom logical type can store a class without using its fields. + logical_type = resolve(declared) + if logical_type is not None and not isinstance( + logical_type, UserClassLogicalType + ): + return + raise with_context( + f"{declared.__qualname__}.{name} ({field})", exc + ) from exc + finally: + seen.remove(declared) + + if annotation is not None: + visit(annotation) + for schema in schemas: + for name, declared in schema.items(): try: - visit(field) + visit(declared) except NestedTypeNotStorableError as exc: - raise with_context( - f"{declared.__qualname__}.{name} ({field})", exc - ) from exc - - visit(annotation) - - -def require_supported_schema_sets( - schema: SchemaLike, - get_logical_type: Callable[[type], LogicalTypeProtocol | None], -) -> None: - """Check set declarations in a Python schema, naming the affected column.""" - from orcapod.semantic_types.nested_none import with_context - - for name, annotation in schema.items(): - try: - require_supported_sets(annotation, get_logical_type) - except NestedTypeNotStorableError as exc: - raise with_context(f"Column {name!r} ({annotation})", exc) from exc + raise with_context(f"Column {name!r} ({declared})", exc) from exc def require_storable_in_struct_field(arrow_type: pa.DataType) -> None: diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 1f8a664b6..14ffc8938 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -11,7 +11,6 @@ from __future__ import annotations -import contextvars import hashlib import logging import types @@ -33,6 +32,7 @@ SubMicrosecondDatetimeError, UnsupportedValueError, ) +from orcapod.logical_types.protocols import python_type_resolution from orcapod.semantic_types.canonical_order import ( sort_dict_entries, sort_set_elements, @@ -46,6 +46,7 @@ ) from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, + checking_declarations, require_storable_in_struct_field, require_supported_sets, ) @@ -69,19 +70,11 @@ # referencing _PYTHON_TO_ARROW_MAP directly. _PYTHON_TO_ARROW_MAP: "dict | None" = None -# Context variable for cycle detection in register_python_class. -# Using a ContextVar (rather than an instance attribute) keeps it thread-safe, -# coroutine-safe, and explicitly scoped to the active call chain without -# polluting the converter instance with temporary state. _FROZENSET_UNSUPPORTED = ( "{annotation!r} is not supported: declare set[T] instead. Support for frozenset " "is to be evaluated in ITL-1140." ) -_register_in_progress: contextvars.ContextVar[set[type] | None] = ( - contextvars.ContextVar("_register_in_progress", default=None) -) - def _get_python_to_arrow_map() -> dict: """Return the Python→Arrow type map, building it on first call.""" @@ -303,8 +296,8 @@ def get_native_python_types(cls) -> frozenset[type]: def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: """Ensure a LogicalType is registered for every annotation in schemas. - Calls ``register_python_class`` for each annotation, which recursively - resolves nested types and synthesises via factory if needed. + Resolves nested annotations recursively and synthesises logical types via + their factories as needed. When no ``LogicalTypeRegistry`` is configured, this is a no-op. Union-typed annotations (e.g. ``str | Path``) are handled by registering @@ -335,7 +328,6 @@ def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: for schema in schemas: for name, annotation in schema.items(): try: - require_supported_sets(annotation, self.get_logical_type) self._register_annotation(annotation) except ( NestedNoneNotRestorableError, @@ -354,18 +346,26 @@ def _register_annotation(self, annotation: Any) -> None: # Arrow representation. for branch in get_args(annotation): if branch is not type(None): - self.register_python_class(branch) + self._register_python_class(branch) else: - self.register_python_class(annotation) + self._register_python_class(annotation) def register_python_class(self, annotation: Any) -> "pa.DataType": + """Register an explicit Python type declaration and return its Arrow type.""" + if python_type_resolution.get() is None and checking_declarations(): + require_supported_sets( + self.get_logical_type_for_python_type, annotation=annotation + ) + return self._register_python_class(annotation) + + def _register_python_class(self, annotation: Any) -> "pa.DataType": """Register a Python type annotation and return its Arrow type. Traverses generic annotations recursively. For each concrete class found, either returns from the primitive map or registry (cache hit), or synthesises via factory and registers the result. - Cycle detection uses a ``ContextVar`` (``_register_in_progress``) rather + Cycle detection uses a ``ContextVar`` (``python_type_resolution``) rather than instance state, so it is thread-safe, coroutine-safe, and correctly detects cycles that cross factory call-backs (e.g. a dataclass with a field of its own type). @@ -385,16 +385,16 @@ def register_python_class(self, annotation: Any) -> "pa.DataType": declared ``X | None`` and a stored None there cannot be read back (ITL-1144). """ - in_progress = _register_in_progress.get() + in_progress = python_type_resolution.get() if in_progress is None: # Top-level call: initialize a fresh in-progress set and register it # in the context so recursive calls (including factory call-backs) reuse it. fresh: set[type] = set() - token = _register_in_progress.set(fresh) + token = python_type_resolution.set(fresh) try: return self._register_python_class_impl(annotation, fresh) finally: - _register_in_progress.reset(token) + python_type_resolution.reset(token) # Nested call (direct recursion or factory call-back): reuse the existing set. return self._register_python_class_impl(annotation, in_progress) @@ -406,7 +406,7 @@ def _register_python_class_impl( Args: annotation: The annotation to resolve. in_progress: The mutable cycle-detection set for the current call chain. - Shared across factory call-backs via ``_register_in_progress`` ContextVar. + Shared across factory call-backs via ``python_type_resolution`` ContextVar. """ import types as _types_mod @@ -423,7 +423,7 @@ def _register_python_class_impl( if origin is typing.Union or origin is _types_mod.UnionType: non_none = [a for a in args if a is not type(None)] if len(non_none) == 1: - return self.register_python_class(non_none[0]) + return self._register_python_class(non_none[0]) # Direct callers must not pass complex unions here — there is no # Arrow type for str | Path. For schema-level registration # (where union-typed input args are valid), use @@ -452,7 +452,7 @@ def _register_python_class_impl( f"Mixed-type Literal is not supported: {annotation!r}. " f"All members must share one type (e.g. Literal['a', 'b'])." ) - return self.register_python_class(next(iter(value_types))) + return self._register_python_class(next(iter(value_types))) # list[T] → large_list(T storage) when T is a plain type, or a top-level # ListLogicalType extension when T has a registered LogicalType. @@ -465,7 +465,7 @@ def _register_python_class_impl( "Unparameterized 'list' is not supported. Use 'list[T]' with a concrete " "element type (e.g. list[int], list[str])." ) - inner = self.register_python_class(args[0]) + inner = self._register_python_class(args[0]) require_restorable_none(args[0], inner, self._is_user_class_extension) if self._logical_type_registry is not None and hasattr( inner, "extension_name" @@ -485,7 +485,7 @@ def _register_python_class_impl( "Unparameterized 'set' is not supported. Use 'set[T]' with a concrete " "element type (e.g. set[int], set[str])." ) - inner = self.register_python_class(args[0]) + inner = self._register_python_class(args[0]) require_restorable_none(args[0], inner, self._is_user_class_extension) if self._logical_type_registry is not None and hasattr( inner, "extension_name" @@ -510,8 +510,8 @@ def _register_python_class_impl( "Unparameterized 'dict' is not supported. Use 'dict[K, V]' with concrete " "key and value types (e.g. dict[str, int])." ) - key_arrow = self.register_python_class(args[0]) - val_arrow = self.register_python_class(args[1]) + key_arrow = self._register_python_class(args[0]) + val_arrow = self._register_python_class(args[1]) require_storable_in_struct_field(key_arrow) require_storable_in_struct_field(val_arrow) require_restorable_none(args[1], val_arrow, self._is_user_class_extension) @@ -1235,7 +1235,7 @@ def get_logical_type_for_python_type( # Slow path: try registering (synthesises via factory if applicable). # Primitives return without raising and produce no registry entry. try: - self.register_python_class(annotation) + self._register_python_class(annotation) except (TypeError, ValueError): return None return self._logical_type_registry.get_by_python_type(annotation) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index d9d70fba5..121f12baf 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -274,9 +274,9 @@ def extract_function_schemas_with_container( >>> dict(output_types) {'count': , 'total': , 'repr': } """ - verified_output_types: Schema = {} + verified_output_types: SchemaLike = {} if output_typespec is not None: - if isinstance(output_typespec, dict): + if isinstance(output_typespec, Mapping): verified_output_types = output_typespec elif isinstance(output_typespec, Sequence): # If output_types is a collection, convert it to a dict with keys from return_keys diff --git a/tests/test_logical_types/test_user_class_set_declarations.py b/tests/test_logical_types/test_user_class_set_declarations.py new file mode 100644 index 000000000..3aa8c5d5b --- /dev/null +++ b/tests/test_logical_types/test_user_class_set_declarations.py @@ -0,0 +1,269 @@ +"""Exercise the ITL-922 rule at declarations and across saved and inferred data.""" + +from __future__ import annotations + +import sys +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from types import FrameType +from typing import Any, cast + +import polars as pl +import pyarrow as pa +import pytest + +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.core.function_pod import FunctionPod +from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.databases import InMemoryArrowDatabase +from orcapod.logical_types.dataclass_logical_type_factory import ( + DataclassLogicalTypeFactory, +) +from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, +) +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.pipeline.serialization import SOURCE_REGISTRY +from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.sources import DictSource, ListSource, PollingSource +from orcapod.types import DataValue, Schema + + +@op.dataclass(frozen=True) +class Point: + x: int + + +@dataclass +class PointSet: + points: set[Point] + + +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[str]]: + """Count calls through every imported reference to the same guard.""" + calls: list[str] = [] + + def record(frame: FrameType, event: str, arg: object) -> None: + if event == "call" and frame.f_code.co_name == "require_supported_sets": + calls.append(frame.f_code.co_name) + + previous = sys.getprofile() + sys.setprofile(record) + try: + yield calls + finally: + sys.setprofile(previous) + + +def _inc(x: int) -> int: + return x + 1 + + +def _consume(points: set[Point]) -> int: + return len(points) + + +def _legacy_table() -> pa.Table: + return get_default_context().type_converter.python_dicts_to_arrow_table( + [{"id": 1, "points": {Point(1)}}] + ) + + +def test_each_definition_calls_the_guard_once() -> None: + converter = get_default_context().type_converter + assert isinstance(converter, TypeConverterProtocol) + arrow = _legacy_table().schema.field("points").with_nullable(False) + schema = Schema({"points": set[Point]}) + companion = (pa.schema([]), pa.schema([arrow])) + value = cast("dict[str, DataValue]", {"points": {Point(1)}}) + for define in ( + lambda: Datagram(value, python_schema=schema), + lambda: Tag(value, python_schema=schema), + lambda: Data(value, python_schema=schema), + lambda: DictSource([value], data_schema=schema), + lambda: ListSource("points", [{Point(1)}], data_schema=schema), + lambda: PollingSource(LegacyPoll(), tag_columns=[], record_id_columns="id"), + lambda: op.SourceNode("node", Schema(), schema), + lambda: op.SourceNode("node", Schema(), schema, arrow_schemas=companion), + lambda: SourceJobNode("node", Schema(), schema, arrow_schemas=companion), + lambda: op.function_pod(output_keys="n")(_consume), + lambda: FunctionPod.from_fn(_consume, output_keys="n"), + lambda: PythonDataFunction(_inc, output_schema=schema, output_keys="points"), + lambda: converter.register_python_class(set[Point]), + lambda: DataclassLogicalTypeFactory().create_for_python_type( + PointSet, converter + ), + ): + with ( + guard_calls() as calls, + pytest.raises(NestedTypeNotStorableError, match=r"Use list\[Point\]"), + ): + _ = define() + assert len(calls) == 1 + + +def test_rows_and_inference_never_call_the_guard() -> None: + with guard_calls() as calls: + pod = FunctionPod.from_fn(_inc, output_keys="out") + assert len(calls) == 1 + tag = Tag({"k": 0}) + data = Data({"x": 1}) + output = None + with guard_calls() as calls: + for _ in range(10_000): + _, output = pod.process_data(tag, data) + assert output is not None + assert output.as_dict() == {"out": 2} + + value = cast("dict[str, DataValue]", {"points": {Point(1)}}) + assert Data(value).as_table().num_rows == 1 + assert DictSource([value]).as_table().num_rows == 1 + table = _legacy_table().select(["points"]) + assert Tag(table).as_datagram().as_dict() == value + assert Data(table).as_datagram().as_dict() == value + assert calls == [] + + +def test_restoring_source_and_job_never_calls_the_guard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setitem(SOURCE_REGISTRY, PollingSource.SOURCE_KIND, PollingSource) + schema = pa.schema([f.with_nullable(False) for f in _legacy_table().schema]) + source = PollingSource( + LegacyPoll(schema), tag_columns=[], record_id_columns="id", source_id="legacy" + ) + pod = FunctionPod.from_fn(_inc, output_keys="out") + 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) + + with guard_calls() as calls: + restored = PollingSource.from_config(source.to_config()) + assert restored.output_schema()[1]["points"] == set[Point] + assert PythonDataFunction.from_config( + pod.data_function.to_config() + ).output_data_schema == (pod.data_function.output_data_schema) + assert ( + FunctionPod.from_config(pod.to_config()).data_function.output_data_schema + == pod.data_function.output_data_schema + ) + loaded = op.PipelineJob.load(path, database=InMemoryArrowDatabase()) + assert loaded.nodes["mapped"].output_schema()[1]["renamed"] == set[Point] + assert isinstance(loaded.sources["legacy"], PollingSource) + assert 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(), b"{}") + + 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) + converter.register_logical_type_factory(WordFactory(), python_bases=[Word]) + assert converter.get_logical_type(Word) is None + rows = [cast("dict[str, DataValue]", {"words": {Word("a"), Word("z")}})] + source = DictSource(rows, data_schema={"words": set[Word]}, data_context=context) + assert converter.arrow_table_to_python_dicts(source.as_table()) == rows + + +def test_an_unresolved_class_does_not_trigger_the_refusal() -> None: + # Exact classes declared locally cannot be resolved by the built-in factory. + @dataclass(frozen=True) + class LocalPoint: + x: int + + row = cast("dict[str, DataValue]", {"points": {LocalPoint(1)}}) + assert Data(row, python_schema={"points": set[LocalPoint]}).as_dict() == row From cc7fea0f6fd9cae5d15a05c514957d8b0658d585 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:41:19 -0800 Subject: [PATCH 05/20] fix(schema): close user-class set declaration gaps --- changelog.d/ITL-922.md | 3 + src/orcapod/core/data_function.py | 4 +- src/orcapod/core/datagrams/datagram.py | 29 ++++--- src/orcapod/core/datagrams/tag_data.py | 2 +- src/orcapod/core/function_pod.py | 6 +- src/orcapod/core/nodes/source_node.py | 4 +- src/orcapod/core/sources/dict_source.py | 6 +- src/orcapod/core/sources/list_source.py | 6 +- src/orcapod/core/sources/polling_source.py | 4 +- .../list_logical_type_factory.py | 18 ++++- src/orcapod/logical_types/protocols.py | 4 - .../logical_types/user_class_identity.py | 3 +- .../logical_types/user_class_logical_type.py | 18 ++++- src/orcapod/pipeline/graph.py | 2 +- .../protocols/semantic_types_protocols.py | 2 + src/orcapod/semantic_types/declarations.py | 29 +++++++ src/orcapod/semantic_types/nested_storage.py | 26 +----- .../semantic_types/universal_converter.py | 17 ++-- src/orcapod/utils/schema_utils.py | 2 +- .../test_user_class_set_declarations.py | 80 +++++++++++++++++++ 20 files changed, 191 insertions(+), 74 deletions(-) create mode 100644 src/orcapod/semantic_types/declarations.py diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 429e3d014..b289776b4 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -4,3 +4,6 @@ dataclasses, pydantic models and `orcapod.dataclass` classes. Use `list[T]` and supply the elements in the order you want stored. Canonical ordering for these sets is deferred to ITL-1691. +- Batch schema registration and explicitly typed new datagram columns apply the same + declaration check. The internal data-context converter protocol uses + `resolve_schema_types` when resolving schemas for conversion. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 8192f7c3b..dbcaa23bb 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -52,11 +52,11 @@ check_conformance, normalize_output_numbers, ) -from orcapod.semantic_types.nested_storage import ( +from orcapod.semantic_types.declarations import ( build_from_existing, checking_declarations, - require_supported_sets, ) +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.types import ContentHash, DataValue, Schema, SchemaLike from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index c38ace605..037499892 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -37,10 +37,8 @@ from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.semantic_types.canonical_order import canonical_python_value -from orcapod.semantic_types.nested_storage import ( - checking_declarations, - require_supported_sets, -) +from orcapod.semantic_types.declarations import checking_declarations +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils @@ -158,7 +156,7 @@ def __init__( self._check_declared_schema(python_schema) def _check_declared_schema(self, python_schema: SchemaLike) -> None: - """Validate a Python schema passed to a public constructor.""" + """Validate a new Python column declaration.""" require_supported_sets( self.data_context.type_converter.get_logical_type_for_python_type, python_schema, @@ -1162,6 +1160,8 @@ def with_columns( Raises: ValueError: If any named column already exists, or a column declared by a non-nullable ``pa.Field`` has the value ``None``. + NestedTypeNotStorableError: If a new Python column type declares a set + of struct-stored user classes. """ if not updates: return self @@ -1178,6 +1178,14 @@ def with_columns( f"Use update() to modify existing columns." ) + declared_python = { + name: annotation + for name, annotation in (column_types or {}).items() + if name in updates and not isinstance(annotation, (pa.DataType, pa.Field)) + } + if declared_python and checking_declarations(): + self._check_declared_schema(declared_python) + has_arrow_types = column_types is not None and any( isinstance(t, (pa.DataType, pa.Field)) for t in column_types.values() ) @@ -1199,16 +1207,7 @@ def with_columns( else: assert self._data_dict is not None new_data = {**self._data_dict, **updates} - schema = dict(self._ensure_python_schema()) - if column_types: - # No Arrow types reach this branch (they take the Arrow path). - schema.update( - { - k: t - for k, t in column_types.items() - if not isinstance(t, (pa.DataType, pa.Field)) - } - ) + schema = {**self._ensure_python_schema(), **declared_python} inferred = infer_python_schema_from_pylist_data([new_data]) new_schema = Schema( {k: schema.get(k, inferred.get(k, str)) for k in new_data} diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 39e5da187..633c16a87 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -27,7 +27,7 @@ from orcapod.core.datagrams.datagram import Datagram, context_key_field from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants -from orcapod.semantic_types.nested_storage import checking_declarations +from orcapod.semantic_types.declarations import checking_declarations from orcapod.types import ( ColumnConfig, ContentHash, diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 27492f261..2671fbd73 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -71,11 +71,11 @@ from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants -from orcapod.semantic_types.nested_storage import ( +from orcapod.semantic_types.declarations import ( build_from_existing, checking_declarations, - require_supported_sets, ) +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.types import ( ColumnConfig, PipelineConfig, @@ -169,7 +169,7 @@ def __init__( data_function.output_data_schema, ) # Register types for schema validation, excluding ctx (not a data column). - self.data_context.type_converter.ensure_types_registered_for_schemas( + self.data_context.type_converter.resolve_schema_types( self.input_data_schema, data_function.output_data_schema, ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 76bedcb60..6a8c15140 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -62,11 +62,11 @@ from orcapod.errors import SourceSpecMismatchError, UnboundSourceError from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.logical_types.user_class_identity import equivalent_hints -from orcapod.semantic_types.nested_storage import ( +from orcapod.semantic_types.declarations import ( build_from_existing, checking_declarations, - require_supported_sets, ) +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.system_constants import constants from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, Schema diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 26ec41064..dfa432c24 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -10,10 +10,8 @@ float32_column_names, warn_first_python_float, ) -from orcapod.semantic_types.nested_storage import ( - checking_declarations, - require_supported_sets, -) +from orcapod.semantic_types.declarations import checking_declarations +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 69ece78d0..f29d384c8 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -9,10 +9,8 @@ float32_column_names, warn_first_python_float, ) -from orcapod.semantic_types.nested_storage import ( - checking_declarations, - require_supported_sets, -) +from orcapod.semantic_types.declarations import checking_declarations +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index e53ee4dcb..917018761 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -47,11 +47,11 @@ RowIdentifierError, SchemaInconsistencyError, ) -from orcapod.semantic_types.nested_storage import ( +from orcapod.semantic_types.declarations import ( build_from_existing, checking_declarations, - require_supported_sets, ) +from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.system_constants import constants from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 69975b29b..a8782b266 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -58,10 +58,18 @@ import pyarrow as pa from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.protocols import python_type_resolution from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, ) +from orcapod.semantic_types.declarations import ( + build_from_existing, + checking_declarations, +) +from orcapod.semantic_types.nested_storage import ( + require_supported_sets, +) if TYPE_CHECKING: from orcapod.logical_types.protocols import ( @@ -461,6 +469,8 @@ def create_for_python_type( ValueError: If ``python_type`` is not ``list[T]`` or ``set[T]``, if it lacks a type argument, or if ``T`` of a ``list[T]`` has no registered ``LogicalType``. + NestedTypeNotStorableError: If a new declaration contains a set of + struct-stored user classes. """ import typing @@ -480,6 +490,10 @@ def create_for_python_type( element_annotation = args[0] is_set = origin is set + if python_type_resolution.get() is None and checking_declarations(): + require_supported_sets( + converter.get_logical_type_for_python_type, annotation=python_type + ) # Directly look up (and register if needed) the LogicalType for the element. element_lt = converter.get_logical_type_for_python_type(element_annotation) @@ -487,7 +501,9 @@ def create_for_python_type( # A set of a plain Arrow type is a native container too (ITL-611). Its # element Python type is that of the element Arrow type, as on the read # path, never the annotation (``Literal[1, 2]`` reads as ``int``). - element_arrow_type = converter._register_python_class(element_annotation) + element_arrow_type = build_from_existing( + converter.register_python_class, element_annotation + ) return ListLogicalType( ArrowElement( converter.arrow_type_to_python_type(element_arrow_type), diff --git a/src/orcapod/logical_types/protocols.py b/src/orcapod/logical_types/protocols.py index 96f25561f..611bc728f 100644 --- a/src/orcapod/logical_types/protocols.py +++ b/src/orcapod/logical_types/protocols.py @@ -58,10 +58,6 @@ def register_python_class(self, annotation: Any) -> "pa.DataType": """ ... - def _register_python_class(self, annotation: Any) -> "pa.DataType": - """Resolve a Python type for conversion or restoration.""" - ... - def register_storage_type(self, arrow_type: "pa.DataType") -> "pa.DataType": """Traverse an Arrow type bottom-up, registering extension types, and return a storage-safe type. diff --git a/src/orcapod/logical_types/user_class_identity.py b/src/orcapod/logical_types/user_class_identity.py index dc6bc9d41..c8355b5b0 100644 --- a/src/orcapod/logical_types/user_class_identity.py +++ b/src/orcapod/logical_types/user_class_identity.py @@ -35,6 +35,7 @@ from typing import TYPE_CHECKING, Any, Literal from orcapod.errors import RecursiveTypeError +from orcapod.semantic_types.declarations import build_from_existing from orcapod.utils.canonical_type_names import ( canonical_module_name, canonical_type_name, @@ -497,7 +498,7 @@ def _type_token( if isinstance(annotation, type) and origin is None: if class_kind(annotation) is not None: return {"class": class_record(annotation, converter, path)} - _ = converter._register_python_class(annotation) # raises for unsupported types + _ = build_from_existing(converter.register_python_class, annotation) lt = converter.get_logical_type_for_python_type(annotation) if lt is not None: return {"logical": logical_type_identifier(lt).text} diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 0c27b6284..e4b9886b8 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -35,9 +35,12 @@ require_restorable_none, with_context, ) +from orcapod.semantic_types.declarations import ( + build_from_existing, + checking_declarations, +) from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, - checking_declarations, require_supported_sets, ) from orcapod.logical_types.registry import ( @@ -292,6 +295,15 @@ def create_for_python_type( require_supported_sets( converter.get_logical_type_for_python_type, annotation=python_type ) + return build_from_existing( + self._create_logical_type, python_type, converter + ) + return self._create_logical_type(python_type, converter) + + def _create_logical_type( + self, python_type: type, converter: TypeConverterProtocol + ) -> UserClassLogicalType: + """Build the logical type after its declaration or during type resolution.""" record = uci.class_record(python_type, converter) storage_type, field_annotations = self._storage(python_type, converter) identity = uci.identity_string(record) @@ -330,7 +342,7 @@ def _storage( for field_name in uci.stored_field_names(python_type): annotation = hints.get(field_name, Any) try: - arrow_type = converter._register_python_class(annotation) + arrow_type = converter.register_python_class(annotation) # A field is a nested position: its None must be readable (ITL-1144). require_restorable_none( annotation, @@ -408,7 +420,7 @@ def reconstruct_from_arrow( raise except (TypeError, ValueError) as exc: raise TypeIdentityError(str(exc)) from exc - _ = converter._register_python_class(cls) + _ = build_from_existing(converter.register_python_class, cls) lt = converter.get_logical_type_for_python_type(cls) if not isinstance(lt, UserClassLogicalType): raise TypeIdentityError( diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 5161d3778..ba082a8f4 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -345,7 +345,7 @@ def load(cls, path: str | Path) -> "Pipeline": ) from orcapod.core.nodes import FunctionNode, OperatorNode from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass - from orcapod.semantic_types.nested_storage import build_from_existing + from orcapod.semantic_types.declarations import build_from_existing from orcapod.types import Schema path = Path(path) diff --git a/src/orcapod/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index b09b3b3d7..dce609d84 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -55,6 +55,8 @@ def get_arrow_to_python_converter( def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: ... + def resolve_schema_types(self, *schemas: SchemaLike) -> None: ... + def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": ... def get_logical_type_for_python_type( diff --git a/src/orcapod/semantic_types/declarations.py b/src/orcapod/semantic_types/declarations.py new file mode 100644 index 000000000..534c94b4f --- /dev/null +++ b/src/orcapod/semantic_types/declarations.py @@ -0,0 +1,29 @@ +"""Distinguish new type declarations from already established schemas.""" + +from __future__ import annotations + +from collections.abc import Callable +from contextvars import ContextVar +from typing import ParamSpec, TypeVar + +_checking_declarations: ContextVar[bool] = ContextVar( + "_checking_declarations", default=True +) +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def checking_declarations() -> bool: + """Return whether a constructor is receiving a new declaration.""" + return _checking_declarations.get() + + +def build_from_existing( + build: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> _T: + """Build an object from schemas that are saved, derived or already checked.""" + token = _checking_declarations.set(False) + try: + return build(*args, **kwargs) + finally: + _checking_declarations.reset(token) diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 4a19dd4a4..9da295148 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -13,10 +13,9 @@ from __future__ import annotations from collections.abc import Callable -from contextvars import ContextVar import typing from types import UnionType -from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, get_args, get_origin +from typing import TYPE_CHECKING, Any, get_args, get_origin if TYPE_CHECKING: @@ -32,29 +31,6 @@ class NestedTypeNotStorableError(ValueError): """A nested type is declared where storage cannot represent it faithfully.""" -_checking_declarations: ContextVar[bool] = ContextVar( - "_checking_declarations", default=True -) -_P = ParamSpec("_P") -_T = TypeVar("_T") - - -def checking_declarations() -> bool: - """Return whether a constructor is receiving a new declaration.""" - return _checking_declarations.get() - - -def build_from_existing( - build: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs -) -> _T: - """Build an object from schemas that are saved, derived or already checked.""" - token = _checking_declarations.set(False) - try: - return build(*args, **kwargs) - finally: - _checking_declarations.reset(token) - - def require_supported_sets( resolve: Callable[[type], LogicalTypeProtocol | None], *schemas: SchemaLike, diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 14ffc8938..71fcf78b1 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -44,9 +44,9 @@ unrestorable_none_error, with_context, ) +from orcapod.semantic_types.declarations import checking_declarations from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, - checking_declarations, require_storable_in_struct_field, require_supported_sets, ) @@ -321,8 +321,15 @@ def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: tuples and raises a plain ``ValueError`` (``Unsupported annotation``). The tuple-field refusal applies where a tuple is converted to Arrow, in ``python_type_to_arrow_type`` and - ``python_schema_to_arrow_schema``. + ``python_schema_to_arrow_schema``. Also raised for sets of + struct-stored user classes (ITL-922). """ + if checking_declarations(): + require_supported_sets(self.get_logical_type_for_python_type, *schemas) + self.resolve_schema_types(*schemas) + + def resolve_schema_types(self, *schemas: SchemaLike) -> None: + """Register types for conversion, restoration or already-checked schemas.""" if self._logical_type_registry is None: return for schema in schemas: @@ -1214,7 +1221,7 @@ def get_logical_type_for_python_type( through the intermediate Arrow type representation. Fast path: if the type is already in the registry, returns immediately. - Slow path: calls ``register_python_class`` to synthesise via factory, then + Slow path: resolves the type internally to synthesise via its factory, then returns the result of a fresh registry lookup. Args: @@ -1385,10 +1392,10 @@ def python_dicts_to_arrow_table( # factory in the semantic-type system (e.g. Pydantic BaseModel subclasses, # @dataclass classes, or any custom factory). This means DictSource users # do not need to pre-register types via a function pod. - # ensure_types_registered_for_schemas is idempotent and thread-safe; it is + # resolve_schema_types is idempotent and thread-safe; it is # 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) + self.resolve_schema_types(python_schema) arrow_schema = self.python_schema_to_arrow_schema(python_schema) if python_schema is None: diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 121f12baf..f3fcf1fed 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -634,7 +634,7 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register try: converted = converter.python_schema_to_arrow_schema(single) except (TypeError, ValueError): - converter.ensure_types_registered_for_schemas(single) + converter.resolve_schema_types(single) converted = converter.python_schema_to_arrow_schema(single) fields.append(converted.field(name)) return pa.schema(fields) diff --git a/tests/test_logical_types/test_user_class_set_declarations.py b/tests/test_logical_types/test_user_class_set_declarations.py index 3aa8c5d5b..be1d3fcfc 100644 --- a/tests/test_logical_types/test_user_class_set_declarations.py +++ b/tests/test_logical_types/test_user_class_set_declarations.py @@ -25,6 +25,7 @@ from orcapod.logical_types.dataclass_logical_type_factory import ( DataclassLogicalTypeFactory, ) +from orcapod.logical_types.list_logical_type_factory import ListLogicalTypeFactory from orcapod.logical_types.protocols import TypeConverterProtocol from orcapod.logical_types.registry import ( make_arrow_extension_type, @@ -48,6 +49,11 @@ class PointSet: points: set[Point] +@dataclass(frozen=True) +class PlainPoint: + x: int + + class LegacyPoll: """Write an Arrow declaration and restore the equivalent legacy Python one.""" @@ -134,6 +140,7 @@ def test_each_definition_calls_the_guard_once() -> None: lambda: DataclassLogicalTypeFactory().create_for_python_type( PointSet, converter ), + lambda: ListLogicalTypeFactory().create_for_python_type(set[Point], converter), ): with ( guard_calls() as calls, @@ -143,6 +150,79 @@ def test_each_definition_calls_the_guard_once() -> None: assert len(calls) == 1 +@pytest.mark.parametrize("row_type", [Datagram, Data, Tag]) +@pytest.mark.parametrize("arrow_backed", [False, True]) +def test_with_columns_checks_only_new_python_declarations( + row_type: type[Datagram], arrow_backed: bool +) -> None: + legacy = cast("dict[str, DataValue]", {"id": 1, "points": {Point(1)}}) + row = row_type(_legacy_table() if arrow_backed else legacy) + value = cast("dict[str, DataValue]", {"new": {Point(2)}}) + with ( + guard_calls() as calls, + pytest.raises( + NestedTypeNotStorableError, match=r"Column 'new'.*Use list\[Point\]" + ), + ): + row.with_columns({"new": set[Point]}, **value) + assert len(calls) == 1 + + with guard_calls() as calls: + expanded = row.with_columns( + {"new": int, "unused": set[Point], "arrow": pa.int64()}, + new=2, + arrow=3, + **cast("dict[str, DataValue]", {"inferred": {Point(3)}}), + ) + assert expanded.as_dict()["inferred"] == {Point(3)} + assert len(calls) == 1 + + with guard_calls() as calls: + updated = row.with_columns({"new": pa.int64()}, new=2) + assert updated.as_dict()["new"] == 2 + assert not calls + + +def test_public_schema_registration_checks_the_batch_once() -> None: + converter = create_registry().get_context().type_converter + with guard_calls() as calls: + converter.ensure_types_registered_for_schemas( + Schema({"ids": set[int]}), Schema({"names": list[str]}) + ) + assert len(calls) == 1 + + with ( + guard_calls() as calls, + pytest.raises( + NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" + ), + ): + converter.ensure_types_registered_for_schemas( + Schema({"ids": set[int]}), Schema({"points": set[Point]}) + ) + assert len(calls) == 1 + + +def test_dataclass_factory_uses_public_converter_protocol() -> None: + converter = create_registry().get_context().type_converter + members = { + name: staticmethod(getattr(converter, name)) + for name, method in vars(TypeConverterProtocol).items() + if not name.startswith("_") and callable(method) + } + adapter = type("PublicConverterAdapter", (), members)() + # The adapter exposes only the public factory protocol, with no fallback. + with guard_calls() as calls: + logical_type = DataclassLogicalTypeFactory().create_for_python_type( + PlainPoint, cast(TypeConverterProtocol, cast(object, adapter)) + ) + assert isinstance(adapter, TypeConverterProtocol) + assert logical_type.get_arrow_extension_type().storage_type == pa.struct( + [pa.field("x", pa.int64())] + ) + assert len(calls) == 1 + + def test_rows_and_inference_never_call_the_guard() -> None: with guard_calls() as calls: pod = FunctionPod.from_fn(_inc, output_keys="out") From f4b5bcdb961d40a1107f5def6630efd514056d62 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:27:38 -0800 Subject: [PATCH 06/20] fix(semantic-types): refuse struct-stored user class sets at conversion --- .zed/rules | 9 +- CLAUDE.md | 9 +- changelog.d/ITL-922.md | 11 +- docs/concepts/function-pods.md | 6 +- docs/concepts/logical-type-identifiers.md | 9 +- docs/concepts/your-own-data-types.md | 10 +- docs/dev/design_issues/ITL-922-SU1.md | 5 +- docs/reference/database-types.md | 2 +- docs/reference/hashing.md | 6 +- src/orcapod/core/cached_function_pod.py | 8 +- src/orcapod/core/data_function.py | 25 +- src/orcapod/core/datagrams/datagram.py | 45 +- src/orcapod/core/datagrams/tag_data.py | 75 ++-- src/orcapod/core/function_pod.py | 36 +- src/orcapod/core/nodes/source_node.py | 52 +-- src/orcapod/core/sources/dict_source.py | 11 - src/orcapod/core/sources/list_source.py | 7 - .../list_logical_type_factory.py | 18 +- src/orcapod/logical_types/protocols.py | 8 - .../logical_types/user_class_identity.py | 3 +- .../logical_types/user_class_logical_type.py | 28 +- src/orcapod/pipeline/graph.py | 4 +- .../protocols/semantic_types_protocols.py | 2 - src/orcapod/semantic_types/declarations.py | 29 -- src/orcapod/semantic_types/nested_storage.py | 99 +---- .../semantic_types/precomputed_converters.py | 19 +- .../semantic_types/universal_converter.py | 92 ++-- src/orcapod/utils/schema_utils.py | 6 +- tests/test_databases/type_matrix.py | 2 +- .../test_nested_logical_type_refusal.py | 74 ---- .../test_user_class_set_conversion.py | 393 ++++++++++++++++++ .../test_user_class_set_declarations.py | 349 ---------------- 32 files changed, 561 insertions(+), 891 deletions(-) delete mode 100644 src/orcapod/semantic_types/declarations.py create mode 100644 tests/test_logical_types/test_user_class_set_conversion.py delete mode 100644 tests/test_logical_types/test_user_class_set_declarations.py diff --git a/.zed/rules b/.zed/rules index b6164de3f..755713dca 100644 --- a/.zed/rules +++ b/.zed/rules @@ -477,11 +477,10 @@ 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, refuse `set[T]` of a struct-stored user class at definition, including nested - declarations (`nested_storage.require_supported_sets`, ITL-922). Name the column or field - and direct users to `list[T]`. Resolve storage through the active converter and its - factories. Run the guard once at a user declaration. Inferred, converted and restored - schemas go through their existing storage paths. Canonical ordering is deferred. +- For 0.4.0, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow + value converter (developer decision D47, ITL-922). Resolve the element through the + converter and its factories. 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 6dfb571f4..f9792cf23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -488,11 +488,10 @@ 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, refuse `set[T]` of a struct-stored user class at definition, including nested - declarations (`nested_storage.require_supported_sets`, ITL-922). Name the column or field - and direct users to `list[T]`. Resolve storage through the active converter and its - factories. Run the guard once at a user declaration. Inferred, converted and restored - schemas go through their existing storage paths. Canonical ordering is deferred. +- For 0.4.0, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow + value converter (developer decision D47, ITL-922). Resolve the element through the + converter and its factories. 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 index b289776b4..11b41fb11 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -1,9 +1,6 @@ ### Breaking changes and migration -- Orcapod rejects declarations of sets of struct-stored user classes, including ordinary - dataclasses, pydantic models and `orcapod.dataclass` classes. Use `list[T]` and supply the - elements in the order you want stored. Canonical ordering for these sets is deferred to - ITL-1691. -- Batch schema registration and explicitly typed new datagram columns apply the same - declaration check. The internal data-context converter protocol uses - `resolve_schema_types` when resolving schemas for conversion. +- Converting Python sets of struct-stored user classes to Arrow now raises an error, including + for nested sets. Use `list[T]` and supply the elements in the order you want stored. + 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 03da0c2b1..0398818b5 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -285,9 +285,9 @@ 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's parameter or output declaration also refuses sets of user classes stored as -structs in Orcapod 0.4.0, including nested sets. The `NestedTypeNotStorableError` -names the parameter, output or field. Use `list[T]` to pass or return those values. +A pod definition can declare a set of user classes stored as structs. When the first +returned value is converted to Arrow, 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. diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index d7f11f298..56b664a8f 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -159,11 +159,10 @@ 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 `set[T]` of a user class stored as a struct when the type is declared, -including declarations nested inside other types. Use `list[T]` for these classes. -Sets of primitives and scalar-stored logical types such as `Path` and `UUID` are supported. -The declaration rule uses the storage type selected by the registered logical type or factory. -Existing Arrow data and saved schemas can still be read. +Orcapod 0.4.0 refuses to convert a Python `set[T]` when the registered logical type +or factory stores its user-class elements as an Arrow struct. Use `list[T]` for these +classes. Sets of primitives and scalar-stored logical types such as `Path` and `UUID` +are supported. 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 40c3105c0..ffb14edbf 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -45,10 +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. -Orcapod 0.4.0 refuses `set[T]` when `T` is a user class stored as an Arrow struct. -This includes ordinary dataclasses, `op.dataclass` classes and pydantic models, even when -the set is nested in another type or declared as a field. Use `list[T]` and supply the -items in the order you want stored. A canonical order for these sets is deferred to ITL-1691. +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 Arrow 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. ## `op.dataclass` in a notebook diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index c38187b11..c612be553 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -8,5 +8,6 @@ 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. -Orcapod 0.4.0 refuses these sets at definition, including nested declarations, and directs -users to `list[T]`. The canonical storage order for these sets remains to be designed. +Developer decision D47 places the temporary refusal where Orcapod builds the Python-to-Arrow +value converter for the set. Definitions and reads of stored data still work. Use +`list[T]` to store these values. ITL-1691 tracks the canonical storage order. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index a342d5823..4d86a3c1f 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -23,7 +23,7 @@ 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 declarations of sets of struct-stored user classes before storage. +Orcapod 0.4.0 refuses to convert Python sets of struct-stored user classes to Arrow. Use `list[T]` for those classes. What a cell says: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 616d2385a..36170079b 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1115,9 +1115,9 @@ 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 new `set[T]` declarations when `T` is a user class stored as a -struct. A canonical storage order for those elements is deferred to ITL-1691. Use -`list[T]` and choose the element order before handing the list to Orcapod. +Orcapod 0.4.0 refuses to convert Python `set[T]` values to Arrow 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 diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index a1c31f83e..30c1d0570 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -243,12 +243,12 @@ def process_data( ) if output is not None: pf = self._function_pod.data_function - var_dg = Datagram._from_typed_dict( + var_dg = Datagram( pf.get_function_variation_data(), python_schema=pf.get_function_variation_data_schema(), data_context=pf.data_context, ) - exec_dg = Datagram._from_typed_dict( + exec_dg = Datagram( pf.get_execution_data(), python_schema=pf.get_execution_data_schema(), data_context=pf.data_context, @@ -312,12 +312,12 @@ async def _async_compute_and_store( ) if output is not None: pf = self._function_pod.data_function - var_dg = Datagram._from_typed_dict( + var_dg = Datagram( pf.get_function_variation_data(), python_schema=pf.get_function_variation_data_schema(), data_context=pf.data_context, ) - exec_dg = Datagram._from_typed_dict( + exec_dg = Datagram( pf.get_execution_data(), python_schema=pf.get_execution_data_schema(), data_context=pf.data_context, diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index dbcaa23bb..286c6a0ea 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -52,11 +52,6 @@ check_conformance, normalize_output_numbers, ) -from orcapod.semantic_types.declarations import ( - build_from_existing, - checking_declarations, -) -from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.types import ContentHash, DataValue, Schema, SchemaLike from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names @@ -924,13 +919,6 @@ def __init__( output_typespec=output_schema, ) - if checking_declarations(): - require_supported_sets( - self.data_context.type_converter.get_logical_type_for_python_type, - self._input_schema, - self._output_schema, - ) - # get git info for the function # TODO: turn this into optional addition env_info = get_git_info_for_python_object(self._function, try_cwd=True) @@ -1118,7 +1106,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: source_info = output_source_info(self.uri, new_record_uuid.hex, output_data) if not output_data: - return Data._from_function_output( + return Data( output_data, source_info=source_info, record_uuid=new_record_uuid, @@ -1134,7 +1122,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: ) for key, value in output_data.items() } - return Data._from_function_output( + return Data( normalized, python_schema=output_schema, source_info=source_info, @@ -1430,10 +1418,9 @@ def from_config(cls, config: dict[str, Any]) -> "PythonDataFunction": import importlib inner = config.get("config", config) - module = build_from_existing(importlib.import_module, inner["module_path"]) + module = importlib.import_module(inner["module_path"]) func = getattr(module, inner["callable_name"]) - return build_from_existing( - cls, + return cls( function=func, output_keys=inner.get("output_keys"), version=inner.get("version", "v0.0"), @@ -1640,12 +1627,12 @@ def result_database(self) -> ArrowDatabaseProtocol: def _build_metadata_datagrams(self) -> tuple[Datagram, Datagram]: """Build variation and execution Datagrams for cache storage.""" - variation_datagram = Datagram._from_typed_dict( + variation_datagram = Datagram( self.get_function_variation_data(), python_schema=self.get_function_variation_data_schema(), data_context=self.data_context, ) - execution_datagram = Datagram._from_typed_dict( + execution_datagram = Datagram( self.get_execution_data(), python_schema=self.get_execution_data_schema(), data_context=self.data_context, diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 037499892..f5d74dac2 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -37,8 +37,6 @@ from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.semantic_types.canonical_order import canonical_python_value -from orcapod.semantic_types.declarations import checking_declarations -from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils @@ -152,28 +150,6 @@ def __init__( data, python_schema, meta_info, data_context, record_uuid ) - if python_schema is not None and checking_declarations(): - self._check_declared_schema(python_schema) - - def _check_declared_schema(self, python_schema: SchemaLike) -> None: - """Validate a new Python column declaration.""" - require_supported_sets( - self.data_context.type_converter.get_logical_type_for_python_type, - python_schema, - ) - - @classmethod - def _from_typed_dict( - cls, - data: Mapping[str, DataValue], - python_schema: SchemaLike, - data_context: str | contexts.DataContext | None = None, - ) -> Self: - """Build a datagram with its already established Python types.""" - datagram = cls.__new__(cls) - datagram._init_from_dict(data, python_schema, None, data_context, None) - return datagram - def _init_from_dict( self, data: Mapping[str, DataValue], @@ -1160,8 +1136,6 @@ def with_columns( Raises: ValueError: If any named column already exists, or a column declared by a non-nullable ``pa.Field`` has the value ``None``. - NestedTypeNotStorableError: If a new Python column type declares a set - of struct-stored user classes. """ if not updates: return self @@ -1178,14 +1152,6 @@ def with_columns( f"Use update() to modify existing columns." ) - declared_python = { - name: annotation - for name, annotation in (column_types or {}).items() - if name in updates and not isinstance(annotation, (pa.DataType, pa.Field)) - } - if declared_python and checking_declarations(): - self._check_declared_schema(declared_python) - has_arrow_types = column_types is not None and any( isinstance(t, (pa.DataType, pa.Field)) for t in column_types.values() ) @@ -1207,7 +1173,16 @@ def with_columns( else: assert self._data_dict is not None new_data = {**self._data_dict, **updates} - schema = {**self._ensure_python_schema(), **declared_python} + schema = dict(self._ensure_python_schema()) + if column_types: + # No Arrow types reach this branch (they take the Arrow path). + schema.update( + { + k: t + for k, t in column_types.items() + if not isinstance(t, (pa.DataType, pa.Field)) + } + ) inferred = infer_python_schema_from_pylist_data([new_data]) new_schema = Schema( {k: schema.get(k, inferred.get(k, str)) for k in new_data} diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 633c16a87..15a2a086f 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -27,7 +27,6 @@ from orcapod.core.datagrams.datagram import Datagram, context_key_field from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants -from orcapod.semantic_types.declarations import checking_declarations from orcapod.types import ( ColumnConfig, ContentHash, @@ -40,7 +39,6 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: - from orcapod.config import OrcapodConfig from orcapod.protocols.core_protocols import DataProtocol logger = logging.getLogger(__name__) @@ -99,7 +97,6 @@ def __init__( # self._data_table (same pattern as the legacy ArrowTag). super().__init__( data, - python_schema=python_schema, meta_info=meta_info, data_context=data_context, record_uuid=record_uuid, @@ -340,7 +337,7 @@ def as_datagram( ) -> Datagram: data = self.as_dict(columns=columns, all_info=all_info) python_schema = self.schema(columns=columns, all_info=all_info) - return Datagram._from_typed_dict( + return Datagram( data, python_schema=python_schema, data_context=self._data_context ) @@ -417,7 +414,7 @@ class Data(Datagram): input are automatically extracted. """ - def __init__( # pyright: ignore[reportMissingSuperCall] # the unchecked initializer also builds function outputs + def __init__( self, data: "Mapping[str, DataValue] | pa.Table | pa.RecordBatch", meta_info: "Mapping[str, DataValue] | None" = None, @@ -427,46 +424,6 @@ def __init__( # pyright: ignore[reportMissingSuperCall] # the unchecked initia record_uuid: "uuid.UUID | None" = None, **kwargs, ) -> None: - self._init_data( - data, - meta_info, - source_info, - python_schema, - data_context, - record_uuid, - **kwargs, - ) - if python_schema is not None and checking_declarations(): - self._check_declared_schema(python_schema) - - @classmethod - def _from_function_output( - cls, - data: "Mapping[str, DataValue]", - python_schema: "SchemaLike", - source_info: "Mapping[str, SourceInfoValue]", - record_uuid: "uuid.UUID", - data_context: "contexts.DataContext", - ) -> Self: - """Build a function output using the function's established schema.""" - row = cls.__new__(cls) - row._init_data( - data, None, source_info, python_schema, data_context, record_uuid - ) - return row - - def _init_data( - self, - data: "Mapping[str, DataValue] | pa.Table | pa.RecordBatch", - meta_info: "Mapping[str, DataValue] | None" = None, - source_info: "Mapping[str, SourceInfoValue] | None" = None, - python_schema: "SchemaLike | None" = None, - data_context: "str | contexts.DataContext | None" = None, - record_uuid: "uuid.UUID | None" = None, - *, - config: "OrcapodConfig | None" = None, - ) -> None: - """Initialize a data row and split off its source info.""" import pyarrow as _pa if isinstance(data, _pa.RecordBatch): @@ -486,7 +443,13 @@ def _init_data( } data_table, si_table = self._data_and_source_info_tables(data, source_info) - self._init_from_table(data_table, meta_info, data_context, record_uuid) + super().__init__( + data_table, + meta_info=meta_info, + data_context=data_context, + record_uuid=record_uuid, + **kwargs, + ) self._source_info: dict[str, SourceInfoValue] = self._source_info_of_row( si_table ) @@ -506,8 +469,13 @@ def _init_data( for k, v in data.items() if k.startswith(constants.SOURCE_PREFIX) } - self._init_from_dict( - data_only, python_schema, meta_info, data_context, record_uuid + super().__init__( + data_only, + python_schema=python_schema, + meta_info=meta_info, + data_context=data_context, + record_uuid=record_uuid, + **kwargs, ) self._source_info = {**contained_source_info, **(source_info or {})} @@ -1079,7 +1047,7 @@ def as_datagram( ) -> Datagram: data = self.as_dict(columns=columns, all_info=all_info) python_schema = self.schema(columns=columns, all_info=all_info) - return Datagram._from_typed_dict( + return Datagram( data=data, python_schema=python_schema, data_context=self._data_context ) @@ -1215,7 +1183,7 @@ class EmptyData(Data): record_uuid: Optional explicit UUID for this token. """ - def __init__( # pyright: ignore[reportMissingSuperCall] # a cached token carries an already established output schema + def __init__( self, cached_content_hash: ContentHash | None = None, source_info: "Mapping[str, SourceInfoValue] | None" = None, @@ -1224,7 +1192,12 @@ def __init__( # pyright: ignore[reportMissingSuperCall] # a cached token carri record_uuid: uuid.UUID | None = None, ) -> None: # Initialise the parent with an empty dict — no payload columns. - self._init_data({}, None, None, python_schema, data_context, record_uuid) + super().__init__( + {}, + python_schema=python_schema, + data_context=data_context, + record_uuid=record_uuid, + ) self._cached_content_hash: ContentHash | None = cached_content_hash self._source_info = dict(source_info or {}) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 2671fbd73..fd8910acb 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -23,11 +23,7 @@ from orcapod.config import OrcapodConfig import orcapod.core.row_ids as row_ids from orcapod.core.base import TraceableBase -from orcapod.core.data_function import ( - CachedDataFunction, - DataFunctionBase, - PythonDataFunction, -) +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction from orcapod.core.datagrams import Data from orcapod.core.data_tags import ( materialization_diagnostic_off, @@ -71,11 +67,6 @@ from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants -from orcapod.semantic_types.declarations import ( - build_from_existing, - checking_declarations, -) -from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.types import ( ColumnConfig, PipelineConfig, @@ -135,8 +126,6 @@ def __init__( data_context: str | contexts.DataContext | None = None, config: OrcapodConfig | None = None, ctx_arg_name: str | None = None, - *, - declare_schema: bool = False, ) -> None: super().__init__( label=label, @@ -157,19 +146,8 @@ def __init__( f"(schema keys: {list(data_function.input_data_schema.keys())})" ) self._ctx_arg_name: str | None = ctx_arg_name - if declare_schema and checking_declarations(): - context = ( - data_function.data_context - if isinstance(data_function, DataFunctionBase) - else self.data_context - ) - require_supported_sets( - context.type_converter.get_logical_type_for_python_type, - self.input_data_schema, - data_function.output_data_schema, - ) # Register types for schema validation, excluding ctx (not a data column). - self.data_context.type_converter.resolve_schema_types( + self.data_context.type_converter.ensure_types_registered_for_schemas( self.input_data_schema, data_function.output_data_schema, ) @@ -957,7 +935,6 @@ def __init__( super().__init__( data_function, ctx_arg_name=ctx_arg_name, - declare_schema=True, **kwargs, ) self._pod_config = pod_config or PodConfig() @@ -997,8 +974,7 @@ def from_fn( Returns: A new ``FunctionPod``. """ - data_function = build_from_existing( - PythonDataFunction, + data_function = PythonDataFunction( fn, output_keys=output_keys, function_name=name or getattr(fn, "__name__", "unknown"), @@ -1126,8 +1102,7 @@ def from_config( if config.get("pod_config") is not None: pod_config = PodConfig(**config["pod_config"]) - return build_from_existing( - cls, + return cls( data_function=data_function, pod_config=pod_config, ctx_arg_name=config.get("ctx_arg_name"), @@ -2001,8 +1976,7 @@ def decorator(func: Callable) -> CallableWithPodProtocol: if func.__name__ == "": raise ValueError("Lambda functions cannot be used with function_pod") - data_function = build_from_existing( - PythonDataFunction, + data_function = PythonDataFunction( func, output_keys=output_keys, function_name=function_name or func.__name__, diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 6a8c15140..a73b258a7 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -62,11 +62,6 @@ from orcapod.errors import SourceSpecMismatchError, UnboundSourceError from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.logical_types.user_class_identity import equivalent_hints -from orcapod.semantic_types.declarations import ( - build_from_existing, - checking_declarations, -) -from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.system_constants import constants from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.types import ColumnConfig, ContentHash, Schema @@ -585,12 +580,6 @@ def __init__( arrow_schemas = (tag_schema, data_schema) tag_schema = Schema(converter.arrow_schema_to_python_schema(tag_schema)) data_schema = Schema(converter.arrow_schema_to_python_schema(data_schema)) - elif checking_declarations(): - require_supported_sets( - self.data_context.type_converter.get_logical_type_for_python_type, - tag_schema, - data_schema, - ) self._name = name self._tag_schema = tag_schema self._data_schema = data_schema @@ -608,8 +597,9 @@ def __init__( # together (ITL-640). self._saved_arrow_texts: dict[str, Any] | None = None if arrow_schemas is None: - converter = self.data_context.type_converter - missing = _columns_without_arrow_type(tag_schema, data_schema, converter) + missing = _columns_without_arrow_type( + tag_schema, data_schema, self.data_context.type_converter + ) if missing: raise _no_arrow_type_error(name, missing) @@ -1607,8 +1597,7 @@ def from_stream( slot_name = name if name is not None else slot_name_for(stream) if not isinstance(stream, SourceNodeBase): _require_stream_arrow_types(stream, slot_name) - node = build_from_existing( - cls, + node = cls( name=slot_name, tag_schema=tag_schema, data_schema=data_schema, @@ -1662,7 +1651,7 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): *bound_source* is ``None``. """ - def __init__( # pyright: ignore[reportMissingSuperCall] # passes the base initializer schemas already checked here + def __init__( self, name: str, tag_schema: Schema | None = None, @@ -1678,19 +1667,6 @@ def __init__( # pyright: ignore[reportMissingSuperCall] # passes the base init if (dependency := independent_source_dependency(bound_source)) is not None: raise binding_dependency_error(dependency, name) - if checking_declarations(): - declared_schemas = tuple( - schema - for schema in (tag_schema, data_schema) - if schema is not None and not isinstance(schema, pa.Schema) - ) - if declared_schemas: - require_supported_sets( - contexts.resolve_context( - data_context - ).type_converter.get_logical_type_for_python_type, - *declared_schemas, - ) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1717,8 +1693,7 @@ def __init__( # pyright: ignore[reportMissingSuperCall] # passes the base init tag_schema = derived_tag if data_schema is None: data_schema = derived_data - build_from_existing( - super().__init__, + super().__init__( name=name, tag_schema=tag_schema, data_schema=data_schema, @@ -2346,8 +2321,7 @@ def from_stream( # Case 1: copy — preserve bound_source, do NOT wrap the SJN itself. # The copy states the slot's Arrow schemas from the start: its bound # source is validated against them as it is constructed (ITL-640). - node = build_from_existing( - cls, + node = cls( name=name if name is not None else stream.name, tag_schema=stream.tag_schema, data_schema=stream.data_schema, @@ -2358,8 +2332,7 @@ def from_stream( return node case SourceNode(): # Case 2: unbound — schema placeholder; SJN hash = SourceNode hash. - node = build_from_existing( - cls, + node = cls( name=name if name is not None else stream.name, tag_schema=stream.tag_schema, data_schema=stream.data_schema, @@ -2385,8 +2358,7 @@ def from_stream( tag_schema, data_schema = stream.output_schema() slot_name = name if name is not None else slot_name_for(stream) _require_stream_arrow_types(stream, slot_name) - return build_from_existing( - cls, + return cls( name=slot_name, tag_schema=tag_schema, data_schema=data_schema, @@ -2411,8 +2383,7 @@ def _from_loaded_slot( Raises: SourceSpecMismatchError: If *bound_source* does not fit the slot. """ - node = build_from_existing( - cls, + node = cls( name=slot.name, tag_schema=slot.tag_schema, data_schema=slot.data_schema, @@ -2429,8 +2400,7 @@ def as_node(self) -> SourceNode: Returns: A new ``SourceNode`` with the same name and schemas. """ - node = build_from_existing( - SourceNode, + node = SourceNode( name=self._name, tag_schema=self._tag_schema, data_schema=self._data_schema, diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index e2e34cde6..51317377b 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -10,8 +10,6 @@ float32_column_names, warn_first_python_float, ) -from orcapod.semantic_types.declarations import checking_declarations -from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, @@ -67,15 +65,6 @@ def __init__( **kwargs: Any, ) -> None: super().__init__(source_id=source_id, **kwargs) - if ( - data_schema is not None - and not isinstance(data_schema, pa.Schema) - and checking_declarations() - ): - require_supported_sets( - self.data_context.type_converter.get_logical_type_for_python_type, - data_schema, - ) tag_columns = _normalize_column_list(tag_columns) # Read the first input row before its origin is erased by dict(row). diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index f29d384c8..1433cbc71 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -9,8 +9,6 @@ float32_column_names, warn_first_python_float, ) -from orcapod.semantic_types.declarations import checking_declarations -from orcapod.semantic_types.nested_storage import require_supported_sets from orcapod.core.sources.base import RootSource from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, @@ -86,11 +84,6 @@ def __init__( **kwargs: Passed on to ``RootSource``. """ super().__init__(source_id=source_id, **kwargs) - if data_schema is not None and checking_declarations(): - require_supported_sets( - self.data_context.type_converter.get_logical_type_for_python_type, - data_schema, - ) self.name = name self._elements = list(data) diff --git a/src/orcapod/logical_types/list_logical_type_factory.py b/src/orcapod/logical_types/list_logical_type_factory.py index 794737a62..a43213b47 100644 --- a/src/orcapod/logical_types/list_logical_type_factory.py +++ b/src/orcapod/logical_types/list_logical_type_factory.py @@ -58,18 +58,10 @@ import pyarrow as pa from orcapod.logical_types.base_logical_type import BaseLogicalType -from orcapod.logical_types.protocols import python_type_resolution from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, ) -from orcapod.semantic_types.declarations import ( - build_from_existing, - checking_declarations, -) -from orcapod.semantic_types.nested_storage import ( - require_supported_sets, -) if TYPE_CHECKING: from orcapod.logical_types.protocols import ( @@ -469,8 +461,6 @@ def create_for_python_type( ValueError: If ``python_type`` is not ``list[T]`` or ``set[T]``, if it lacks a type argument, or if ``T`` of a ``list[T]`` has no registered ``LogicalType``. - NestedTypeNotStorableError: If a new declaration contains a set of - struct-stored user classes. """ import typing @@ -490,10 +480,6 @@ def create_for_python_type( element_annotation = args[0] is_set = origin is set - if python_type_resolution.get() is None and checking_declarations(): - require_supported_sets( - converter.get_logical_type_for_python_type, annotation=python_type - ) # Directly look up (and register if needed) the LogicalType for the element. element_lt = converter.get_logical_type_for_python_type(element_annotation) @@ -501,9 +487,7 @@ def create_for_python_type( # A set of a plain Arrow type is a native container too (ITL-611). Its # element Python type is that of the element Arrow type, as on the read # path, never the annotation (``Literal[1, 2]`` reads as ``int``). - element_arrow_type = build_from_existing( - converter.register_python_class, element_annotation - ) + element_arrow_type = converter.register_python_class(element_annotation) return ListLogicalType( ArrowElement( converter.arrow_type_to_python_type(element_arrow_type), diff --git a/src/orcapod/logical_types/protocols.py b/src/orcapod/logical_types/protocols.py index 611bc728f..89e399622 100644 --- a/src/orcapod/logical_types/protocols.py +++ b/src/orcapod/logical_types/protocols.py @@ -9,7 +9,6 @@ from __future__ import annotations -from contextvars import ContextVar from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.types import DataType @@ -19,13 +18,6 @@ import pyarrow as pa -# Share cycle detection with factory callbacks. An active resolution has already -# passed its declaration check, or was requested by storage without one. -python_type_resolution: ContextVar[set[type] | None] = ContextVar( - "python_type_resolution", default=None -) - - @runtime_checkable class TypeConverterProtocol(Protocol): """Minimal protocol exposing what factories and logical types need from the converter. diff --git a/src/orcapod/logical_types/user_class_identity.py b/src/orcapod/logical_types/user_class_identity.py index c8355b5b0..c18a9a0b8 100644 --- a/src/orcapod/logical_types/user_class_identity.py +++ b/src/orcapod/logical_types/user_class_identity.py @@ -35,7 +35,6 @@ from typing import TYPE_CHECKING, Any, Literal from orcapod.errors import RecursiveTypeError -from orcapod.semantic_types.declarations import build_from_existing from orcapod.utils.canonical_type_names import ( canonical_module_name, canonical_type_name, @@ -498,7 +497,7 @@ def _type_token( if isinstance(annotation, type) and origin is None: if class_kind(annotation) is not None: return {"class": class_record(annotation, converter, path)} - _ = build_from_existing(converter.register_python_class, annotation) + _ = converter.register_python_class(annotation) # raises for unsupported types lt = converter.get_logical_type_for_python_type(annotation) if lt is not None: return {"logical": logical_type_identifier(lt).text} diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 141702386..39cba09ff 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -30,20 +30,12 @@ import orcapod.logical_types.user_class_identity as uci from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.structural_class import class_for_record -from orcapod.logical_types.protocols import python_type_resolution from orcapod.semantic_types.nested_none import ( NestedNoneNotRestorableError, require_restorable_none, with_context, ) -from orcapod.semantic_types.declarations import ( - build_from_existing, - checking_declarations, -) -from orcapod.semantic_types.nested_storage import ( - NestedTypeNotStorableError, - require_supported_sets, -) +from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, @@ -54,6 +46,7 @@ logger = logging.getLogger(__name__) + # Extension type classes per (identity string, storage type, metadata). Two class objects # with one identity (a class defined again, two structural classes of one type) must # give Arrow types that compare equal, and pyarrow compares the type's Python class. @@ -290,21 +283,6 @@ def create_for_python_type( TypeError: If the class refers back to itself (directly or through other classes), naming the field path, or a field type cannot be stored. """ - # A direct factory call declares a class. A converter dispatch is - # resolving a type for either an already-checked declaration or storage. - if python_type_resolution.get() is None and checking_declarations(): - require_supported_sets( - converter.get_logical_type_for_python_type, annotation=python_type - ) - return build_from_existing( - self._create_logical_type, python_type, converter - ) - return self._create_logical_type(python_type, converter) - - def _create_logical_type( - self, python_type: type, converter: TypeConverterProtocol - ) -> UserClassLogicalType: - """Build the logical type after its declaration or during type resolution.""" record = uci.class_record(python_type, converter) storage_type, field_annotations = self._storage(python_type, converter) identity = uci.identity_string(record) @@ -421,7 +399,7 @@ def reconstruct_from_arrow( raise except (TypeError, ValueError) as exc: raise TypeIdentityError(str(exc)) from exc - _ = build_from_existing(converter.register_python_class, cls) + _ = converter.register_python_class(cls) lt = converter.get_logical_type_for_python_type(cls) if not isinstance(lt, UserClassLogicalType): raise TypeIdentityError( diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index ba082a8f4..46937b262 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -345,7 +345,6 @@ def load(cls, path: str | Path) -> "Pipeline": ) from orcapod.core.nodes import FunctionNode, OperatorNode from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass - from orcapod.semantic_types.declarations import build_from_existing from orcapod.types import Schema path = Path(path) @@ -479,8 +478,7 @@ def load(cls, path: str | Path) -> "Pipeline": ) except (ValueError, TypeError, KeyError): arrow_schemas = None - node = build_from_existing( - SourceNodeClass, + node = SourceNodeClass( name=node_name, tag_schema=tag_schema, data_schema=data_schema, diff --git a/src/orcapod/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index dce609d84..b09b3b3d7 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -55,8 +55,6 @@ def get_arrow_to_python_converter( def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: ... - def resolve_schema_types(self, *schemas: SchemaLike) -> None: ... - def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": ... def get_logical_type_for_python_type( diff --git a/src/orcapod/semantic_types/declarations.py b/src/orcapod/semantic_types/declarations.py deleted file mode 100644 index 534c94b4f..000000000 --- a/src/orcapod/semantic_types/declarations.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Distinguish new type declarations from already established schemas.""" - -from __future__ import annotations - -from collections.abc import Callable -from contextvars import ContextVar -from typing import ParamSpec, TypeVar - -_checking_declarations: ContextVar[bool] = ContextVar( - "_checking_declarations", default=True -) -_P = ParamSpec("_P") -_T = TypeVar("_T") - - -def checking_declarations() -> bool: - """Return whether a constructor is receiving a new declaration.""" - return _checking_declarations.get() - - -def build_from_existing( - build: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs -) -> _T: - """Build an object from schemas that are saved, derived or already checked.""" - token = _checking_declarations.set(False) - try: - return build(*args, **kwargs) - finally: - _checking_declarations.reset(token) diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 9da295148..37ee98ba6 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -12,111 +12,16 @@ from __future__ import annotations -from collections.abc import Callable -import typing -from types import UnionType -from typing import TYPE_CHECKING, Any, get_args, get_origin - +from typing import TYPE_CHECKING if TYPE_CHECKING: import pyarrow as pa - from orcapod.logical_types.protocols import LogicalTypeProtocol - from orcapod.types import SchemaLike - _FOLLOW_UP = "ITL-1150" class NestedTypeNotStorableError(ValueError): - """A nested type is declared where storage cannot represent it faithfully.""" - - -def require_supported_sets( - resolve: Callable[[type], LogicalTypeProtocol | None], - *schemas: SchemaLike, - annotation: object = None, -) -> None: - """Refuse sets of struct-stored user classes in one Python declaration (ITL-922). - - Args: - resolve: Resolve an element using the converter's registry and factories. - *schemas: Declared column types. - annotation: A Python type declared directly, outside a schema. - - Raises: - NestedTypeNotStorableError: If a set has a struct-stored user class element. - """ - import pyarrow as pa - - from orcapod.logical_types import user_class_identity as uci - from orcapod.logical_types.user_class_logical_type import UserClassLogicalType - from orcapod.semantic_types.nested_none import with_context - - seen: set[type] = set() - - def visit(declared: object) -> None: - """Check a generic's arguments or the stored fields of a user class.""" - origin: object = get_origin(declared) - args: tuple[object, ...] = get_args(declared) - if origin is set and args: - element = args[0] - if get_origin(element) in (typing.Union, UnionType): - members = tuple( - arg for arg in get_args(element) if arg is not type(None) - ) - if len(members) == 1: - element = members[0] - if isinstance(element, type) and uci.class_kind(element) is not None: - logical_type = resolve(element) - if logical_type is not None and pa.types.is_struct( - logical_type.get_arrow_extension_type().storage_type - ): - raise NestedTypeNotStorableError( - "Sets of user classes are not supported in this version. " - f"Use list[{element.__qualname__}] instead." - ) - if origin in (list, set, dict, tuple, typing.Union, UnionType): - for arg in args: - visit(arg) - return - if ( - not isinstance(declared, type) - or declared in seen - or uci.class_kind(declared) is None - ): - return - try: - hints = uci.type_hints(declared) - except ValueError: - # Class registration reports unresolved hints when it builds the type. - return - seen.add(declared) - try: - for name in uci.stored_field_names(declared): - field: object = hints.get(name, Any) - try: - visit(field) - except NestedTypeNotStorableError as exc: - # A custom logical type can store a class without using its fields. - logical_type = resolve(declared) - if logical_type is not None and not isinstance( - logical_type, UserClassLogicalType - ): - return - raise with_context( - f"{declared.__qualname__}.{name} ({field})", exc - ) from exc - finally: - seen.remove(declared) - - if annotation is not None: - visit(annotation) - for schema in schemas: - for name, declared in schema.items(): - try: - visit(declared) - except NestedTypeNotStorableError as exc: - raise with_context(f"Column {name!r} ({declared})", exc) from exc + """A logical type is declared where storage cannot keep it (ITL-1150).""" def require_storable_in_struct_field(arrow_type: pa.DataType) -> None: diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 3e56bc801..bf3b14e16 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -10,6 +10,7 @@ from typing import Any from collections.abc import Callable +from functools import cached_property import pyarrow as pa @@ -43,20 +44,21 @@ def __init__( "Either python_schema or arrow_schema must be provided to initialize SemanticSchemaConverter." ) - # Pre-compute converters for each field - 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) - ) - for field in self.arrow_schema: self._arrow_to_python_converters[field.name] = ( self.universal_converter.get_arrow_to_python_converter(field.type) ) + @cached_property + def _python_to_arrow_converters(self) -> dict[str, Callable[[Any], Any]]: + """Build write converters only when converting Python rows.""" + return { + name: self.universal_converter.get_python_to_arrow_converter(python_type) + for name, python_type in self.python_schema.items() + } + 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. @@ -75,10 +77,11 @@ def python_dicts_to_struct_dicts( if not data: raise ValueError("Cannot convert empty data list") + converters = self._python_to_arrow_converters 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: diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 71fcf78b1..cfc5531a1 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -11,6 +11,7 @@ from __future__ import annotations +import contextvars import hashlib import logging import types @@ -32,7 +33,6 @@ SubMicrosecondDatetimeError, UnsupportedValueError, ) -from orcapod.logical_types.protocols import python_type_resolution from orcapod.semantic_types.canonical_order import ( sort_dict_entries, sort_set_elements, @@ -44,11 +44,9 @@ unrestorable_none_error, with_context, ) -from orcapod.semantic_types.declarations import checking_declarations from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, require_storable_in_struct_field, - require_supported_sets, ) from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data from orcapod.types import DataType, Schema, SchemaLike @@ -70,11 +68,19 @@ # referencing _PYTHON_TO_ARROW_MAP directly. _PYTHON_TO_ARROW_MAP: "dict | None" = None +# Context variable for cycle detection in register_python_class. +# Using a ContextVar (rather than an instance attribute) keeps it thread-safe, +# coroutine-safe, and explicitly scoped to the active call chain without +# polluting the converter instance with temporary state. _FROZENSET_UNSUPPORTED = ( "{annotation!r} is not supported: declare set[T] instead. Support for frozenset " "is to be evaluated in ITL-1140." ) +_register_in_progress: contextvars.ContextVar[set[type] | None] = ( + contextvars.ContextVar("_register_in_progress", default=None) +) + def _get_python_to_arrow_map() -> dict: """Return the Python→Arrow type map, building it on first call.""" @@ -296,8 +302,8 @@ def get_native_python_types(cls) -> frozenset[type]: def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: """Ensure a LogicalType is registered for every annotation in schemas. - Resolves nested annotations recursively and synthesises logical types via - their factories as needed. + Calls ``register_python_class`` for each annotation, which recursively + resolves nested types and synthesises via factory if needed. When no ``LogicalTypeRegistry`` is configured, this is a no-op. Union-typed annotations (e.g. ``str | Path``) are handled by registering @@ -321,15 +327,8 @@ def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: tuples and raises a plain ``ValueError`` (``Unsupported annotation``). The tuple-field refusal applies where a tuple is converted to Arrow, in ``python_type_to_arrow_type`` and - ``python_schema_to_arrow_schema``. Also raised for sets of - struct-stored user classes (ITL-922). + ``python_schema_to_arrow_schema``. """ - if checking_declarations(): - require_supported_sets(self.get_logical_type_for_python_type, *schemas) - self.resolve_schema_types(*schemas) - - def resolve_schema_types(self, *schemas: SchemaLike) -> None: - """Register types for conversion, restoration or already-checked schemas.""" if self._logical_type_registry is None: return for schema in schemas: @@ -353,26 +352,18 @@ def _register_annotation(self, annotation: Any) -> None: # Arrow representation. for branch in get_args(annotation): if branch is not type(None): - self._register_python_class(branch) + self.register_python_class(branch) else: - self._register_python_class(annotation) + self.register_python_class(annotation) def register_python_class(self, annotation: Any) -> "pa.DataType": - """Register an explicit Python type declaration and return its Arrow type.""" - if python_type_resolution.get() is None and checking_declarations(): - require_supported_sets( - self.get_logical_type_for_python_type, annotation=annotation - ) - return self._register_python_class(annotation) - - def _register_python_class(self, annotation: Any) -> "pa.DataType": """Register a Python type annotation and return its Arrow type. Traverses generic annotations recursively. For each concrete class found, either returns from the primitive map or registry (cache hit), or synthesises via factory and registers the result. - Cycle detection uses a ``ContextVar`` (``python_type_resolution``) rather + Cycle detection uses a ``ContextVar`` (``_register_in_progress``) rather than instance state, so it is thread-safe, coroutine-safe, and correctly detects cycles that cross factory call-backs (e.g. a dataclass with a field of its own type). @@ -392,16 +383,16 @@ def _register_python_class(self, annotation: Any) -> "pa.DataType": declared ``X | None`` and a stored None there cannot be read back (ITL-1144). """ - in_progress = python_type_resolution.get() + in_progress = _register_in_progress.get() if in_progress is None: # Top-level call: initialize a fresh in-progress set and register it # in the context so recursive calls (including factory call-backs) reuse it. fresh: set[type] = set() - token = python_type_resolution.set(fresh) + token = _register_in_progress.set(fresh) try: return self._register_python_class_impl(annotation, fresh) finally: - python_type_resolution.reset(token) + _register_in_progress.reset(token) # Nested call (direct recursion or factory call-back): reuse the existing set. return self._register_python_class_impl(annotation, in_progress) @@ -413,7 +404,7 @@ def _register_python_class_impl( Args: annotation: The annotation to resolve. in_progress: The mutable cycle-detection set for the current call chain. - Shared across factory call-backs via ``python_type_resolution`` ContextVar. + Shared across factory call-backs via ``_register_in_progress`` ContextVar. """ import types as _types_mod @@ -430,7 +421,7 @@ def _register_python_class_impl( if origin is typing.Union or origin is _types_mod.UnionType: non_none = [a for a in args if a is not type(None)] if len(non_none) == 1: - return self._register_python_class(non_none[0]) + return self.register_python_class(non_none[0]) # Direct callers must not pass complex unions here — there is no # Arrow type for str | Path. For schema-level registration # (where union-typed input args are valid), use @@ -459,7 +450,7 @@ def _register_python_class_impl( f"Mixed-type Literal is not supported: {annotation!r}. " f"All members must share one type (e.g. Literal['a', 'b'])." ) - return self._register_python_class(next(iter(value_types))) + return self.register_python_class(next(iter(value_types))) # list[T] → large_list(T storage) when T is a plain type, or a top-level # ListLogicalType extension when T has a registered LogicalType. @@ -472,7 +463,7 @@ def _register_python_class_impl( "Unparameterized 'list' is not supported. Use 'list[T]' with a concrete " "element type (e.g. list[int], list[str])." ) - inner = self._register_python_class(args[0]) + inner = self.register_python_class(args[0]) require_restorable_none(args[0], inner, self._is_user_class_extension) if self._logical_type_registry is not None and hasattr( inner, "extension_name" @@ -492,7 +483,7 @@ def _register_python_class_impl( "Unparameterized 'set' is not supported. Use 'set[T]' with a concrete " "element type (e.g. set[int], set[str])." ) - inner = self._register_python_class(args[0]) + inner = self.register_python_class(args[0]) require_restorable_none(args[0], inner, self._is_user_class_extension) if self._logical_type_registry is not None and hasattr( inner, "extension_name" @@ -517,8 +508,8 @@ def _register_python_class_impl( "Unparameterized 'dict' is not supported. Use 'dict[K, V]' with concrete " "key and value types (e.g. dict[str, int])." ) - key_arrow = self._register_python_class(args[0]) - val_arrow = self._register_python_class(args[1]) + key_arrow = self.register_python_class(args[0]) + val_arrow = self.register_python_class(args[1]) require_storable_in_struct_field(key_arrow) require_storable_in_struct_field(val_arrow) require_restorable_none(args[1], val_arrow, self._is_user_class_extension) @@ -1221,7 +1212,7 @@ def get_logical_type_for_python_type( through the intermediate Arrow type representation. Fast path: if the type is already in the registry, returns immediately. - Slow path: resolves the type internally to synthesise via its factory, then + Slow path: calls ``register_python_class`` to synthesise via factory, then returns the result of a fresh registry lookup. Args: @@ -1242,7 +1233,7 @@ def get_logical_type_for_python_type( # Slow path: try registering (synthesises via factory if applicable). # Primitives return without raising and produce no registry entry. try: - self._register_python_class(annotation) + self.register_python_class(annotation) except (TypeError, ValueError): return None return self._logical_type_registry.get_by_python_type(annotation) @@ -1392,10 +1383,10 @@ def python_dicts_to_arrow_table( # factory in the semantic-type system (e.g. Pydantic BaseModel subclasses, # @dataclass classes, or any custom factory). This means DictSource users # do not need to pre-register types via a function pod. - # resolve_schema_types is idempotent and thread-safe; it is + # ensure_types_registered_for_schemas is idempotent and thread-safe; it is # a no-op for primitives and already-registered types. assert python_schema is not None, "Python schema should not be None here" - self.resolve_schema_types(python_schema) + self.ensure_types_registered_for_schemas(python_schema) arrow_schema = self.python_schema_to_arrow_schema(python_schema) if python_schema is None: @@ -1404,6 +1395,10 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) + if not python_dicts: + # A declared schema with no rows needs no value converters. + return pa.Table.from_pylist([], schema=arrow_schema) + struct_dicts = self.python_dicts_to_struct_dicts( python_dicts, python_schema=python_schema ) @@ -1856,11 +1851,31 @@ def _generate_unique_type_name(self, field_specs: Mapping[str, DataType]) -> str self._created_type_names.add(base_name) return base_name + def _require_storable_set(self, element_type: DataType) -> None: + """Refuse writes of sets whose user-class elements lack a canonical order.""" + from orcapod.logical_types.user_class_identity import class_kind + + if not isinstance(element_type, type) or class_kind(element_type) is None: + return + element = self.get_logical_type_for_python_type(element_type) + if element is not None and pa.types.is_struct( + element.get_arrow_extension_type().storage_type + ): + raise NestedTypeNotStorableError( + "A set of user-class values cannot be stored in this version because " + "its element order would not be canonical. " + f"Use list[{element_type.__qualname__}]." + ) + def _create_python_to_arrow_converter( self, python_type: DataType ) -> Callable[[Any], Any]: """Create a cached conversion function for Python → Arrow values.""" + origin = get_origin(python_type) + if origin is set and len(set_args := get_args(python_type)) == 1: + self._require_storable_set(set_args[0]) + # Check LogicalTypeRegistry first — extension-type identity takes priority. # GenericAlias instances like list[UUID] or set[UUID] may be registered as # ListLogicalType entries, so we must not guard this check with isinstance(python_type, type). @@ -1901,7 +1916,6 @@ def _convert_datetime(dt: datetime) -> datetime: return _convert_datetime - origin = get_origin(python_type) args = get_args(python_type) if python_type is int: diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index f3fcf1fed..d9d70fba5 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -274,9 +274,9 @@ def extract_function_schemas_with_container( >>> dict(output_types) {'count': , 'total': , 'repr': } """ - verified_output_types: SchemaLike = {} + verified_output_types: Schema = {} if output_typespec is not None: - if isinstance(output_typespec, Mapping): + if isinstance(output_typespec, dict): verified_output_types = output_typespec elif isinstance(output_typespec, Sequence): # If output_types is a collection, convert it to a dict with keys from return_keys @@ -634,7 +634,7 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register try: converted = converter.python_schema_to_arrow_schema(single) except (TypeError, ValueError): - converter.resolve_schema_types(single) + converter.ensure_types_registered_for_schemas(single) converted = converter.python_schema_to_arrow_schema(single) fields.append(converted.field(name)) return pa.schema(fields) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 158d39d68..a9948de4a 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1070,7 +1070,7 @@ 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 declarations of sets of struct-stored user classes before storage. +Orcapod 0.4.0 refuses to convert Python sets of struct-stored user classes to Arrow. Use `list[T]` for those classes. What a cell says: diff --git a/tests/test_logical_types/test_nested_logical_type_refusal.py b/tests/test_logical_types/test_nested_logical_type_refusal.py index 7bc8597fb..63b22d468 100644 --- a/tests/test_logical_types/test_nested_logical_type_refusal.py +++ b/tests/test_logical_types/test_nested_logical_type_refusal.py @@ -29,12 +29,8 @@ import pytest import orcapod as op -from orcapod.contexts import get_default_context -from orcapod.core.datagrams import Data from orcapod.databases import InMemoryArrowDatabase -from orcapod.logical_types.protocols import TypeConverterProtocol from orcapod.operators import MapData -from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError from orcapod.sources import DictSource # A declared type whose value would not read back as declared -> one value of it. @@ -169,82 +165,12 @@ def test_the_refusal_says_how_to_keep_the_value() -> None: assert "dict[str, list[int]]" in message -@dataclasses.dataclass(frozen=True) -class SetPoint: - x: int - - -@op.dataclass(frozen=True) -class StructuralSetPoint: - x: int - - -class ModelSetPoint(pydantic.BaseModel, frozen=True): - x: int - - -@dataclasses.dataclass -class HoldsPointSet: - points: set[SetPoint] - - -@pytest.mark.parametrize("point_type", [SetPoint, StructuralSetPoint, ModelSetPoint]) -def test_a_source_rejects_sets_of_user_classes(point_type: type) -> None: - with pytest.raises( - NestedTypeNotStorableError, - match=rf"'points'.*Use list\[{point_type.__name__}\]", - ): - _ = DictSource( - [{"points": set()}], - data_schema={"points": set[point_type]}, - source_id="user_class_set", - ) - - -@pytest.mark.parametrize( - "declared", - [ - list[set[SetPoint]], - set[SetPoint] | None, - dict[str, set[SetPoint]], - HoldsPointSet, - ], -) -def test_data_rejects_nested_sets_in_the_declared_schema(declared: Any) -> None: - with pytest.raises( - NestedTypeNotStorableError, match=r"'points'.*Use list\[SetPoint\]" - ): - _ = Data({"points": None}, python_schema={"points": declared}) - - -def test_registering_a_class_rejects_a_set_field() -> None: - converter = get_default_context().type_converter - assert isinstance(converter, TypeConverterProtocol) - with pytest.raises( - NestedTypeNotStorableError, match=r"HoldsPointSet\.points.*Use list\[SetPoint\]" - ): - _ = converter.register_python_class(HoldsPointSet) - - -def test_a_pod_rejects_a_set_of_user_classes_at_definition() -> None: - with pytest.raises( - NestedTypeNotStorableError, match=r"'got'.*Use list\[SetPoint\]" - ): - _consumer(set[SetPoint]) - with pytest.raises( - NestedTypeNotStorableError, match=r"'out'.*Use list\[SetPoint\]" - ): - _producer(set[SetPoint], set()) - - # --------------------------------------------------------------------------- # Accepted: the positions that keep the declared type # --------------------------------------------------------------------------- ACCEPTED: dict[str, tuple[Any, Any]] = { "set_int": (set[int], {3, 1, 2}), - "set_path": (set[Path], {Path("/a"), Path("/b")}), - "list_of_user_classes": (list[SetPoint], [SetPoint(2), SetPoint(1)]), "list_of_sets": (list[set[int]], [{2, 1}, {3}]), "list_of_paths": (list[Path], [Path("/a"), Path("/b")]), "dict_of_lists": (dict[str, list[int]], {"a": [2, 1]}), 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..c1af5b91d --- /dev/null +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -0,0 +1,393 @@ +"""Test the Python-to-Arrow refusal and the existing read paths (ITL-922).""" + +from __future__ import annotations + +import subprocess +import sys +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from textwrap import dedent +from types import FrameType +from typing import Any, cast + +import polars as pl +import pydantic +import pyarrow as pa +import pytest + +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 +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.logical_types.base_logical_type import BaseLogicalType +from orcapod.pipeline.serialization import SOURCE_REGISTRY, resolve_source_from_config +from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError +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 + + +@op.dataclass(frozen=True) +class Point: + x: int + + +@dataclass +class PointSet: + points: set[Point] + + +@dataclass(frozen=True) +class PlainPoint: + x: int + + +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[str]]: + """Count calls through every imported reference to the same guard.""" + calls: list[str] = [] + + def record(frame: FrameType, event: str, arg: object) -> None: + if event == "call" and frame.f_code.co_name == "_require_storable_set": + calls.append(frame.f_code.co_name) + + previous = sys.getprofile() + sys.setprofile(record) + try: + yield calls + finally: + sys.setprofile(previous) + + +@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) + converter.register_logical_type_factory(WordFactory(), python_bases=[Word]) + assert converter.get_logical_type(Word) is None + rows = [cast("dict[str, DataValue]", {"words": {Word("a"), Word("z")}})] + source = DictSource(rows, data_schema={"words": set[Word]}, data_context=context) + assert converter.arrow_table_to_python_dicts(source.as_table()) == rows + + +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"canonical.*Use list\["): + DictSource([{"points": {value}}]) + + +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)}]), + (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 = get_default_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]]} + ) + + +@pytest.mark.asyncio +async def test_sync_and_async_function_pod_outputs_fail_at_conversion() -> None: + source = DictSource([{"x": 1}]) + with pytest.raises(OutputTypeError, match="NestedTypeNotStorableError"): + list(points_sync.pod(source).iter_data()) + with pytest.raises(OutputTypeError, match="NestedTypeNotStorableError"): + _ = [row async for row in points_async.pod(source).async_iter_data()] + + +def test_a_failed_job_writes_no_tables() -> None: + database = InMemoryArrowDatabase() + job = op.PipelineJob(name="refused", database=database) + with job: + points_sync.pod(DictSource([{"x": 1}]), label="points") + with pytest.warns(RowFailuresWarning, match="NestedTypeNotStorableError"): + job.run() + 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"], + ) + + +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 + schema = converter.python_schema_to_arrow_schema( + Schema({"points": set[PlainPoint]}) + ) + 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 == "_require_storable_set": + 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_a_set_converter_is_checked_once_for_many_rows_and_reuses_its_cache() -> 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 len(calls) == 1 + assert first.equals(second) diff --git a/tests/test_logical_types/test_user_class_set_declarations.py b/tests/test_logical_types/test_user_class_set_declarations.py deleted file mode 100644 index be1d3fcfc..000000000 --- a/tests/test_logical_types/test_user_class_set_declarations.py +++ /dev/null @@ -1,349 +0,0 @@ -"""Exercise the ITL-922 rule at declarations and across saved and inferred data.""" - -from __future__ import annotations - -import sys -from collections.abc import Callable, Iterator -from contextlib import contextmanager -from dataclasses import dataclass -from pathlib import Path -from types import FrameType -from typing import Any, cast - -import polars as pl -import pyarrow as pa -import pytest - -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.core.function_pod import FunctionPod -from orcapod.core.nodes.source_node import SourceJobNode -from orcapod.databases import InMemoryArrowDatabase -from orcapod.logical_types.dataclass_logical_type_factory import ( - DataclassLogicalTypeFactory, -) -from orcapod.logical_types.list_logical_type_factory import ListLogicalTypeFactory -from orcapod.logical_types.protocols import TypeConverterProtocol -from orcapod.logical_types.registry import ( - make_arrow_extension_type, - make_polars_extension_type, -) -from orcapod.logical_types.base_logical_type import BaseLogicalType -from orcapod.pipeline.serialization import SOURCE_REGISTRY -from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError -from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from orcapod.sources import DictSource, ListSource, PollingSource -from orcapod.types import DataValue, Schema - - -@op.dataclass(frozen=True) -class Point: - x: int - - -@dataclass -class PointSet: - points: set[Point] - - -@dataclass(frozen=True) -class PlainPoint: - x: int - - -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[str]]: - """Count calls through every imported reference to the same guard.""" - calls: list[str] = [] - - def record(frame: FrameType, event: str, arg: object) -> None: - if event == "call" and frame.f_code.co_name == "require_supported_sets": - calls.append(frame.f_code.co_name) - - previous = sys.getprofile() - sys.setprofile(record) - try: - yield calls - finally: - sys.setprofile(previous) - - -def _inc(x: int) -> int: - return x + 1 - - -def _consume(points: set[Point]) -> int: - return len(points) - - -def _legacy_table() -> pa.Table: - return get_default_context().type_converter.python_dicts_to_arrow_table( - [{"id": 1, "points": {Point(1)}}] - ) - - -def test_each_definition_calls_the_guard_once() -> None: - converter = get_default_context().type_converter - assert isinstance(converter, TypeConverterProtocol) - arrow = _legacy_table().schema.field("points").with_nullable(False) - schema = Schema({"points": set[Point]}) - companion = (pa.schema([]), pa.schema([arrow])) - value = cast("dict[str, DataValue]", {"points": {Point(1)}}) - for define in ( - lambda: Datagram(value, python_schema=schema), - lambda: Tag(value, python_schema=schema), - lambda: Data(value, python_schema=schema), - lambda: DictSource([value], data_schema=schema), - lambda: ListSource("points", [{Point(1)}], data_schema=schema), - lambda: PollingSource(LegacyPoll(), tag_columns=[], record_id_columns="id"), - lambda: op.SourceNode("node", Schema(), schema), - lambda: op.SourceNode("node", Schema(), schema, arrow_schemas=companion), - lambda: SourceJobNode("node", Schema(), schema, arrow_schemas=companion), - lambda: op.function_pod(output_keys="n")(_consume), - lambda: FunctionPod.from_fn(_consume, output_keys="n"), - lambda: PythonDataFunction(_inc, output_schema=schema, output_keys="points"), - lambda: converter.register_python_class(set[Point]), - lambda: DataclassLogicalTypeFactory().create_for_python_type( - PointSet, converter - ), - lambda: ListLogicalTypeFactory().create_for_python_type(set[Point], converter), - ): - with ( - guard_calls() as calls, - pytest.raises(NestedTypeNotStorableError, match=r"Use list\[Point\]"), - ): - _ = define() - assert len(calls) == 1 - - -@pytest.mark.parametrize("row_type", [Datagram, Data, Tag]) -@pytest.mark.parametrize("arrow_backed", [False, True]) -def test_with_columns_checks_only_new_python_declarations( - row_type: type[Datagram], arrow_backed: bool -) -> None: - legacy = cast("dict[str, DataValue]", {"id": 1, "points": {Point(1)}}) - row = row_type(_legacy_table() if arrow_backed else legacy) - value = cast("dict[str, DataValue]", {"new": {Point(2)}}) - with ( - guard_calls() as calls, - pytest.raises( - NestedTypeNotStorableError, match=r"Column 'new'.*Use list\[Point\]" - ), - ): - row.with_columns({"new": set[Point]}, **value) - assert len(calls) == 1 - - with guard_calls() as calls: - expanded = row.with_columns( - {"new": int, "unused": set[Point], "arrow": pa.int64()}, - new=2, - arrow=3, - **cast("dict[str, DataValue]", {"inferred": {Point(3)}}), - ) - assert expanded.as_dict()["inferred"] == {Point(3)} - assert len(calls) == 1 - - with guard_calls() as calls: - updated = row.with_columns({"new": pa.int64()}, new=2) - assert updated.as_dict()["new"] == 2 - assert not calls - - -def test_public_schema_registration_checks_the_batch_once() -> None: - converter = create_registry().get_context().type_converter - with guard_calls() as calls: - converter.ensure_types_registered_for_schemas( - Schema({"ids": set[int]}), Schema({"names": list[str]}) - ) - assert len(calls) == 1 - - with ( - guard_calls() as calls, - pytest.raises( - NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" - ), - ): - converter.ensure_types_registered_for_schemas( - Schema({"ids": set[int]}), Schema({"points": set[Point]}) - ) - assert len(calls) == 1 - - -def test_dataclass_factory_uses_public_converter_protocol() -> None: - converter = create_registry().get_context().type_converter - members = { - name: staticmethod(getattr(converter, name)) - for name, method in vars(TypeConverterProtocol).items() - if not name.startswith("_") and callable(method) - } - adapter = type("PublicConverterAdapter", (), members)() - # The adapter exposes only the public factory protocol, with no fallback. - with guard_calls() as calls: - logical_type = DataclassLogicalTypeFactory().create_for_python_type( - PlainPoint, cast(TypeConverterProtocol, cast(object, adapter)) - ) - assert isinstance(adapter, TypeConverterProtocol) - assert logical_type.get_arrow_extension_type().storage_type == pa.struct( - [pa.field("x", pa.int64())] - ) - assert len(calls) == 1 - - -def test_rows_and_inference_never_call_the_guard() -> None: - with guard_calls() as calls: - pod = FunctionPod.from_fn(_inc, output_keys="out") - assert len(calls) == 1 - tag = Tag({"k": 0}) - data = Data({"x": 1}) - output = None - with guard_calls() as calls: - for _ in range(10_000): - _, output = pod.process_data(tag, data) - assert output is not None - assert output.as_dict() == {"out": 2} - - value = cast("dict[str, DataValue]", {"points": {Point(1)}}) - assert Data(value).as_table().num_rows == 1 - assert DictSource([value]).as_table().num_rows == 1 - table = _legacy_table().select(["points"]) - assert Tag(table).as_datagram().as_dict() == value - assert Data(table).as_datagram().as_dict() == value - assert calls == [] - - -def test_restoring_source_and_job_never_calls_the_guard( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setitem(SOURCE_REGISTRY, PollingSource.SOURCE_KIND, PollingSource) - schema = pa.schema([f.with_nullable(False) for f in _legacy_table().schema]) - source = PollingSource( - LegacyPoll(schema), tag_columns=[], record_id_columns="id", source_id="legacy" - ) - pod = FunctionPod.from_fn(_inc, output_keys="out") - 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) - - with guard_calls() as calls: - restored = PollingSource.from_config(source.to_config()) - assert restored.output_schema()[1]["points"] == set[Point] - assert PythonDataFunction.from_config( - pod.data_function.to_config() - ).output_data_schema == (pod.data_function.output_data_schema) - assert ( - FunctionPod.from_config(pod.to_config()).data_function.output_data_schema - == pod.data_function.output_data_schema - ) - loaded = op.PipelineJob.load(path, database=InMemoryArrowDatabase()) - assert loaded.nodes["mapped"].output_schema()[1]["renamed"] == set[Point] - assert isinstance(loaded.sources["legacy"], PollingSource) - assert 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(), b"{}") - - 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) - converter.register_logical_type_factory(WordFactory(), python_bases=[Word]) - assert converter.get_logical_type(Word) is None - rows = [cast("dict[str, DataValue]", {"words": {Word("a"), Word("z")}})] - source = DictSource(rows, data_schema={"words": set[Word]}, data_context=context) - assert converter.arrow_table_to_python_dicts(source.as_table()) == rows - - -def test_an_unresolved_class_does_not_trigger_the_refusal() -> None: - # Exact classes declared locally cannot be resolved by the built-in factory. - @dataclass(frozen=True) - class LocalPoint: - x: int - - row = cast("dict[str, DataValue]", {"points": {LocalPoint(1)}}) - assert Data(row, python_schema={"points": set[LocalPoint]}).as_dict() == row From 125f721f52cf4c2e97928f7099f2565cdc10c8e7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:40:43 -0800 Subject: [PATCH 07/20] fix(semantic-types): name the column in set write errors --- docs/concepts/your-own-data-types.md | 4 +- .../semantic_types/universal_converter.py | 12 +++-- .../test_user_class_set_conversion.py | 44 +++++++++++++++++++ 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/docs/concepts/your-own-data-types.md b/docs/concepts/your-own-data-types.md index ffb14edbf..6781304c1 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -50,7 +50,9 @@ structs. The error occurs when Orcapod first converts a Python set to Arrow stor 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. +ordering for these sets. 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 diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index cfc5531a1..179a29096 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1282,10 +1282,14 @@ 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: + converters[field_name] = self.get_python_to_arrow_converter(python_type) + except NestedTypeNotStorableError as exc: + raise with_context( + f"Column {field_name!r} ({python_type})", exc + ) from exc converted_data = [] for record in python_dicts: diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index c1af5b91d..f59b99f4b 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -275,6 +275,20 @@ def from_config( ) +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": {Point(1)}}], + data_schema={"points": set[Point]}, + source_id=config["source_name"], + ) + + 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) @@ -391,3 +405,33 @@ def test_a_set_converter_is_checked_once_for_many_rows_and_reuses_its_cache() -> second = converter.python_dicts_to_arrow_table(rows, schema) assert len(calls) == 1 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": set[Point]}, source_id="legacy" + ) + with guard_calls() as calls: + with pytest.raises( + NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" + ): + resolve_source_from_config(source.to_config()) + assert len(calls) == 1 + + 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"] == set[Point] + assert "Could not reconstruct source 'legacy'" in caplog.text + assert "NestedTypeNotStorableError" in caplog.text From 650f9c9ce93e86e94ac27bc78088879da78db20e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:43:56 -0800 Subject: [PATCH 08/20] test(semantic-types): type the custom source fixture --- tests/test_logical_types/test_user_class_set_conversion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index f59b99f4b..580abe5b2 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -283,7 +283,7 @@ def from_config( cls, config: dict[str, Any], db_registry: Any = None ) -> CustomRebuiltSource: return cls( - [{"points": {Point(1)}}], + [{"points": cast(DataValue, {Point(1)})}], data_schema={"points": set[Point]}, source_id=config["source_name"], ) From bb40cb1d665350cf0e54a6fb07891767937e882d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 23:28:16 -0800 Subject: [PATCH 09/20] fix(conversion): complete the user-class set refusal --- docs/dev/design_issues/ITL-922-SU1.md | 9 +- src/orcapod/core/data_function.py | 8 +- src/orcapod/semantic_types/nested_storage.py | 15 ++++ .../semantic_types/universal_converter.py | 88 ++++++++++++++----- .../test_user_class_set_conversion.py | 56 +++++++++--- 5 files changed, 137 insertions(+), 39 deletions(-) diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index c612be553..2b6db8ea7 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -1,13 +1,14 @@ ## `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:** open +**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. -Developer decision D47 places the temporary refusal where Orcapod builds the Python-to-Arrow -value converter for the set. Definitions and reads of stored data still work. Use -`list[T]` to store these values. ITL-1691 tracks the canonical storage order. +**Fix:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value +converter for the set. The check uses the resolved element type, and the converter caches +its decision for subsequent rows. The error directs writers to `list[T]`. Definitions and +reads of stored data still work. ITL-1691 tracks the canonical storage order. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 286c6a0ea..97cd0a993 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, @@ -1178,10 +1179,13 @@ def _convert_outputs( _ = converter.python_dicts_to_arrow_table( [{key: value}], python_schema={key: output_schema[key]} ) - except UnstorableDatetimeError as failure: + except ( + UnstorableDatetimeError, + UserClassSetNotStorableError, + ) as failure: # The datetime rule says what is wrong and how to convert, # without the value (ITL-1268); its own message names the value, - # so it is not chained. + # so it is not chained. A refused set also has a specific remedy. raise OutputTypeError( self.canonical_function_name, key, diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 37ee98ba6..b719a9c91 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -24,6 +24,21 @@ 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).""" + + reason = ( + "A set of user-class values cannot be stored in this version because " + "its element order would not be canonical" + ) + + def __init__(self, hint: str, *, context: str | None = None) -> None: + """Keep the migration hint available to callers that wrap this error.""" + self.hint = hint + prefix = f"{context}: " if context else "" + super().__init__(f"{prefix}{self.reason}. {hint}.") + + 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/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 179a29096..5339a3cae 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -23,6 +23,7 @@ from typing import TYPE_CHECKING, Any, TypedDict, get_args, get_origin import pyarrow as pa +from typing_extensions import TypeAliasType from orcapod.contexts import DataContext, resolve_context from orcapod.errors import ( @@ -46,6 +47,7 @@ ) 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 @@ -172,6 +174,25 @@ def _is_optional_type(python_type: DataType) -> bool: return False +def _set_element_annotation(annotation: Any) -> DataType: + """Resolve transparent wrappers on a set element, preserving its nullability.""" + origin = get_origin(annotation) + if origin is typing.Annotated: + return _set_element_annotation(get_args(annotation)[0]) + if isinstance(annotation, typing.NewType): + return _set_element_annotation(annotation.__supertype__) + if isinstance(annotation, TypeAliasType): + return _set_element_annotation(annotation.__value__) + if origin in (typing.Union, types.UnionType): + args = get_args(annotation) + if len(args) == 2 and type(None) in args: + inner = args[1] if args[0] is type(None) else args[0] + resolved = _set_element_annotation(inner) + if resolved is not inner: + return typing.Optional[resolved] + return annotation + + def storable_instant(value: object, timezone_policy: str) -> datetime: """Return ``value`` as a ``datetime`` column holds it, or refuse it (ITL-1268). @@ -271,8 +292,8 @@ def __init__( self._typeddict_to_struct_signature: dict[DataType, pa.StructType] = {} self._created_type_names: set[str] = set() - # Cache for conversion functions - self._python_to_arrow_converters: dict[DataType, Callable] = {} + # A string records the migration hint of a refused write converter. + self._python_to_arrow_converters: dict[DataType, Callable | str] = {} self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} # Cache for type mappings @@ -483,8 +504,9 @@ def _register_python_class_impl( "Unparameterized 'set' is not supported. Use 'set[T]' with a concrete " "element type (e.g. set[int], set[str])." ) - inner = self.register_python_class(args[0]) - require_restorable_none(args[0], inner, self._is_user_class_extension) + element = _set_element_annotation(args[0]) + inner = self.register_python_class(element) + require_restorable_none(element, inner, self._is_user_class_extension) if self._logical_type_registry is not None and hasattr( inner, "extension_name" ): @@ -1286,6 +1308,10 @@ def python_dicts_to_struct_dicts( for field_name, python_type in python_schema.items(): try: converters[field_name] = self.get_python_to_arrow_converter(python_type) + except UserClassSetNotStorableError as exc: + raise UserClassSetNotStorableError( + exc.hint, context=f"Column {field_name!r} ({python_type})" + ) from exc except NestedTypeNotStorableError as exc: raise with_context( f"Column {field_name!r} ({python_type})", exc @@ -1448,13 +1474,17 @@ def get_python_to_arrow_converter( This creates and caches conversion functions for optimal performance during data conversion operations. """ - if python_type in self._python_to_arrow_converters: - return self._python_to_arrow_converters[python_type] - - # Create conversion function - converter = self._create_python_to_arrow_converter(python_type) - self._python_to_arrow_converters[python_type] = converter - + converter = self._python_to_arrow_converters.get(python_type) + if converter is None: + try: + converter = self._create_python_to_arrow_converter(python_type) + except UserClassSetNotStorableError as exc: + self._python_to_arrow_converters[python_type] = exc.hint + raise + self._python_to_arrow_converters[python_type] = converter + if isinstance(converter, str): + # Raise a fresh exception to keep each row's traceback independent. + raise UserClassSetNotStorableError(converter) return converter def get_arrow_to_python_converter( @@ -1612,9 +1642,10 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: raise ValueError( f"set type must have exactly one type argument, got: {args}" ) - element_type = self.python_type_to_arrow_type(args[0]) + element = _set_element_annotation(args[0]) + element_type = self.python_type_to_arrow_type(element) require_restorable_none( - args[0], element_type, self._is_user_class_extension + element, element_type, self._is_user_class_extension ) if self._logical_type_registry is not None and hasattr( element_type, "extension_name" @@ -1859,17 +1890,26 @@ def _require_storable_set(self, element_type: DataType) -> None: """Refuse writes of sets whose user-class elements lack a canonical order.""" from orcapod.logical_types.user_class_identity import class_kind - if not isinstance(element_type, type) or class_kind(element_type) is None: + try: + arrow_type = self.register_python_class(element_type) + except (TypeError, ValueError): + # The normal conversion path reports unsupported element annotations. return - element = self.get_logical_type_for_python_type(element_type) - if element is not None and pa.types.is_struct( - element.get_arrow_extension_type().storage_type + if isinstance(arrow_type, pa.ExtensionType) and pa.types.is_struct( + arrow_type.storage_type ): - raise NestedTypeNotStorableError( - "A set of user-class values cannot be stored in this version because " - "its element order would not be canonical. " - f"Use list[{element_type.__qualname__}]." + logical_type = self.get_logical_type_by_arrow_extension_name( + arrow_type.extension_name ) + if logical_type is not None: + python_type = logical_type.python_type + if ( + isinstance(python_type, type) + and class_kind(python_type) is not None + ): + raise UserClassSetNotStorableError( + f"Use list[{python_type.__qualname__}]" + ) def _create_python_to_arrow_converter( self, python_type: DataType @@ -1878,7 +1918,7 @@ def _create_python_to_arrow_converter( origin = get_origin(python_type) if origin is set and len(set_args := get_args(python_type)) == 1: - self._require_storable_set(set_args[0]) + self._require_storable_set(_set_element_annotation(set_args[0])) # Check LogicalTypeRegistry first — extension-type identity takes priority. # GenericAlias instances like list[UUID] or set[UUID] may be registered as @@ -1968,7 +2008,9 @@ def convert_dict(value: Any) -> list[dict[str, Any]]: elif origin is set: # A set has no order: elements are stored sorted, never in iteration # order, which depends on PYTHONHASHSEED for str and bytes (ITL-905). - element_converter = self.get_python_to_arrow_converter(args[0]) + element_converter = self.get_python_to_arrow_converter( + _set_element_annotation(args[0]) + ) def convert_set(value: Any) -> list[Any]: if value is None: diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 580abe5b2..6341e96aa 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -10,12 +10,13 @@ from pathlib import Path from textwrap import dedent from types import FrameType -from typing import Any, cast +from typing import Annotated, Any, NewType, Optional, cast import polars as pl import pydantic import pyarrow as pa import pytest +from typing_extensions import TypeAliasType import orcapod as op from orcapod.contexts import create_registry, get_default_context @@ -45,6 +46,10 @@ class Point: x: int +NamedPoint = NewType("NamedPoint", Point) +PointAlias = TypeAliasType("PointAlias", Point) + + @dataclass class PointSet: points: set[Point] @@ -188,6 +193,26 @@ def test_dict_source_refuses_each_struct_stored_class_kind(value: Any) -> None: DictSource([{"points": {value}}]) +@pytest.mark.parametrize( + ("element", "values"), + [ + (Point | None, {Point(1), None}), + (Optional[Point], {Point(1)}), + (NamedPoint, {Point(1)}), + (Annotated[Point, "point metadata"], {Point(1)}), + (PointAlias, {Point(1)}), + (Annotated[PointAlias | None, "point metadata"], {Point(1), None}), + ], +) +def test_source_refuses_wrapped_user_class_set_elements( + element: Any, values: Any +) -> None: + with pytest.raises( + NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" + ): + DictSource([{"points": values}], data_schema={"points": set[element]}) + + def test_other_python_sources_refuse_the_conversion() -> None: values = cast("list[DataValue]", [{Point(1)}]) with pytest.raises(NestedTypeNotStorableError, match=r"Use list\[Point\]"): @@ -220,7 +245,7 @@ def test_python_rows_refuse_table_conversion_and_hashing(row_type: Any) -> None: def test_nested_sets_refused_at_the_same_conversion_boundary( annotation: Any, value: Any ) -> None: - converter = get_default_context().type_converter + 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}) @@ -235,22 +260,30 @@ def test_dict_values_follow_the_existing_nested_storage_rule() -> None: ) -@pytest.mark.asyncio -async def test_sync_and_async_function_pod_outputs_fail_at_conversion() -> None: +def test_sync_function_pod_output_includes_the_migration_hint() -> None: source = DictSource([{"x": 1}]) - with pytest.raises(OutputTypeError, match="NestedTypeNotStorableError"): + with pytest.raises(OutputTypeError, match=r"output 'points'.*Use list\[Point\]"): list(points_sync.pod(source).iter_data()) - with pytest.raises(OutputTypeError, match="NestedTypeNotStorableError"): + + +@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_writes_no_tables() -> None: +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": 1}]), label="points") - with pytest.warns(RowFailuresWarning, match="NestedTypeNotStorableError"): + 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 len(calls) == 1 assert list(database.list_table_paths(())) == [] @@ -416,6 +449,9 @@ def test_custom_restore_that_builds_python_rows_is_a_write( source = CustomRebuiltSource( [], data_schema={"points": 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\]" @@ -434,4 +470,4 @@ def test_custom_restore_that_builds_python_rows_is_a_write( assert not restored.sources assert restored.nodes["mapped"].output_schema()[1]["renamed"] == set[Point] assert "Could not reconstruct source 'legacy'" in caplog.text - assert "NestedTypeNotStorableError" in caplog.text + assert "UserClassSetNotStorableError" in caplog.text From 507787937480962c6c155f71648141f44befab39 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 00:03:59 -0800 Subject: [PATCH 10/20] fix(conversion): keep the user-class set check read-only --- .zed/rules | 8 +- CLAUDE.md | 8 +- docs/dev/design_issues/ITL-922-SU1.md | 7 +- src/orcapod/pipeline/job.py | 9 +- .../semantic_types/universal_converter.py | 166 ++++++++++++------ .../test_user_class_set_conversion.py | 63 ++++++- 6 files changed, 190 insertions(+), 71 deletions(-) diff --git a/.zed/rules b/.zed/rules index 755713dca..ad1accabc 100644 --- a/.zed/rules +++ b/.zed/rules @@ -478,9 +478,11 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 - 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, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow - value converter (developer decision D47, ITL-922). Resolve the element through the - converter and its factories. Declarations and Arrow reads use their existing paths. - Direct writers to `list[T]`. ITL-1691 tracks canonical ordering. + value converter (developer decision D47, ITL-922). Inspect the element through the + converter's registered types and factory selection without changing the annotation + or registering a type. Declarations and Arrow reads use their existing paths. + Direct writers to `list[T]`, including in warnings when a saved source rebuilds + from Python rows. 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 f9792cf23..9285f6724 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -489,9 +489,11 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 - 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, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow - value converter (developer decision D47, ITL-922). Resolve the element through the - converter and its factories. Declarations and Arrow reads use their existing paths. - Direct writers to `list[T]`. ITL-1691 tracks canonical ordering. + value converter (developer decision D47, ITL-922). Inspect the element through the + converter's registered types and factory selection without changing the annotation + or registering a type. Declarations and Arrow reads use their existing paths. + Direct writers to `list[T]`, including in warnings when a saved source rebuilds + from Python rows. 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/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index 2b6db8ea7..9f7bb3061 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -9,6 +9,7 @@ The stored order of a set of struct-stored user classes can follow the set's ite order, so equal sets can have different stored representations and row hashes. **Fix:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value -converter for the set. The check uses the resolved element type, and the converter caches -its decision for subsequent rows. The error directs writers to `list[T]`. Definitions and -reads of stored data still work. ITL-1691 tracks the canonical storage order. +converter for the set. The check inspects the element type without changing its +annotation or registering a type. The converter caches the decision for subsequent rows. +The error directs writers to `list[T]`, including in the warning when a saved source's +rebuild attempts the write. ITL-1691 tracks the canonical storage order. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index e9d494c6e..3c4c529b0 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -64,6 +64,7 @@ require_live_source_bindings, ) from orcapod.protocols import core_protocols as cp +from orcapod.semantic_types.nested_storage import UserClassSetNotStorableError from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.types import NodeConfig from orcapod.utils.database_errors import ( @@ -2345,6 +2346,11 @@ def load( elif isinstance(failure, Warning): raise failure elif failure is not None: + diagnostic = type(failure).__name__ + # This library-generated refusal describes the column and remedy. + # Other exception text may expose source configuration (ITL-1391). + if isinstance(failure, UserClassSetNotStorableError): + diagnostic = f"{diagnostic}: {str(failure).removesuffix('.')}" logger.warning( "Could not reconstruct source %r (%s) from its saved config: %s. " "Stored function-node results are still readable from the database. " @@ -2352,8 +2358,7 @@ def load( "job.bind(sources={%r: }).", spec_name, saved_source_kind(src_config), - # Its type, never its text (ITL-1391). - type(failure).__name__, + diagnostic, spec_name, spec_name, ) diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 5339a3cae..1e8750f22 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -20,7 +20,7 @@ from datetime import date, datetime, timezone # Handle generic types -from typing import TYPE_CHECKING, Any, TypedDict, get_args, get_origin +from typing import TYPE_CHECKING, Any, TypedDict, cast, get_args, get_origin import pyarrow as pa from typing_extensions import TypeAliasType @@ -174,23 +174,47 @@ def _is_optional_type(python_type: DataType) -> bool: return False -def _set_element_annotation(annotation: Any) -> DataType: - """Resolve transparent wrappers on a set element, preserving its nullability.""" +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 _nested_set_annotations(annotation: DataType) -> Iterable[DataType]: + """Find set converters a failed write schema may have prevented us building.""" origin = get_origin(annotation) - if origin is typing.Annotated: - return _set_element_annotation(get_args(annotation)[0]) - if isinstance(annotation, typing.NewType): - return _set_element_annotation(annotation.__supertype__) - if isinstance(annotation, TypeAliasType): - return _set_element_annotation(annotation.__value__) - if origin in (typing.Union, types.UnionType): - args = get_args(annotation) - if len(args) == 2 and type(None) in args: - inner = args[1] if args[0] is type(None) else args[0] - resolved = _set_element_annotation(inner) - if resolved is not inner: - return typing.Optional[resolved] - return annotation + if origin is set: + yield annotation + elif origin in (list, tuple) or _is_optional_type(annotation): + for arg in get_args(annotation): + yield from _nested_set_annotations(arg) def storable_instant(value: object, timezone_policy: str) -> datetime: @@ -504,9 +528,8 @@ def _register_python_class_impl( "Unparameterized 'set' is not supported. Use 'set[T]' with a concrete " "element type (e.g. set[int], set[str])." ) - element = _set_element_annotation(args[0]) - inner = self.register_python_class(element) - require_restorable_none(element, inner, self._is_user_class_extension) + inner = self.register_python_class(args[0]) + require_restorable_none(args[0], inner, self._is_user_class_extension) if self._logical_type_registry is not None and hasattr( inner, "extension_name" ): @@ -1312,10 +1335,6 @@ def python_dicts_to_struct_dicts( raise UserClassSetNotStorableError( exc.hint, context=f"Column {field_name!r} ({python_type})" ) from exc - except NestedTypeNotStorableError as exc: - raise with_context( - f"Column {field_name!r} ({python_type})", exc - ) from exc converted_data = [] for record in python_dicts: @@ -1416,8 +1435,15 @@ def python_dicts_to_arrow_table( # ensure_types_registered_for_schemas is idempotent and thread-safe; it is # 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) + try: + self.ensure_types_registered_for_schemas(cast(Schema, python_schema)) + arrow_schema = self.python_schema_to_arrow_schema(python_schema) + except (NestedNoneNotRestorableError, NestedTypeNotStorableError): + raise + except ValueError: + if python_dicts: + self._diagnose_set_write(python_schema) + raise if python_schema is None: assert arrow_schema is not None, ( @@ -1642,10 +1668,9 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: raise ValueError( f"set type must have exactly one type argument, got: {args}" ) - element = _set_element_annotation(args[0]) - element_type = self.python_type_to_arrow_type(element) + element_type = self.python_type_to_arrow_type(args[0]) require_restorable_none( - element, element_type, self._is_user_class_extension + args[0], element_type, self._is_user_class_extension ) if self._logical_type_registry is not None and hasattr( element_type, "extension_name" @@ -1886,30 +1911,65 @@ def _generate_unique_type_name(self, field_specs: Mapping[str, DataType]) -> str self._created_type_names.add(base_name) return base_name - def _require_storable_set(self, element_type: DataType) -> None: - """Refuse writes of sets whose user-class elements lack a canonical order.""" + def _is_set_of_struct_user_class(self, python_type: DataType) -> bool: + """Check how a set's element would be stored without registering any types.""" + from orcapod.logical_types.dataclass_logical_type_factory import ( + DataclassLogicalTypeFactory, + ) + from orcapod.logical_types.pydantic_logical_type_factory import ( + PydanticLogicalTypeFactory, + ) + from orcapod.logical_types.structural_logical_type_factory import ( + StructuralLogicalTypeFactory, + ) from orcapod.logical_types.user_class_identity import class_kind + from orcapod.utils.deferred_types import qualified_name - try: - arrow_type = self.register_python_class(element_type) - except (TypeError, ValueError): - # The normal conversion path reports unsupported element annotations. - return - if isinstance(arrow_type, pa.ExtensionType) and pa.types.is_struct( - arrow_type.storage_type + registry = self._logical_type_registry + element = _unwrapped_set_element(python_type) + if registry is None or element is None or class_kind(element) is None: + return False + + logical_type = registry._by_python_type.get(element) + if logical_type is None and not any( + qualified_name(base) in registry._deferred_by_python_name + for base in element.__mro__ ): - logical_type = self.get_logical_type_by_arrow_extension_name( - arrow_type.extension_name - ) - if logical_type is not None: - python_type = logical_type.python_type - if ( - isinstance(python_type, type) - and class_kind(python_type) is not None - ): + logical_type = registry._find_by_python_type(element) + if logical_type is None: + # For a wrapper the schema cannot derive, the standard factories + # always produce structs. Leave arbitrary factories to registration. + return type(self._find_factory_for_class(element)) in ( + DataclassLogicalTypeFactory, + PydanticLogicalTypeFactory, + StructuralLogicalTypeFactory, + ) + return logical_type is not None and pa.types.is_struct( + logical_type.get_arrow_extension_type().storage_type + ) + + def _check_set_write(self, python_type: DataType) -> None: + """Check a set converter once and cache the diagnostic if it is refused.""" + cached = self._python_to_arrow_converters.get(python_type) + if isinstance(cached, str): + raise UserClassSetNotStorableError(cached) + if cached is None and self._is_set_of_struct_user_class(python_type): + element = _unwrapped_set_element(python_type) + assert element is not None + hint = f"Use list[{element.__qualname__}]" + self._python_to_arrow_converters[python_type] = hint + raise UserClassSetNotStorableError(hint) + + def _diagnose_set_write(self, python_schema: SchemaLike) -> None: + """Recover the write diagnostic if schema derivation failed first.""" + for name, annotation in python_schema.items(): + for set_type in _nested_set_annotations(annotation): + try: + self._check_set_write(set_type) + except UserClassSetNotStorableError as exc: raise UserClassSetNotStorableError( - f"Use list[{python_type.__qualname__}]" - ) + exc.hint, context=f"Column {name!r} ({annotation})" + ) from exc def _create_python_to_arrow_converter( self, python_type: DataType @@ -1917,8 +1977,8 @@ def _create_python_to_arrow_converter( """Create a cached conversion function for Python → Arrow values.""" origin = get_origin(python_type) - if origin is set and len(set_args := get_args(python_type)) == 1: - self._require_storable_set(_set_element_annotation(set_args[0])) + if origin is set: + self._check_set_write(python_type) # Check LogicalTypeRegistry first — extension-type identity takes priority. # GenericAlias instances like list[UUID] or set[UUID] may be registered as @@ -2008,9 +2068,7 @@ def convert_dict(value: Any) -> list[dict[str, Any]]: elif origin is set: # A set has no order: elements are stored sorted, never in iteration # order, which depends on PYTHONHASHSEED for str and bytes (ITL-905). - element_converter = self.get_python_to_arrow_converter( - _set_element_annotation(args[0]) - ) + element_converter = self.get_python_to_arrow_converter(args[0]) def convert_set(value: Any) -> list[Any]: if value is None: diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 6341e96aa..86d808288 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -4,6 +4,7 @@ import subprocess import sys +import typing from collections.abc import Callable, Iterator from contextlib import contextmanager from dataclasses import dataclass @@ -48,6 +49,10 @@ class Point: NamedPoint = NewType("NamedPoint", Point) PointAlias = TypeAliasType("PointAlias", Point) +NativePointAlias = getattr(typing, "TypeAliasType", TypeAliasType)( + "NativePointAlias", Point +) +NamedPointAlias = TypeAliasType("NamedPointAlias", NamedPoint) @dataclass @@ -97,7 +102,7 @@ def guard_calls() -> Iterator[list[str]]: calls: list[str] = [] def record(frame: FrameType, event: str, arg: object) -> None: - if event == "call" and frame.f_code.co_name == "_require_storable_set": + if event == "call" and frame.f_code.co_name == "_is_set_of_struct_user_class": calls.append(frame.f_code.co_name) previous = sys.getprofile() @@ -201,16 +206,60 @@ def test_dict_source_refuses_each_struct_stored_class_kind(value: Any) -> None: (NamedPoint, {Point(1)}), (Annotated[Point, "point metadata"], {Point(1)}), (PointAlias, {Point(1)}), + (NativePointAlias, {Point(1)}), (Annotated[PointAlias | None, "point metadata"], {Point(1), None}), + (Annotated[NamedPointAlias | None, "point metadata"], {Point(1)}), ], ) +@pytest.mark.parametrize("nested", [False, True]) def test_source_refuses_wrapped_user_class_set_elements( - element: Any, values: Any + element: Any, values: Any, nested: bool +) -> None: + annotation = list[set[element]] if nested else set[element] + value = [values] if nested else values + context = create_registry().get_context() + with guard_calls() as calls: + for _ in range(2): + with pytest.raises( + NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" + ): + DictSource( + [{"points": value}], + data_schema={"points": annotation}, + data_context=context, + ) + assert len(calls) == 1 + + +@pytest.mark.parametrize("element", [Point, int, Word]) +def test_wrapped_set_annotations_preserve_schema_errors_and_registry( + element: type, ) -> None: - with pytest.raises( - NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" + 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([{"points": values}], data_schema={"points": set[element]}) + 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")} + ) + error = "Use list" if element is Point else "Unsupported annotation" + with pytest.raises(ValueError, match=error): + DictSource( + [{"points": value}], + data_schema={"points": annotation}, + data_context=context, + ) + assert converter.registered_logical_type_names() == before def test_other_python_sources_refuse_the_conversion() -> None: @@ -371,7 +420,7 @@ def test_a_cold_ipc_read_can_import_a_module_defining_a_set_output( 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 == "_require_storable_set": + if event == "call" and frame.f_code.co_name == "_is_set_of_struct_user_class": raise AssertionError("An Arrow read entered the write check") sys.setprofile(profile) converter = get_default_context().type_converter @@ -471,3 +520,5 @@ def test_custom_restore_that_builds_python_rows_is_a_write( assert restored.nodes["mapped"].output_schema()[1]["renamed"] == set[Point] assert "Could not reconstruct source 'legacy'" in caplog.text assert "UserClassSetNotStorableError" in caplog.text + assert "Column 'points'" in caplog.text + assert "Use list[Point]" in caplog.text From 56b248657581b5583570d01ea01b948be423181e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 00:38:16 -0800 Subject: [PATCH 11/20] fix(conversion): simplify user-class set refusal diagnostics --- .zed/rules | 3 +- CLAUDE.md | 3 +- docs/dev/design_issues/ITL-922-SU1.md | 4 +- src/orcapod/core/data_function.py | 13 +- src/orcapod/pipeline/job.py | 9 +- src/orcapod/semantic_types/nested_storage.py | 11 -- .../semantic_types/universal_converter.py | 66 ++----- .../sources/test_repeated_dict_keys.py | 25 ++- .../test_user_class_set_conversion.py | 183 +++++++++++++----- 9 files changed, 190 insertions(+), 127 deletions(-) diff --git a/.zed/rules b/.zed/rules index ad1accabc..fd4447565 100644 --- a/.zed/rules +++ b/.zed/rules @@ -481,8 +481,7 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 value converter (developer decision D47, ITL-922). Inspect the element through the converter's registered types and factory selection without changing the annotation or registering a type. Declarations and Arrow reads use their existing paths. - Direct writers to `list[T]`, including in warnings when a saved source rebuilds - from Python rows. ITL-1691 tracks canonical ordering. + 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 9285f6724..a0b9f8f75 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -492,8 +492,7 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 value converter (developer decision D47, ITL-922). Inspect the element through the converter's registered types and factory selection without changing the annotation or registering a type. Declarations and Arrow reads use their existing paths. - Direct writers to `list[T]`, including in warnings when a saved source rebuilds - from Python rows. ITL-1691 tracks canonical ordering. + 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/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index 9f7bb3061..a8998616e 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -11,5 +11,5 @@ order, so equal sets can have different stored representations and row hashes. **Fix:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value converter for the set. The check inspects the element type without changing its annotation or registering a type. The converter caches the decision for subsequent rows. -The error directs writers to `list[T]`, including in the warning when a saved source's -rebuild attempts the write. ITL-1691 tracks the canonical storage order. +The conversion error directs writers to `list[T]`. ITL-1691 tracks the canonical +storage order. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 97cd0a993..0f960e8a7 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1179,13 +1179,10 @@ def _convert_outputs( _ = converter.python_dicts_to_arrow_table( [{key: value}], python_schema={key: output_schema[key]} ) - except ( - UnstorableDatetimeError, - UserClassSetNotStorableError, - ) as failure: + except UnstorableDatetimeError as failure: # The datetime rule says what is wrong and how to convert, # without the value (ITL-1268); its own message names the value, - # so it is not chained. A refused set also has a specific remedy. + # so it is not chained. raise OutputTypeError( self.canonical_function_name, key, @@ -1194,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/pipeline/job.py b/src/orcapod/pipeline/job.py index 3c4c529b0..e9d494c6e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -64,7 +64,6 @@ require_live_source_bindings, ) from orcapod.protocols import core_protocols as cp -from orcapod.semantic_types.nested_storage import UserClassSetNotStorableError from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.types import NodeConfig from orcapod.utils.database_errors import ( @@ -2346,11 +2345,6 @@ def load( elif isinstance(failure, Warning): raise failure elif failure is not None: - diagnostic = type(failure).__name__ - # This library-generated refusal describes the column and remedy. - # Other exception text may expose source configuration (ITL-1391). - if isinstance(failure, UserClassSetNotStorableError): - diagnostic = f"{diagnostic}: {str(failure).removesuffix('.')}" logger.warning( "Could not reconstruct source %r (%s) from its saved config: %s. " "Stored function-node results are still readable from the database. " @@ -2358,7 +2352,8 @@ def load( "job.bind(sources={%r: }).", spec_name, saved_source_kind(src_config), - diagnostic, + # Its type, never its text (ITL-1391). + type(failure).__name__, spec_name, spec_name, ) diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index b719a9c91..9496ca503 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -27,17 +27,6 @@ class NestedTypeNotStorableError(ValueError): class UserClassSetNotStorableError(NestedTypeNotStorableError): """A set of struct-stored user classes has no canonical storage order (ITL-922).""" - reason = ( - "A set of user-class values cannot be stored in this version because " - "its element order would not be canonical" - ) - - def __init__(self, hint: str, *, context: str | None = None) -> None: - """Keep the migration hint available to callers that wrap this error.""" - self.hint = hint - prefix = f"{context}: " if context else "" - super().__init__(f"{prefix}{self.reason}. {hint}.") - 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/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index aa748e93c..61ca7d6c1 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -54,6 +54,7 @@ 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.logical_types.registry import LogicalTypeRegistry @@ -208,16 +209,6 @@ def _unwrapped_set_element(annotation: DataType) -> type | None: return element -def _nested_set_annotations(annotation: DataType) -> Iterable[DataType]: - """Find set converters a failed write schema may have prevented us building.""" - origin = get_origin(annotation) - if origin is set: - yield annotation - elif origin in (list, tuple) or _is_optional_type(annotation): - for arg in get_args(annotation): - yield from _nested_set_annotations(arg) - - def storable_instant(value: object, timezone_policy: str) -> datetime: """Return ``value`` as a ``datetime`` column holds it, or refuse it (ITL-1268). @@ -317,7 +308,7 @@ def __init__( self._typeddict_to_struct_signature: dict[DataType, pa.StructType] = {} self._created_type_names: set[str] = set() - # A string records the migration hint of a refused write converter. + # A string records the message of a refused write converter. self._python_to_arrow_converters: dict[DataType, Callable | str] = {} self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} @@ -1334,7 +1325,7 @@ def python_dicts_to_struct_dicts( converters[field_name] = self.get_python_to_arrow_converter(python_type) except UserClassSetNotStorableError as exc: raise UserClassSetNotStorableError( - exc.hint, context=f"Column {field_name!r} ({python_type})" + f"Column {field_name!r}: {exc}" ) from exc converted_data = [] @@ -1349,6 +1340,10 @@ def python_dicts_to_struct_dicts( raise CanonicalOrderError( f"Column {field_name!r}: {exc}" ) from exc + except UserClassSetNotStorableError as exc: + raise UserClassSetNotStorableError( + 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( @@ -1436,15 +1431,8 @@ def python_dicts_to_arrow_table( # ensure_types_registered_for_schemas is idempotent and thread-safe; it is # a no-op for primitives and already-registered types. assert python_schema is not None, "Python schema should not be None here" - try: - self.ensure_types_registered_for_schemas(cast(Schema, python_schema)) - arrow_schema = self.python_schema_to_arrow_schema(python_schema) - except (NestedNoneNotRestorableError, NestedTypeNotStorableError): - raise - except ValueError: - if python_dicts: - self._diagnose_set_write(python_schema) - raise + 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, ( @@ -1509,7 +1497,7 @@ def get_python_to_arrow_converter( try: converter = self._create_python_to_arrow_converter(python_type) except UserClassSetNotStorableError as exc: - self._python_to_arrow_converters[python_type] = exc.hint + self._python_to_arrow_converters[python_type] = str(exc) raise self._python_to_arrow_converters[python_type] = converter if isinstance(converter, str): @@ -1911,7 +1899,7 @@ def _generate_unique_type_name(self, field_specs: Mapping[str, DataType]) -> str self._created_type_names.add(base_name) return base_name - def _is_set_of_struct_user_class(self, python_type: DataType) -> bool: + def _is_set_of_struct_user_class(self, element: type) -> bool: """Check how a set's element would be stored without registering any types.""" from orcapod.logical_types.dataclass_logical_type_factory import ( DataclassLogicalTypeFactory, @@ -1923,11 +1911,9 @@ def _is_set_of_struct_user_class(self, python_type: DataType) -> bool: StructuralLogicalTypeFactory, ) from orcapod.logical_types.user_class_identity import class_kind - from orcapod.utils.deferred_types import qualified_name registry = self._logical_type_registry - element = _unwrapped_set_element(python_type) - if registry is None or element is None or class_kind(element) is None: + if registry is None or class_kind(element) is None: return False logical_type = registry._by_python_type.get(element) @@ -1949,27 +1935,13 @@ def _is_set_of_struct_user_class(self, python_type: DataType) -> bool: ) def _check_set_write(self, python_type: DataType) -> None: - """Check a set converter once and cache the diagnostic if it is refused.""" - cached = self._python_to_arrow_converters.get(python_type) - if isinstance(cached, str): - raise UserClassSetNotStorableError(cached) - if cached is None and self._is_set_of_struct_user_class(python_type): - element = _unwrapped_set_element(python_type) - assert element is not None - hint = f"Use list[{element.__qualname__}]" - self._python_to_arrow_converters[python_type] = hint - raise UserClassSetNotStorableError(hint) - - def _diagnose_set_write(self, python_schema: SchemaLike) -> None: - """Recover the write diagnostic if schema derivation failed first.""" - for name, annotation in python_schema.items(): - for set_type in _nested_set_annotations(annotation): - try: - self._check_set_write(set_type) - except UserClassSetNotStorableError as exc: - raise UserClassSetNotStorableError( - exc.hint, context=f"Column {name!r} ({annotation})" - ) from exc + """Refuse a set whose elements are user classes stored as structs.""" + element = _unwrapped_set_element(python_type) + if element is not None and self._is_set_of_struct_user_class(element): + raise UserClassSetNotStorableError( + f"a set of {qualified_name(element)} values cannot be stored in this " + f"version; use list[{element.__name__}]." + ) def _create_python_to_arrow_converter( self, python_type: DataType 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_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 86d808288..0c0910159 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -10,13 +10,15 @@ from dataclasses import dataclass from pathlib import Path from textwrap import dedent -from types import FrameType +from types import UnionType from typing import Annotated, Any, NewType, Optional, cast import polars as pl import pydantic import pyarrow as pa import pytest +from unittest.mock import patch + from typing_extensions import TypeAliasType import orcapod as op @@ -34,13 +36,18 @@ ) 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_storage import NestedTypeNotStorableError +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.types import DataType, 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: @@ -98,19 +105,16 @@ async def close(self) -> None: @contextmanager def guard_calls() -> Iterator[list[str]]: - """Count calls through every imported reference to the same guard.""" + """Record the immediate caller of every invocation of the write check.""" calls: list[str] = [] + check = UniversalTypeConverter._check_set_write - def record(frame: FrameType, event: str, arg: object) -> None: - if event == "call" and frame.f_code.co_name == "_is_set_of_struct_user_class": - calls.append(frame.f_code.co_name) + def record(converter: UniversalTypeConverter, python_type: DataType) -> None: + calls.append(sys._getframe(1).f_code.co_name) + check(converter, python_type) - previous = sys.getprofile() - sys.setprofile(record) - try: + with patch.object(UniversalTypeConverter, "_check_set_write", record): yield calls - finally: - sys.setprofile(previous) @dataclass(frozen=True) @@ -194,7 +198,10 @@ async def points_async(x: int) -> set[Point]: @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"canonical.*Use list\["): + with pytest.raises( + NestedTypeNotStorableError, + match=r"cannot be stored in this version; use list\[", + ): DictSource([{"points": {value}}]) @@ -204,31 +211,51 @@ def test_dict_source_refuses_each_struct_stored_class_kind(value: Any) -> None: (Point | None, {Point(1), None}), (Optional[Point], {Point(1)}), (NamedPoint, {Point(1)}), - (Annotated[Point, "point metadata"], {Point(1)}), + (Annotated[Point, _METADATA], {Point(1)}), (PointAlias, {Point(1)}), (NativePointAlias, {Point(1)}), - (Annotated[PointAlias | None, "point metadata"], {Point(1), None}), - (Annotated[NamedPointAlias | None, "point metadata"], {Point(1)}), + (Annotated[PointAlias | None, _METADATA], {Point(1), None}), + (Annotated[NamedPointAlias | None, _METADATA], {Point(1)}), ], ) @pytest.mark.parametrize("nested", [False, True]) -def test_source_refuses_wrapped_user_class_set_elements( +def test_converter_refuses_wrapped_user_class_set_elements( element: Any, values: Any, nested: bool ) -> None: annotation = list[set[element]] if nested else set[element] value = [values] if nested else values - context = create_registry().get_context() + converter = create_registry().get_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + # 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}) + converter.ensure_types_registered_for_schemas(declared) + arrow_schema = converter.python_schema_to_arrow_schema(declared) with guard_calls() as calls: + if nested and typing.get_origin(element) 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( - NestedTypeNotStorableError, match=r"Column 'points'.*Use list\[Point\]" - ): - DictSource( - [{"points": value}], - data_schema={"points": annotation}, - data_context=context, + UserClassSetNotStorableError, + match=r"Column 'points'.*use list\[Point\]", + ) as error: + converter.python_dicts_to_arrow_table( + [{"points": value}], {"points": annotation}, arrow_schema ) - assert len(calls) == 1 + 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) + assert calls == ["_create_python_to_arrow_converter"] @pytest.mark.parametrize("element", [Point, int, Word]) @@ -252,21 +279,24 @@ def test_wrapped_set_annotations_preserve_schema_errors_and_registry( value: Any = ( {Point(1)} if element is Point else {1} if element is int else {Word("a")} ) - error = "Use list" if element is Point else "Unsupported annotation" - with pytest.raises(ValueError, match=error): + 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\]"): + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): ListSource("points", values) - with pytest.raises(NestedTypeNotStorableError, match=r"Use list\[Point\]"): + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): DataFrameSource(pl.DataFrame({"points": pl.Series(values, dtype=pl.Object)})) @@ -277,9 +307,9 @@ def test_python_rows_refuse_table_conversion_and_hashing(row_type: Any) -> None: 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\]"): + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): row.as_table() - with pytest.raises(NestedTypeNotStorableError, match=r"Use list\[Point\]"): + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): row.content_hash() @@ -287,6 +317,7 @@ def test_python_rows_refuse_table_conversion_and_hashing(row_type: Any) -> None: ("annotation", "value"), [ (list[set[Point]], [{Point(1)}]), + (list[set[Point | None]], [{Point(1), None}]), (set[Point] | None, {Point(1)}), (PointSet, PointSet({Point(1)})), ], @@ -296,9 +327,9 @@ def test_nested_sets_refused_at_the_same_conversion_boundary( ) -> None: converter = create_registry().get_context().type_converter with guard_calls() as calls: - with pytest.raises(NestedTypeNotStorableError, match=r"Use list\[Point\]"): + with pytest.raises(NestedTypeNotStorableError, match=r"use list\[Point\]"): converter.python_dicts_to_arrow_table([{"v": value}], {"v": annotation}) - assert len(calls) == 1 + assert calls == ["_create_python_to_arrow_converter"] def test_dict_values_follow_the_existing_nested_storage_rule() -> None: @@ -311,14 +342,14 @@ def test_dict_values_follow_the_existing_nested_storage_rule() -> None: 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\]"): + 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\]"): + with pytest.raises(OutputTypeError, match=r"output 'points'.*use list\[Point\]"): _ = [row async for row in points_async.pod(source).async_iter_data()] @@ -332,7 +363,7 @@ def test_a_failed_job_checks_the_set_once_and_writes_no_tables() -> None: 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 len(calls) == 1 + assert calls == ["_create_python_to_arrow_converter"] assert list(database.list_table_paths(())) == [] @@ -365,8 +396,8 @@ def from_config( cls, config: dict[str, Any], db_registry: Any = None ) -> CustomRebuiltSource: return cls( - [{"points": cast(DataValue, {Point(1)})}], - data_schema={"points": set[Point]}, + [{"points": cast(DataValue, [{Point(1)}])}], + data_schema={"points": list[set[Point]]}, source_id=config["source_name"], ) @@ -420,7 +451,7 @@ def test_a_cold_ipc_read_can_import_a_module_defining_a_set_output( 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 == "_is_set_of_struct_user_class": + 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 @@ -485,7 +516,7 @@ def test_a_set_converter_is_checked_once_for_many_rows_and_reuses_its_cache() -> with guard_calls() as calls: first = converter.python_dicts_to_arrow_table(rows, schema) second = converter.python_dicts_to_arrow_table(rows, schema) - assert len(calls) == 1 + assert calls == ["_create_python_to_arrow_converter"] assert first.equals(second) @@ -496,17 +527,17 @@ def test_custom_restore_that_builds_python_rows_is_a_write( SOURCE_REGISTRY, CustomRebuiltSource.SOURCE_KIND, CustomRebuiltSource ) source = CustomRebuiltSource( - [], data_schema={"points": set[Point]}, source_id="legacy" + [], 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\]" + NestedTypeNotStorableError, match=r"Column 'points'.*use list\[Point\]" ): resolve_source_from_config(source.to_config()) - assert len(calls) == 1 + assert calls == ["_create_python_to_arrow_converter"] job = op.PipelineJob(name="legacy", database=InMemoryArrowDatabase()) with job: @@ -517,8 +548,68 @@ def test_custom_restore_that_builds_python_rows_is_a_write( restored = op.PipelineJob.load(path, database=InMemoryArrowDatabase()) assert restored.unbound_sources == ["legacy"] assert not restored.sources - assert restored.nodes["mapped"].output_schema()[1]["renamed"] == set[Point] + 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'" in caplog.text - assert "Use list[Point]" 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 From 56ca4a8d648684b9f66620435a8ee64abe460aeb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 01:24:30 -0800 Subject: [PATCH 12/20] fix(conversion): refuse sets of deferred struct types --- .zed/rules | 6 +- CLAUDE.md | 6 +- docs/dev/design_issues/ITL-922-SU1.md | 4 +- .../semantic_types/universal_converter.py | 86 +++++++---- .../test_user_class_set_conversion.py | 142 +++++++++++++++++- 5 files changed, 201 insertions(+), 43 deletions(-) diff --git a/.zed/rules b/.zed/rules index fd4447565..f8b5ffdf0 100644 --- a/.zed/rules +++ b/.zed/rules @@ -478,9 +478,9 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 - 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, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow - value converter (developer decision D47, ITL-922). Inspect the element through the - converter's registered types and factory selection without changing the annotation - or registering a type. Declarations and Arrow reads use their existing paths. + value converter (developer decision D47, ITL-922). Inspect the element storage + from the converter's normal type resolution, including deferred types. + 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 diff --git a/CLAUDE.md b/CLAUDE.md index a0b9f8f75..33a4df7b9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -489,9 +489,9 @@ A class a user defines is one of two kinds (developer, November 12, 2026, ITL-97 - 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, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow - value converter (developer decision D47, ITL-922). Inspect the element through the - converter's registered types and factory selection without changing the annotation - or registering a type. Declarations and Arrow reads use their existing paths. + value converter (developer decision D47, ITL-922). Inspect the element storage + from the converter's normal type resolution, including deferred types. + 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 diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index a8998616e..cb6166160 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -9,7 +9,7 @@ The stored order of a set of struct-stored user classes can follow the set's ite order, so equal sets can have different stored representations and row hashes. **Fix:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value -converter for the set. The check inspects the element type without changing its -annotation or registering a type. The converter caches the decision for subsequent rows. +converter for the set. The check uses the element storage resolved during the normal +converter build. The converter caches the decision for subsequent rows. The conversion error directs writers to `list[T]`. ITL-1691 tracks the canonical storage order. diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 61ca7d6c1..59525853a 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1899,8 +1899,23 @@ def _generate_unique_type_name(self, field_specs: Mapping[str, DataType]) -> str self._created_type_names.add(base_name) return base_name - def _is_set_of_struct_user_class(self, element: type) -> bool: - """Check how a set's element would be stored without registering any types.""" + def _is_set_of_struct_user_class( + self, element: type, set_type: pa.DataType | None + ) -> bool: + """Recognize a struct-stored user class from the resolved set storage.""" + from orcapod.logical_types.user_class_identity import class_kind + + if self._logical_type_registry is None or class_kind(element) is None: + return False + + if isinstance(set_type, pa.ExtensionType): + set_type = set_type.storage_type + if isinstance(set_type, (pa.ListType, pa.LargeListType)): + return pa.types.is_struct(cast(pa.DataType, set_type.value_type)) + + # An explicit Arrow schema can send a wrapped annotation here even when + # the converter cannot derive its Arrow type. Keep the existing refusal + # for those annotations without resolving a type just for the diagnostic. from orcapod.logical_types.dataclass_logical_type_factory import ( DataclassLogicalTypeFactory, ) @@ -1910,12 +1925,8 @@ def _is_set_of_struct_user_class(self, element: type) -> bool: from orcapod.logical_types.structural_logical_type_factory import ( StructuralLogicalTypeFactory, ) - from orcapod.logical_types.user_class_identity import class_kind registry = self._logical_type_registry - if registry is None or class_kind(element) is None: - return False - logical_type = registry._by_python_type.get(element) if logical_type is None and not any( qualified_name(base) in registry._deferred_by_python_name @@ -1934,14 +1945,31 @@ def _is_set_of_struct_user_class(self, element: type) -> bool: logical_type.get_arrow_extension_type().storage_type ) - def _check_set_write(self, python_type: DataType) -> None: - """Refuse a set whose elements are user classes stored as structs.""" + def _check_set_write( + self, python_type: DataType, logical_type: LogicalTypeProtocol | None + ) -> None: + """Resolve the set's existing storage path and check its element.""" + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + + set_type = None + resolution_error = None + if isinstance(logical_type, ListLogicalType): + set_type = logical_type.get_arrow_extension_type() + elif logical_type is None: + # This is the type resolution the fallback converter already performs. + try: + set_type = self.python_type_to_arrow_type(python_type) + except ValueError as exc: + resolution_error = exc + element = _unwrapped_set_element(python_type) - if element is not None and self._is_set_of_struct_user_class(element): + if element is not None and self._is_set_of_struct_user_class(element, set_type): raise UserClassSetNotStorableError( f"a set of {qualified_name(element)} values cannot be stored in this " f"version; use list[{element.__name__}]." ) + if resolution_error is not None: + raise resolution_error def _create_python_to_arrow_converter( self, python_type: DataType @@ -1949,31 +1977,33 @@ def _create_python_to_arrow_converter( """Create a cached conversion function for Python → Arrow values.""" origin = get_origin(python_type) - if origin is set: - self._check_set_write(python_type) - # Check LogicalTypeRegistry first — extension-type identity takes priority. # GenericAlias instances like list[UUID] or set[UUID] may be registered as # ListLogicalType entries, so we must not guard this check with isinstance(python_type, type). - if self._logical_type_registry is not None: - lt = self._logical_type_registry.get_by_python_type(python_type) - if lt is not None: - _lt = lt - _self = self + registry = self._logical_type_registry + lt = ( + registry.get_by_python_type(cast(type, python_type)) + if registry is not None + else None + ) + if origin is set: + self._check_set_write(python_type, lt) + if lt is not None: + _lt = lt + _self = self - def convert_logical(value: Any) -> Any: - # A None at a position whose type does not admit one never reaches - # the logical type's encoder, which would store a wrong value (a - # Path stored the string 'None', a list[UUID] an empty list). - if value is None: - raise _none_not_admitted(python_type) - return _lt.python_to_storage(value, _self) + def convert_logical(value: Any) -> Any: + # A None at a position whose type does not admit one never reaches + # the logical type's encoder, which would store a wrong value (a + # Path stored the string 'None', a list[UUID] an empty list). + if value is None: + raise _none_not_admitted(python_type) + return _lt.python_to_storage(value, _self) - return 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) + if origin is not set: + _ = self.python_type_to_arrow_type(python_type) # Create conversion function based on type diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 0c0910159..4395f0403 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -2,12 +2,14 @@ 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 @@ -19,7 +21,7 @@ import pytest from unittest.mock import patch -from typing_extensions import TypeAliasType +from typing_extensions import TypeAliasType, override import orcapod as op from orcapod.contexts import create_registry, get_default_context @@ -28,9 +30,13 @@ from orcapod.core.datagrams.datagram import Datagram from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import OutputTypeError, RowFailuresWarning +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.protocols import LogicalTypeProtocol, TypeConverterProtocol from orcapod.logical_types.registry import ( + LogicalTypeRegistry, make_arrow_extension_type, make_polars_extension_type, ) @@ -109,9 +115,13 @@ def guard_calls() -> Iterator[list[str]]: calls: list[str] = [] check = UniversalTypeConverter._check_set_write - def record(converter: UniversalTypeConverter, python_type: DataType) -> None: + def record( + converter: UniversalTypeConverter, + python_type: DataType, + logical_type: LogicalTypeProtocol | None, + ) -> None: calls.append(sys._getframe(1).f_code.co_name) - check(converter, python_type) + check(converter, python_type, logical_type) with patch.object(UniversalTypeConverter, "_check_set_write", record): yield calls @@ -175,11 +185,129 @@ def test_a_lazily_registered_scalar_dataclass_is_accepted() -> None: context = create_registry().get_context() converter = context.type_converter assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type_factory(WordFactory(), python_bases=[Word]) + 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")}})] - source = DictSource(rows, data_schema={"words": set[Word]}, data_context=context) - assert converter.arrow_table_to_python_dicts(source.as_table()) == rows + 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 == ["_create_python_to_arrow_converter"] + + +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): From 1fec597d6b29d354acb70b9b08b8cce99a4433fe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 02:13:45 -0800 Subject: [PATCH 13/20] fix(conversion): honor registered whole-set encoders --- .zed/rules | 7 +- CLAUDE.md | 7 +- changelog.d/ITL-922.md | 5 +- docs/concepts/function-pods.md | 5 +- docs/concepts/logical-type-identifiers.md | 9 ++- docs/concepts/your-own-data-types.md | 5 +- docs/dev/design_issues/ITL-922-SU1.md | 5 +- docs/reference/database-types.md | 4 +- docs/reference/hashing.md | 6 +- .../semantic_types/universal_converter.py | 11 ++- .../test_user_class_set_conversion.py | 73 +++++++++++++++++-- 11 files changed, 103 insertions(+), 34 deletions(-) diff --git a/.zed/rules b/.zed/rules index f8b5ffdf0..1b5a56c8b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -477,9 +477,10 @@ 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, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow - value converter (developer decision D47, ITL-922). Inspect the element storage - from the converter's normal type resolution, including deferred types. +- For 0.4.0, refuse `set[T]` of a struct-stored user class when building its native + Python-to-Arrow value converter (developer decision D47, ITL-922). Inspect the element + storage from the converter's normal type resolution, including deferred types. + A logical type selected for the whole set owns its storage. 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}` diff --git a/CLAUDE.md b/CLAUDE.md index 33a4df7b9..9e73b788c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -488,9 +488,10 @@ 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, refuse `set[T]` of a struct-stored user class when building its Python-to-Arrow - value converter (developer decision D47, ITL-922). Inspect the element storage - from the converter's normal type resolution, including deferred types. +- For 0.4.0, refuse `set[T]` of a struct-stored user class when building its native + Python-to-Arrow value converter (developer decision D47, ITL-922). Inspect the element + storage from the converter's normal type resolution, including deferred types. + A logical type selected for the whole set owns its storage. 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}` diff --git a/changelog.d/ITL-922.md b/changelog.d/ITL-922.md index 11b41fb11..ebf88f1fd 100644 --- a/changelog.d/ITL-922.md +++ b/changelog.d/ITL-922.md @@ -1,6 +1,7 @@ ### Breaking changes and migration -- Converting Python sets of struct-stored user classes to Arrow now raises an error, including - for nested sets. Use `list[T]` and supply the elements in the order you want stored. +- 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 0398818b5..4f9c32463 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -286,8 +286,9 @@ dataclass, an `orcapod.dataclass` or a pydantic model: hold such a value in a da 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 Arrow, Orcapod 0.4.0 reports an `OutputTypeError` for -that output. Use `list[T]` to return these values, including inside other types. +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. diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index 56b664a8f..22f5758ff 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -159,10 +159,11 @@ 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 to convert a Python `set[T]` when the registered logical type -or factory stores its user-class elements as an Arrow struct. Use `list[T]` for these -classes. Sets of primitives and scalar-stored logical types such as `Path` and `UUID` -are supported. Existing Arrow data and saved schemas can still be read. +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 6781304c1..1605ba630 100644 --- a/docs/concepts/your-own-data-types.md +++ b/docs/concepts/your-own-data-types.md @@ -46,11 +46,12 @@ 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 Arrow storage. +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 custom source's `from_config` follows the same rule when it +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. diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index cb6166160..c8d38e47f 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -9,7 +9,8 @@ The stored order of a set of struct-stored user classes can follow the set's ite order, so equal sets can have different stored representations and row hashes. **Fix:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value -converter for the set. The check uses the element storage resolved during the normal -converter build. The converter caches the decision for subsequent rows. +converter for a native set. The check uses the element storage resolved during the normal +converter build. A registered logical type for the whole set owns its storage. +The converter caches the decision for subsequent rows. The conversion error directs writers to `list[T]`. ITL-1691 tracks the canonical storage order. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 4d86a3c1f..9ba71342d 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -23,8 +23,8 @@ 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 Arrow. -Use `list[T]` for those classes. +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: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 36170079b..0045c28ae 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -1115,9 +1115,9 @@ 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 Arrow 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. +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 diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 59525853a..a3911dfd7 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1948,19 +1948,22 @@ def _is_set_of_struct_user_class( def _check_set_write( self, python_type: DataType, logical_type: LogicalTypeProtocol | None ) -> None: - """Resolve the set's existing storage path and check its element.""" + """Check the element storage when the converter uses a native set.""" from orcapod.logical_types.list_logical_type_factory import ListLogicalType set_type = None resolution_error = None - if isinstance(logical_type, ListLogicalType): - set_type = logical_type.get_arrow_extension_type() - elif logical_type is None: + if logical_type is None: # This is the type resolution the fallback converter already performs. try: set_type = self.python_type_to_arrow_type(python_type) except ValueError as exc: resolution_error = exc + elif type(logical_type) is ListLogicalType: + set_type = logical_type.get_arrow_extension_type() + else: + # A logical type selected for the whole set owns its storage. + return element = _unwrapped_set_element(python_type) if element is not None and self._is_set_of_struct_user_class(element, set_type): diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 4395f0403..67c23a8b4 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -78,6 +78,59 @@ 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.""" @@ -336,6 +389,7 @@ def test_dict_source_refuses_each_struct_stored_class_kind(value: Any) -> None: @pytest.mark.parametrize( ("element", "values"), [ + (Point, {Point(1)}), (Point | None, {Point(1), None}), (Optional[Point], {Point(1)}), (NamedPoint, {Point(1)}), @@ -346,22 +400,27 @@ def test_dict_source_refuses_each_struct_stored_class_kind(value: Any) -> None: (Annotated[NamedPointAlias | None, _METADATA], {Point(1)}), ], ) -@pytest.mark.parametrize("nested", [False, True]) +@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 + element: Any, values: Any, nested: bool, warm: bool ) -> None: annotation = list[set[element]] if nested else set[element] value = [values] if nested else values - converter = create_registry().get_context().type_converter - assert isinstance(converter, UniversalTypeConverter) # 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}) - converter.ensure_types_registered_for_schemas(declared) - arrow_schema = converter.python_schema_to_arrow_schema(declared) + 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 typing.get_origin(element) not in (typing.Union, UnionType): + 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"): From 97ba08c7f0a4746d29bbac54f9ab8e91052e80cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 02:37:47 -0800 Subject: [PATCH 14/20] docs(database): sync native set wording with matrix generator --- tests/test_databases/type_matrix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index a9948de4a..93ed6ae66 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1070,8 +1070,8 @@ 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 Arrow. -Use `list[T]` for those classes. +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: From d0ebcdd486c245827db008146427c8ba354b3e29 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 05:43:02 -0800 Subject: [PATCH 15/20] fix(conversion): preserve precomputed write schema and refusal context --- .../semantic_types/precomputed_converters.py | 16 +++++++++---- .../test_user_class_set_conversion.py | 23 +++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index bf3b14e16..d4ac77a13 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -14,6 +14,7 @@ import pyarrow as pa +from orcapod.semantic_types.nested_storage import UserClassSetNotStorableError from orcapod.semantic_types.universal_converter import UniversalTypeConverter @@ -44,6 +45,8 @@ def __init__( "Either python_schema or arrow_schema must be provided to initialize SemanticSchemaConverter." ) + # Keep the deferred write plan aligned with the schema resolved above. + self._python_schema_items = tuple(self.python_schema.items()) self._arrow_to_python_converters: dict[str, Callable[[Any], Any]] = {} for field in self.arrow_schema: @@ -54,10 +57,15 @@ def __init__( @cached_property def _python_to_arrow_converters(self) -> dict[str, Callable[[Any], Any]]: """Build write converters only when converting Python rows.""" - return { - name: self.universal_converter.get_python_to_arrow_converter(python_type) - for name, python_type in self.python_schema.items() - } + converters = {} + for name, python_type in self._python_schema_items: + try: + converters[name] = ( + self.universal_converter.get_python_to_arrow_converter(python_type) + ) + except UserClassSetNotStorableError as exc: + raise UserClassSetNotStorableError(f"Column {name!r}: {exc}") from exc + return converters def python_dict_to_struct_dict(self, record: dict[str, Any]) -> dict[str, Any]: """ diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 67c23a8b4..66b45640d 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -589,6 +589,29 @@ def from_config( ) +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}] + + +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) From 658c63515f0d304b0969790a5b3aa13de016e75e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 06:23:22 -0800 Subject: [PATCH 16/20] fix(conversion): preserve eager converter selection for native sets --- .zed/rules | 10 +- CLAUDE.md | 10 +- docs/dev/design_issues/ITL-922-SU1.md | 3 +- .../semantic_types/precomputed_converters.py | 34 ++-- .../semantic_types/universal_converter.py | 181 ++++++++++-------- .../test_user_class_set_conversion.py | 96 ++++++++-- 6 files changed, 206 insertions(+), 128 deletions(-) diff --git a/.zed/rules b/.zed/rules index f8eb9597d..d846c6cc7 100644 --- a/.zed/rules +++ b/.zed/rules @@ -477,12 +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, refuse `set[T]` of a struct-stored user class when building its native - Python-to-Arrow value converter (developer decision D47, ITL-922). Inspect the element - storage from the converter's normal type resolution, including deferred types. +- 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. - Declarations and Arrow reads use their existing paths. - Direct writers to `list[T]`. ITL-1691 tracks canonical ordering. + 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 d8a761a3e..373e74863 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -488,12 +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, refuse `set[T]` of a struct-stored user class when building its native - Python-to-Arrow value converter (developer decision D47, ITL-922). Inspect the element - storage from the converter's normal type resolution, including deferred types. +- 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. - Declarations and Arrow reads use their existing paths. - Direct writers to `list[T]`. ITL-1691 tracks canonical ordering. + 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/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index c8d38e47f..8e5e74271 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -11,6 +11,7 @@ order, so equal sets can have different stored representations and row hashes. **Fix:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value converter for a native set. The check uses the element storage resolved during the normal converter build. A registered logical type for the whole set owns its storage. -The converter caches the decision for subsequent rows. +The existing converter cache retains the decision. The refusal surfaces when a Python +value is written, so Arrow reads and empty declarations keep their existing validation. The conversion error directs writers to `list[T]`. ITL-1691 tracks the canonical storage order. diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index d4ac77a13..701c36cff 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -10,7 +10,6 @@ from typing import Any from collections.abc import Callable -from functools import cached_property import pyarrow as pa @@ -45,28 +44,21 @@ def __init__( "Either python_schema or arrow_schema must be provided to initialize SemanticSchemaConverter." ) - # Keep the deferred write plan aligned with the schema resolved above. - self._python_schema_items = tuple(self.python_schema.items()) + # Pre-compute converters for each field + self._python_to_arrow_converters: dict[str, Callable[[Any], Any]] = {} self._arrow_to_python_converters: dict[str, Callable[[Any], Any]] = {} + # 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) + ) + for field in self.arrow_schema: self._arrow_to_python_converters[field.name] = ( self.universal_converter.get_arrow_to_python_converter(field.type) ) - @cached_property - def _python_to_arrow_converters(self) -> dict[str, Callable[[Any], Any]]: - """Build write converters only when converting Python rows.""" - converters = {} - for name, python_type in self._python_schema_items: - try: - converters[name] = ( - self.universal_converter.get_python_to_arrow_converter(python_type) - ) - except UserClassSetNotStorableError as exc: - raise UserClassSetNotStorableError(f"Column {name!r}: {exc}") from exc - return converters - 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. @@ -85,18 +77,22 @@ def python_dicts_to_struct_dicts( if not data: raise ValueError("Cannot convert empty data list") - converters = self._python_to_arrow_converters converted_data = [] for record in data: converted_record = {} - for field_name, converter in converters.items(): + for field_name, converter in self._python_to_arrow_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 diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 2ef0c88bb..c14c23a9a 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -18,6 +18,7 @@ import typing from collections.abc import Callable, Iterable, Mapping from datetime import date, datetime, timezone +from functools import cache # Handle generic types from typing import TYPE_CHECKING, Any, TypedDict, cast, get_args, get_origin @@ -311,8 +312,8 @@ def __init__( self._typeddict_to_struct_signature: dict[DataType, pa.StructType] = {} self._created_type_names: set[str] = set() - # A string records the message of a refused write converter. - self._python_to_arrow_converters: dict[DataType, Callable | str] = {} + # Cache for conversion functions + self._python_to_arrow_converters: dict[DataType, Callable] = {} self._arrow_to_python_converters: dict[pa.DataType, Callable] = {} # Cache for type mappings @@ -1329,14 +1330,10 @@ 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 = {} - for field_name, python_type in python_schema.items(): - try: - converters[field_name] = self.get_python_to_arrow_converter(python_type) - except UserClassSetNotStorableError as exc: - raise UserClassSetNotStorableError( - f"Column {field_name!r}: {exc}" - ) from exc + converters = { + field_name: self.get_python_to_arrow_converter(python_type) + for field_name, python_type in python_schema.items() + } converted_data = [] for record in python_dicts: @@ -1450,10 +1447,6 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) - if not python_dicts: - # A declared schema with no rows needs no value converters. - return pa.Table.from_pylist([], schema=arrow_schema) - struct_dicts = self.python_dicts_to_struct_dicts( python_dicts, python_schema=python_schema ) @@ -1502,17 +1495,13 @@ def get_python_to_arrow_converter( This creates and caches conversion functions for optimal performance during data conversion operations. """ - converter = self._python_to_arrow_converters.get(python_type) - if converter is None: - try: - converter = self._create_python_to_arrow_converter(python_type) - except UserClassSetNotStorableError as exc: - self._python_to_arrow_converters[python_type] = str(exc) - raise - self._python_to_arrow_converters[python_type] = converter - if isinstance(converter, str): - # Raise a fresh exception to keep each row's traceback independent. - raise UserClassSetNotStorableError(converter) + if python_type in self._python_to_arrow_converters: + return self._python_to_arrow_converters[python_type] + + # Create conversion function + converter = self._create_python_to_arrow_converter(python_type) + self._python_to_arrow_converters[python_type] = converter + return converter def get_arrow_to_python_converter( @@ -1922,10 +1911,11 @@ def _is_set_of_struct_user_class( set_type = set_type.storage_type if isinstance(set_type, (pa.ListType, pa.LargeListType)): return pa.types.is_struct(cast(pa.DataType, set_type.value_type)) + if set_type is not None: + return False - # An explicit Arrow schema can send a wrapped annotation here even when - # the converter cannot derive its Arrow type. Keep the existing refusal - # for those annotations without resolving a type just for the diagnostic. + # With an explicit Arrow schema, a wrapped annotation can reach the + # builder even if the normal Arrow type lookup cannot resolve it. from orcapod.logical_types.dataclass_logical_type_factory import ( DataclassLogicalTypeFactory, ) @@ -1935,72 +1925,110 @@ def _is_set_of_struct_user_class( from orcapod.logical_types.structural_logical_type_factory import ( StructuralLogicalTypeFactory, ) + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType registry = self._logical_type_registry - logical_type = registry._by_python_type.get(element) - if logical_type is None and not any( - qualified_name(base) in registry._deferred_by_python_name - for base in element.__mro__ - ): - logical_type = registry._find_by_python_type(element) - if logical_type is None: - # For a wrapper the schema cannot derive, the standard factories - # always produce structs. Leave arbitrary factories to registration. - return type(self._find_factory_for_class(element)) in ( - DataclassLogicalTypeFactory, - PydanticLogicalTypeFactory, - StructuralLogicalTypeFactory, - ) - return logical_type is not None and pa.types.is_struct( - logical_type.get_arrow_extension_type().storage_type - ) + cached = self._python_to_arrow_types.get(element) + if isinstance(cached, pa.ExtensionType): + return pa.types.is_struct(cached.storage_type) + + for base in element.__mro__: + registered = registry._by_python_type.get(base) + if registered is not None and ( + base is element + or not getattr(registered, "exact_python_type_only", False) + ): + return isinstance(registered, UserClassLogicalType) + if qualified_name(base) in registry._deferred_by_python_name: + # Only the normal resolution path may load a deferred encoder. + return False - def _check_set_write( - self, python_type: DataType, logical_type: LogicalTypeProtocol | None - ) -> None: - """Check the element storage when the converter uses a native set.""" + class_factories = ( + DataclassLogicalTypeFactory, + PydanticLogicalTypeFactory, + StructuralLogicalTypeFactory, + ) + for base in element.__mro__: + factory = registry._python_class_factories.get(base) + if factory is not None: + if type(factory) not in class_factories: + # Do not invoke an arbitrary factory to classify a refusal. + return False + if factory.supports_class(element): + return True + return False + + def _struct_set_element( + self, + python_type: DataType, + logical_type: LogicalTypeProtocol | None, + arrow_type: pa.DataType | None, + ) -> type | None: + """Identify the prohibited element using the native set's resolved storage.""" from orcapod.logical_types.list_logical_type_factory import ListLogicalType - set_type = None - resolution_error = None - if logical_type is None: - # This is the type resolution the fallback converter already performs. - try: - set_type = self.python_type_to_arrow_type(python_type) - except ValueError as exc: - resolution_error = exc - elif type(logical_type) is ListLogicalType: - set_type = logical_type.get_arrow_extension_type() - else: - # A logical type selected for the whole set owns its storage. - return - + if logical_type is not None: + if type(logical_type) is not ListLogicalType: + # A whole-set encoder owns its storage. + return None + arrow_type = logical_type._storage_type element = _unwrapped_set_element(python_type) - if element is not None and self._is_set_of_struct_user_class(element, set_type): - raise UserClassSetNotStorableError( - f"a set of {qualified_name(element)} values cannot be stored in this " - f"version; use list[{element.__name__}]." - ) - if resolution_error is not None: - raise resolution_error + if element is not None and self._is_set_of_struct_user_class( + element, arrow_type + ): + return element + return None + + @staticmethod + def _check_set_write(element: type) -> str: + """Describe the refusal for a set whose resolved element is a user struct.""" + return ( + f"a set of {qualified_name(element)} values cannot be stored in this " + f"version; use list[{element.__name__}]." + ) def _create_python_to_arrow_converter( self, python_type: DataType ) -> Callable[[Any], Any]: """Create a cached conversion function for Python → Arrow values.""" - origin = get_origin(python_type) # Check LogicalTypeRegistry first — extension-type identity takes priority. # GenericAlias instances like list[UUID] or set[UUID] may be registered as # ListLogicalType entries, so we must not guard this check with isinstance(python_type, type). - registry = self._logical_type_registry lt = ( - registry.get_by_python_type(cast(type, python_type)) - if registry is not None + self._logical_type_registry.get_by_python_type(cast(type, python_type)) + if self._logical_type_registry is not None else None ) + origin = get_origin(python_type) + arrow_type = None + resolution_error = None + if lt is None: + # Get the Arrow type for this Python type + # TODO: check if this step is necessary + try: + arrow_type = self.python_type_to_arrow_type(python_type) + except ValueError as exc: + if origin is not set: + raise + resolution_error = exc + if origin is set: - self._check_set_write(python_type, lt) + element = self._struct_set_element(python_type, lt, arrow_type) + if element is not None: + # This is a write converter even when a reader or empty table + # eagerly builds it. Report the refusal only on a value write. + @cache + def refusal_message() -> str: + return self._check_set_write(element) + + def refuse_set(value: Any) -> Any: + raise UserClassSetNotStorableError(refusal_message()) + + return refuse_set + if resolution_error is not None: + raise resolution_error + if lt is not None: _lt = lt _self = self @@ -2015,9 +2043,6 @@ def convert_logical(value: Any) -> Any: return convert_logical - if origin is not set: - _ = self.python_type_to_arrow_type(python_type) - # Create conversion function based on type # Without this guard, datetime would reach the `origin is None` catch-all diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 66b45640d..809527ec1 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -34,7 +34,7 @@ DataclassLogicalTypeFactory, ) from orcapod.logical_types.identifier import version_metadata -from orcapod.logical_types.protocols import LogicalTypeProtocol, TypeConverterProtocol +from orcapod.logical_types.protocols import TypeConverterProtocol from orcapod.logical_types.registry import ( LogicalTypeRegistry, make_arrow_extension_type, @@ -49,7 +49,7 @@ 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 DataType, DataValue, Schema +from orcapod.types import DataValue, Schema from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data _METADATA = "private-annotation-sentinel-itl922" @@ -163,20 +163,16 @@ async def close(self) -> None: @contextmanager -def guard_calls() -> Iterator[list[str]]: - """Record the immediate caller of every invocation of the write check.""" - calls: list[str] = [] +def guard_calls() -> Iterator[list[type]]: + """Record when a refusing set converter is first used for a write.""" + calls: list[type] = [] check = UniversalTypeConverter._check_set_write - def record( - converter: UniversalTypeConverter, - python_type: DataType, - logical_type: LogicalTypeProtocol | None, - ) -> None: - calls.append(sys._getframe(1).f_code.co_name) - check(converter, python_type, logical_type) + def record(element: type) -> str: + calls.append(element) + return check(element) - with patch.object(UniversalTypeConverter, "_check_set_write", record): + with patch.object(UniversalTypeConverter, "_check_set_write", staticmethod(record)): yield calls @@ -341,7 +337,7 @@ def test_struct_set_write_uses_resolved_deferred_type( [{"points": {PlainPoint(0)}}], schema, arrow_schema ) load.assert_called_once() - assert calls == ["_create_python_to_arrow_converter"] + assert calls == [PlainPoint] def test_a_cold_struct_factory_registered_by_python_base_is_refused() -> None: @@ -442,7 +438,7 @@ def test_converter_refuses_wrapped_user_class_set_elements( "version; use list[Point]." ) assert _METADATA not in str(error.value) - assert calls == ["_create_python_to_arrow_converter"] + assert calls == [Point] @pytest.mark.parametrize("element", [Point, int, Word]) @@ -516,7 +512,7 @@ def test_nested_sets_refused_at_the_same_conversion_boundary( 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 calls == ["_create_python_to_arrow_converter"] + assert calls == [Point] def test_dict_values_follow_the_existing_nested_storage_rule() -> None: @@ -550,7 +546,7 @@ def test_a_failed_job_checks_the_set_once_and_writes_no_tables() -> None: 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 == ["_create_python_to_arrow_converter"] + assert calls == [Point] assert list(database.list_table_paths(())) == [] @@ -599,6 +595,66 @@ def test_precomputed_write_retains_schema_after_caller_mutation() -> None: 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) + + def test_precomputed_set_write_refusal_names_the_column() -> None: converter = create_registry().get_context().type_converter assert isinstance(converter, UniversalTypeConverter) @@ -719,14 +775,14 @@ def test_source_construction_config_and_saved_job_skip_the_check( assert calls == [] -def test_a_set_converter_is_checked_once_for_many_rows_and_reuses_its_cache() -> None: +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 == ["_create_python_to_arrow_converter"] + assert calls == [] assert first.equals(second) @@ -747,7 +803,7 @@ def test_custom_restore_that_builds_python_rows_is_a_write( NestedTypeNotStorableError, match=r"Column 'points'.*use list\[Point\]" ): resolve_source_from_config(source.to_config()) - assert calls == ["_create_python_to_arrow_converter"] + assert calls == [Point] job = op.PipelineJob(name="legacy", database=InMemoryArrowDatabase()) with job: From ecb550d4bdb50e67cd3a2ceb2eed88e118d78c24 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 07:25:42 -0800 Subject: [PATCH 17/20] fix(conversion): preserve native set validation before writes --- docs/dev/design_issues/ITL-922-SU1.md | 14 +- .../semantic_types/universal_converter.py | 245 ++++++++---------- .../test_user_class_set_conversion.py | 90 ++++++- 3 files changed, 197 insertions(+), 152 deletions(-) diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index 8e5e74271..87173272f 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -8,10 +8,10 @@ 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:** D47 places the temporary refusal where Orcapod builds the Python-to-Arrow value -converter for a native set. The check uses the element storage resolved during the normal -converter build. A registered logical type for the whole set owns its storage. -The existing converter cache retains the decision. The refusal surfaces when a Python -value is written, so Arrow reads and empty declarations keep their existing validation. -The conversion error directs writers to `list[T]`. ITL-1691 tracks the canonical -storage order. +**Fix:** The first Python set write through a native set converter checks the resolved +Arrow element storage. The existing converter cache retains that decision. A registered +whole-set encoder owns its storage. Empty declarations and Arrow reads keep the eager +validation and required nulls keep the original null error. An explicit Arrow schema +can identify native user-class set storage when a wrapped or cold Python annotation +cannot be resolved on an actual set write. The refusal directs writers to `list[T]`. +ITL-1691 tracks the canonical storage order. diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index c14c23a9a..aa9227800 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -1320,6 +1320,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. @@ -1330,10 +1332,38 @@ 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: + converters[field_name] = 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 isinstance( + arrow_type := _explicit_arrow_schema.field(field_name).type, + pa.ExtensionType, + ): + raise + for record in python_dicts: + value = record.get(field_name) + if isinstance(value, set): + 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 converted_data = [] for record in python_dicts: @@ -1348,9 +1378,7 @@ def python_dicts_to_struct_dicts( f"Column {field_name!r}: {exc}" ) from exc except UserClassSetNotStorableError as exc: - raise UserClassSetNotStorableError( - f"Column {field_name!r}: {exc}" - ) from 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( @@ -1422,7 +1450,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." ) @@ -1448,7 +1478,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 @@ -1898,95 +1930,54 @@ def _generate_unique_type_name(self, field_specs: Mapping[str, DataType]) -> str self._created_type_names.add(base_name) return base_name - def _is_set_of_struct_user_class( - self, element: type, set_type: pa.DataType | None - ) -> bool: - """Recognize a struct-stored user class from the resolved set storage.""" - from orcapod.logical_types.user_class_identity import class_kind - - if self._logical_type_registry is None or class_kind(element) is None: - return False - - if isinstance(set_type, pa.ExtensionType): - set_type = set_type.storage_type - if isinstance(set_type, (pa.ListType, pa.LargeListType)): - return pa.types.is_struct(cast(pa.DataType, set_type.value_type)) - if set_type is not None: - return False - - # With an explicit Arrow schema, a wrapped annotation can reach the - # builder even if the normal Arrow type lookup cannot resolve it. - from orcapod.logical_types.dataclass_logical_type_factory import ( - DataclassLogicalTypeFactory, - ) - from orcapod.logical_types.pydantic_logical_type_factory import ( - PydanticLogicalTypeFactory, - ) - from orcapod.logical_types.structural_logical_type_factory import ( - StructuralLogicalTypeFactory, - ) - from orcapod.logical_types.user_class_logical_type import UserClassLogicalType - - registry = self._logical_type_registry - cached = self._python_to_arrow_types.get(element) - if isinstance(cached, pa.ExtensionType): - return pa.types.is_struct(cached.storage_type) - - for base in element.__mro__: - registered = registry._by_python_type.get(base) - if registered is not None and ( - base is element - or not getattr(registered, "exact_python_type_only", False) - ): - return isinstance(registered, UserClassLogicalType) - if qualified_name(base) in registry._deferred_by_python_name: - # Only the normal resolution path may load a deferred encoder. - return False - - class_factories = ( - DataclassLogicalTypeFactory, - PydanticLogicalTypeFactory, - StructuralLogicalTypeFactory, - ) - for base in element.__mro__: - factory = registry._python_class_factories.get(base) - if factory is not None: - if type(factory) not in class_factories: - # Do not invoke an arbitrary factory to classify a refusal. - return False - if factory.supports_class(element): - return True - return False - - def _struct_set_element( - self, - python_type: DataType, - logical_type: LogicalTypeProtocol | None, - arrow_type: pa.DataType | None, - ) -> type | None: - """Identify the prohibited element using the native set's resolved storage.""" - from orcapod.logical_types.list_logical_type_factory import ListLogicalType + @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 - if logical_type is not None: - if type(logical_type) is not ListLogicalType: - # A whole-set encoder owns its storage. - return None - arrow_type = logical_type._storage_type element = _unwrapped_set_element(python_type) - if element is not None and self._is_set_of_struct_user_class( - element, arrow_type - ): - return element - return None + if element is None or class_kind(element) is None: + return None - @staticmethod - def _check_set_write(element: type) -> str: - """Describe the refusal for a set whose resolved element is a user struct.""" + 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 eager validation and classify the storage only on a set value write.""" + + @cache + def refusal() -> str | None: + storage = ( + arrow_type.storage_type + if isinstance(arrow_type, pa.ExtensionType) + else arrow_type + ) + if isinstance( + storage, (pa.ListType, pa.LargeListType) + ) and pa.types.is_struct(cast(pa.DataType, storage.value_type)): + return self._check_set_write(python_type, arrow_type) + return None + + def write(value: Any) -> Any: + if isinstance(value, set) and (message := refusal()) is not None: + raise UserClassSetNotStorableError(message) from None + return encode(value) + + return write + def _create_python_to_arrow_converter( self, python_type: DataType ) -> Callable[[Any], Any]: @@ -1995,53 +1986,35 @@ def _create_python_to_arrow_converter( # Check LogicalTypeRegistry first — extension-type identity takes priority. # GenericAlias instances like list[UUID] or set[UUID] may be registered as # ListLogicalType entries, so we must not guard this check with isinstance(python_type, type). - lt = ( - self._logical_type_registry.get_by_python_type(cast(type, python_type)) - if self._logical_type_registry is not None - else None - ) - origin = get_origin(python_type) - arrow_type = None - resolution_error = None - if lt is None: - # Get the Arrow type for this Python type - # TODO: check if this step is necessary - try: - arrow_type = self.python_type_to_arrow_type(python_type) - except ValueError as exc: - if origin is not set: - raise - resolution_error = exc - - if origin is set: - element = self._struct_set_element(python_type, lt, arrow_type) - if element is not None: - # This is a write converter even when a reader or empty table - # eagerly builds it. Report the refusal only on a value write. - @cache - def refusal_message() -> str: - return self._check_set_write(element) - - def refuse_set(value: Any) -> Any: - raise UserClassSetNotStorableError(refusal_message()) + if self._logical_type_registry is not None: + lt = self._logical_type_registry.get_by_python_type(python_type) + if lt is not None: + _lt = lt + _self = self - return refuse_set - if resolution_error is not None: - raise resolution_error + def convert_logical(value: Any) -> Any: + # A None at a position whose type does not admit one never reaches + # the logical type's encoder, which would store a wrong value (a + # Path stored the string 'None', a list[UUID] an empty list). + if value is None: + 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 lt is not None: - _lt = lt - _self = self + if type(lt) is ListLogicalType: + return self._native_set_writer( + python_type, lt._storage_type, convert_logical + ) - def convert_logical(value: Any) -> Any: - # A None at a position whose type does not admit one never reaches - # the logical type's encoder, which would store a wrong value (a - # Path stored the string 'None', a list[UUID] an empty list). - if value is None: - raise _none_not_admitted(python_type) - return _lt.python_to_storage(value, _self) + return convert_logical - return convert_logical + # Get the Arrow type for this Python type + # TODO: check if this step is necessary + arrow_type = self.python_type_to_arrow_type(python_type) # Create conversion function based on type @@ -2060,6 +2033,7 @@ def _convert_datetime(dt: datetime) -> datetime: return _convert_datetime + origin = get_origin(python_type) args = get_args(python_type) if python_type is int: @@ -2115,7 +2089,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: diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index 809527ec1..f9b693d20 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -14,6 +14,7 @@ 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 @@ -29,7 +30,7 @@ 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 +from orcapod.errors import OutputTypeError, RowFailuresWarning, UnsupportedValueError from orcapod.logical_types.dataclass_logical_type_factory import ( DataclassLogicalTypeFactory, ) @@ -163,14 +164,14 @@ async def close(self) -> None: @contextmanager -def guard_calls() -> Iterator[list[type]]: - """Record when a refusing set converter is first used for a write.""" - calls: list[type] = [] +def guard_calls() -> Iterator[list[Any]]: + """Record the actual refusal predicate, including unsuccessful checks.""" + calls: list[Any] = [] check = UniversalTypeConverter._check_set_write - def record(element: type) -> str: - calls.append(element) - return check(element) + 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 @@ -337,7 +338,7 @@ def test_struct_set_write_uses_resolved_deferred_type( [{"points": {PlainPoint(0)}}], schema, arrow_schema ) load.assert_called_once() - assert calls == [PlainPoint] + assert calls == [set[PlainPoint]] def test_a_cold_struct_factory_registered_by_python_base_is_refused() -> None: @@ -438,7 +439,9 @@ def test_converter_refuses_wrapped_user_class_set_elements( "version; use list[Point]." ) assert _METADATA not in str(error.value) - assert calls == [Point] + # 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]) @@ -512,7 +515,7 @@ def test_nested_sets_refused_at_the_same_conversion_boundary( 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 calls == [Point] + assert len(calls) == 1 def test_dict_values_follow_the_existing_nested_storage_rule() -> None: @@ -546,7 +549,7 @@ def test_a_failed_job_checks_the_set_once_and_writes_no_tables() -> None: 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 == [Point] + assert calls == [set[Point]] assert list(database.list_table_paths(())) == [] @@ -655,6 +658,69 @@ def test_zero_width_lists_keep_the_original_converter_validation() -> None: converter.python_dicts_to_arrow_table([], arrow_schema=table.schema) +@pytest.mark.parametrize( + ("element", "message"), + [ + (PlainPoint, f"Unsupported Python type: {PlainPoint}."), + ( + Annotated[PlainPoint, _METADATA], + "Unsupported generic type: ", + ), + (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 + ) + + +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." + ) + + +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) @@ -803,7 +869,7 @@ def test_custom_restore_that_builds_python_rows_is_a_write( NestedTypeNotStorableError, match=r"Column 'points'.*use list\[Point\]" ): resolve_source_from_config(source.to_config()) - assert calls == [Point] + assert calls == [set[Point]] job = op.PipelineJob(name="legacy", database=InMemoryArrowDatabase()) with job: From 00a75c4b1a3af129c81997d19541e62d206c6411 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 07:44:57 -0800 Subject: [PATCH 18/20] test(conversion): match native annotation wording on Python 3.13 --- tests/test_logical_types/test_user_class_set_conversion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index f9b693d20..a967eae5f 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -664,7 +664,7 @@ def test_zero_width_lists_keep_the_original_converter_validation() -> None: (PlainPoint, f"Unsupported Python type: {PlainPoint}."), ( Annotated[PlainPoint, _METADATA], - "Unsupported generic type: ", + f"Unsupported generic type: {Annotated}", ), (PlainPoint | None, f"Unsupported Python type: {PlainPoint}."), ], From 5c5f889b384c25d667174a1eb0dd8d5a3d92cf5c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 09:02:35 -0800 Subject: [PATCH 19/20] fix(conversion): validate before refusing native class set writes --- docs/dev/design_issues/ITL-922-SU1.md | 12 +- .../semantic_types/precomputed_converters.py | 25 ++- .../semantic_types/universal_converter.py | 108 ++++++++--- .../test_user_class_set_conversion.py | 169 ++++++++++++++++++ 4 files changed, 278 insertions(+), 36 deletions(-) diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index 87173272f..951696c8d 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -8,10 +8,10 @@ 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 first Python set write through a native set converter checks the resolved -Arrow element storage. The existing converter cache retains that decision. A registered -whole-set encoder owns its storage. Empty declarations and Arrow reads keep the eager -validation and required nulls keep the original null error. An explicit Arrow schema -can identify native user-class set storage when a wrapped or cold Python annotation -cannot be resolved on an actual set write. The refusal directs writers to `list[T]`. +**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, +Arrow reads and null diagnostics 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. diff --git a/src/orcapod/semantic_types/precomputed_converters.py b/src/orcapod/semantic_types/precomputed_converters.py index 701c36cff..0260b8031 100644 --- a/src/orcapod/semantic_types/precomputed_converters.py +++ b/src/orcapod/semantic_types/precomputed_converters.py @@ -14,7 +14,10 @@ from orcapod.semantic_types.nested_storage import UserClassSetNotStorableError -from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.semantic_types.universal_converter import ( + UniversalTypeConverter, + _converter_for_arrow_field, +) class SemanticSchemaConverter: @@ -74,13 +77,18 @@ 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: @@ -147,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 aa9227800..42c2fe969 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -17,6 +17,7 @@ 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 @@ -213,6 +214,56 @@ def _unwrapped_set_element(annotation: DataType) -> type | 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). @@ -1335,7 +1386,7 @@ def python_dicts_to_struct_dicts( converters = {} for field_name, python_type in python_schema.items(): try: - converters[field_name] = self.get_python_to_arrow_converter(python_type) + 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. @@ -1347,14 +1398,21 @@ def python_dicts_to_struct_dicts( raise if _explicit_arrow_schema.get_field_index( field_name - ) < 0 or not isinstance( - arrow_type := _explicit_arrow_schema.field(field_name).type, - pa.ExtensionType, + ) < 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): + 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 ) @@ -1364,6 +1422,11 @@ def python_dicts_to_struct_dicts( 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: @@ -1956,27 +2019,15 @@ def _native_set_writer( arrow_type: pa.DataType, encode: Callable[[Any], Any], ) -> Callable[[Any], Any]: - """Keep eager validation and classify the storage only on a set value write.""" + """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: - storage = ( - arrow_type.storage_type - if isinstance(arrow_type, pa.ExtensionType) - else arrow_type - ) - if isinstance( - storage, (pa.ListType, pa.LargeListType) - ) and pa.types.is_struct(cast(pa.DataType, storage.value_type)): - return self._check_set_write(python_type, arrow_type) - return None - - def write(value: Any) -> Any: - if isinstance(value, set) and (message := refusal()) is not None: - raise UserClassSetNotStorableError(message) from None - return encode(value) + return self._check_set_write(python_type, arrow_type) - return write + return _NativeSetWriter(encode, refusal) def _create_python_to_arrow_converter( self, python_type: DataType @@ -2114,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_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index a967eae5f..af9d111c0 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -43,6 +43,7 @@ ) 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, @@ -684,6 +685,148 @@ def test_empty_table_with_both_schemas_retains_eager_validation( ) +_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: @@ -698,6 +841,32 @@ def test_required_set_null_keeps_the_existing_error() -> None: ) +@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 From 90556047d22aa604a7a92ac89213cee4e2f0a885 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 13:16:19 -0800 Subject: [PATCH 20/20] test(semantic-types): isolate the cold IPC set fixture --- docs/dev/design_issues/ITL-922-SU1.md | 15 ++++++++++----- .../test_user_class_set_conversion.py | 6 +++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/dev/design_issues/ITL-922-SU1.md b/docs/dev/design_issues/ITL-922-SU1.md index 951696c8d..f31c51066 100644 --- a/docs/dev/design_issues/ITL-922-SU1.md +++ b/docs/dev/design_issues/ITL-922-SU1.md @@ -10,8 +10,13 @@ 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, -Arrow reads and null diagnostics 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. +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/tests/test_logical_types/test_user_class_set_conversion.py b/tests/test_logical_types/test_user_class_set_conversion.py index af9d111c0..64fbc8abc 100644 --- a/tests/test_logical_types/test_user_class_set_conversion.py +++ b/tests/test_logical_types/test_user_class_set_conversion.py @@ -932,9 +932,9 @@ def test_a_cold_ipc_read_can_import_a_module_defining_a_set_output( tmp_path: Path, ) -> None: converter = get_default_context().type_converter - schema = converter.python_schema_to_arrow_schema( - Schema({"points": set[PlainPoint]}) - ) + 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: