From f55be45766a572a1c65e21710a66ff7d8230e354 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:38:27 -0800 Subject: [PATCH 01/32] fix(semantic_types)!: refuse float32 and float16 dict keys and set elements where a type is declared (ITL-1591) A float stored under float32 or float16 is narrowed, and two distinct floats can narrow to one stored value, so a dict or a set lost an entry silently. A declared type whose dict key or set element is float32 or float16 is now refused (NarrowFloatKeyError) where it is declared, in a Python schema or annotation and in an Arrow schema or table, at any depth, by a type check. Co-Authored-By: Claude Fable 5.2 --- .zed/rules | 14 + CLAUDE.md | 14 + changelog.d/ITL-1591.md | 24 + docs/concepts/function-pods.md | 7 + docs/concepts/logical-type-identifiers.md | 5 + docs/dev/design_issues/ITL-1591-NFK1.md | 31 + src/orcapod/core/datagrams/datagram.py | 34 + src/orcapod/core/sources/stream_builder.py | 6 + .../core/streams/arrow_table_stream.py | 8 + .../logical_types/user_class_logical_type.py | 7 +- .../semantic_types/narrow_float_keys.py | 217 ++++++ src/orcapod/semantic_types/nested_storage.py | 38 +- .../semantic_types/universal_converter.py | 82 ++- .../test_narrow_float_keys_refused.py | 620 ++++++++++++++++++ 14 files changed, 1069 insertions(+), 38 deletions(-) create mode 100644 changelog.d/ITL-1591.md create mode 100644 docs/dev/design_issues/ITL-1591-NFK1.md create mode 100644 src/orcapod/semantic_types/narrow_float_keys.py create mode 100644 tests/test_semantic_types/test_narrow_float_keys_refused.py diff --git a/.zed/rules b/.zed/rules index 47691fb2e..696badf2e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1416,6 +1416,20 @@ data. The rules: Batch with a size has its own form, grouping rows by arrival. A new operator whose output rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch code. +- A dict key and a set element are never `float32` or `float16` (developer, November 28, 2026, + D16 and D25, ITL-1591): a float stored under such a type is narrowed, two distinct floats + can become one stored value, and the container loses an entry. A declared type with such a + key or element is refused (`NarrowFloatKeyError`, an `InputValidationError`) where it is + declared, Python-declared and Arrow-declared alike, at any depth, by a check of types that + never reads a value. One rule, `semantic_types/narrow_float_keys.py`: the type converter + applies it to every dict and set type it builds (sources' Python schemas, datagrams, + user-class fields, a function pod's inputs and outputs when the pod is defined), and + `SourceStreamBuilder.build`, `ArrowTableStream.__init__` and a datagram given an Arrow + table apply it to the table's schema; never check it elsewhere. A dict is the converter's + one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an + Arrow map; a set is the native set container, live or in its storage form. `float32` and + `float16` stay valid as a plain column, a list element, a struct field and a dict value; + the silent narrowing of such plain values from an Arrow declaration is ITL-1613. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 29205c0e3..4716405f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1464,6 +1464,20 @@ data. The rules: input (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no other per-operator batch code. +- A dict key and a set element are never `float32` or `float16` (developer, November 28, 2026, + D16 and D25, ITL-1591): a float stored under such a type is narrowed, two distinct floats + can become one stored value, and the container loses an entry. A declared type with such a + key or element is refused (`NarrowFloatKeyError`, an `InputValidationError`) where it is + declared, Python-declared and Arrow-declared alike, at any depth, by a check of types that + never reads a value. One rule, `semantic_types/narrow_float_keys.py`: the type converter + applies it to every dict and set type it builds (sources' Python schemas, datagrams, + user-class fields, a function pod's inputs and outputs when the pod is defined), and + `SourceStreamBuilder.build`, `ArrowTableStream.__init__` and a datagram given an Arrow + table apply it to the table's schema; never check it elsewhere. A dict is the converter's + one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an + Arrow map; a set is the native set container, live or in its storage form. `float32` and + `float16` stay valid as a plain column, a list element, a struct field and a dict value; + the silent narrowing of such plain values from an Arrow declaration is ITL-1613. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md new file mode 100644 index 000000000..dc2645c42 --- /dev/null +++ b/changelog.d/ITL-1591.md @@ -0,0 +1,24 @@ +### Breaking changes and migration + +- **`float32` and `float16` are refused as a dict key type and as a set element type** + (ITL-1591). A float stored under such a type is narrowed, and two distinct floats can + narrow to one stored value (`1e-50` and `2e-50` both become `0.0`), so a dict or a set + lost an entry without notice. A declared type with such a key or element, at any nesting + depth (a dict in a list, a dict as a dict value, a dict in a tuple or a user-class field, + an Arrow `map`), now raises `NarrowFloatKeyError` (an `InputValidationError`) naming the + column and the key or element type, where the type is declared: a source's Python or + Arrow schema, the table given to a source or to an `ArrowTableStream`, a datagram's + schema or table, and a function pod's parameters and outputs when the pod is defined + (`-> dict[np.float32, int]`, `set[np.float32]`). The check reads types only, never a + value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in + Arrow), or use another type. `float32` and `float16` are still accepted as a plain + column, a list element, a struct field and a dict value. + +### Known limitations + +- A plain value (not a dict key or set element) stored into a column that an Arrow schema + declares `float32` or `float16` is still narrowed without a warning: `0.1` under + `pa.float16()` is stored as `0.0999755859375` (ITL-1613). +- A struct column whose fields are exactly `key` and `value` has the stored shape of a dict + once `Batch`, `GroupBy` or `MergeJoin` collects it into a list. With a `float32` or + `float16` field `key`, that result is refused as a dict keyed by a narrow float. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 03d09578f..2388438a9 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -285,6 +285,13 @@ 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 dictionary key and a set element cannot be `np.float32` or `np.float16` +(`dict[np.float32, int]`, `set[np.float32]`, at any depth): a float stored under such a type +is narrowed, two distinct floats can become one stored value, and the dictionary or set would +lose an entry. Such a parameter or output raises `NarrowFloatKeyError` when the pod is +defined (ITL-1591). Declare the key or element as `float`. `np.float32` remains valid as a +plain value, a list element and a dictionary value. + 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..d9208b217 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -182,6 +182,11 @@ print(labels_type.storage_type) `NestedTypeNotStorableError` that names the column or `Class.field` (ITL-1150). Hold the set in a dataclass field, where it keeps its type, or declare the plain type (`dict[str, list[int]]`). +- A set of `float32` or `float16` elements is refused where it is declared, in Python + (`set[np.float32]`) and in Arrow (`set[float]`, `set[halffloat]`), with a + `NarrowFloatKeyError`: a float stored under such a type is narrowed, two distinct floats can + become one stored element, and the set would lose one (ITL-1591). Declare `set[float]` + (`set[double]`). The same holds for the key of a dict. - `frozenset[T]` is not supported: declare `set[T]`. Support is to be evaluated in ITL-1140. A container type you implement yourself is not a native container. It is an ordinary logical diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md new file mode 100644 index 000000000..c8f86996b --- /dev/null +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -0,0 +1,31 @@ +## `src/orcapod/semantic_types/universal_converter.py` + +### NFK1 — A float32 or float16 dict key or set element loses an entry when a float is narrowed +**Status:** resolved +**Severity:** high +**Issue:** ITL-1591 (related: ITL-924, ITL-1613) + +A Python float stored under a `float32` or `float16` type is narrowed without notice, and two +distinct floats can narrow to one stored value (`1e-50` and `2e-50` both become `0.0`). For +the keys of a dict and the elements of a set that lost an entry: a `DictSource` with an Arrow +`data_schema` whose column `k` is `large_list>` stored +`{1e-50: 1, 2e-50: 2}` with two `0.0` keys, a set column `{1e-50, 2e-50}` was stored as +`[0.0, 0.0]` and read back `{0.0}`, and updating a datagram held as an Arrow table did the +same. No warning, no error. + +**Fix:** developer decisions D16 and D25 (November 28, 2026): a declared type whose dict key +or set element is `float32` or `float16` is refused where it is declared, in a Python schema +or annotation and in an Arrow schema or table alike, at any nesting depth, by a check of +types that reads no value. One rule, `semantic_types/narrow_float_keys.py` +(`NarrowFloatKeyError`, an `InputValidationError`): the type converter applies it to every +dict and set type it builds (so a source's Python schema, a datagram's, a user-class field +and a function pod's declared inputs and outputs, when the pod is defined), and the source +builder, `ArrowTableStream` and a datagram given an Arrow table apply it to the table's +schema. A dict is the converter's one dict shape (`nested_storage.dict_entry_fields`, now +used by the converter's two readers too) or an Arrow map. `float32` and `float16` stay +accepted as a plain column, a list element, a struct field and a dict value. + +Left as it is: a plain value in an Arrow-declared `float32` or `float16` column is still +narrowed silently (ITL-1613). A struct column whose fields are exactly `key` and `value` +becomes the dict shape once `Batch`, `GroupBy` or `MergeJoin` puts it in a list, and is +refused there when its `key` is `float32` or `float16`. diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 23acd12ac..6151af0be 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -37,6 +37,11 @@ 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.narrow_float_keys import ( + NarrowFloatKeyError, + require_schema_without_narrow_float_keys, +) +from orcapod.semantic_types.nested_none import with_context from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils @@ -188,6 +193,8 @@ def _init_from_dict( if python_schema else inferred ) + if python_schema: + self._refuse_narrow_float_keys(python_schema) self._data_dict = self._canonical_dict_values( data_columns, self._data_python_schema ) @@ -202,6 +209,29 @@ def _init_from_dict( self._meta_table: pa.Table | None = None self._context_table: pa.Table | None = None + def _refuse_narrow_float_keys(self, python_schema: SchemaLike) -> None: + """Refuse a declared type with a ``float32`` or ``float16`` dict key or set element. + + The datagram converts its values to Arrow only when asked for a table; a type + with such a key or element is refused when it is declared, here (ITL-1591). + The rule is the type converter's, applied when it maps the declared type to + Arrow. Any other reason a declared type has no Arrow type is reported where it + is today, by the conversion. + + Args: + python_schema: The declared Python types, by column name. + + Raises: + NarrowFloatKeyError: Naming the column and its declared type. + """ + for name, python_type in python_schema.items(): + try: + self.converter.python_type_to_arrow_type(python_type) + except NarrowFloatKeyError as exc: + raise with_context(f"Column {name!r} ({python_type})", exc) from exc + except Exception: # noqa: BLE001 - reported by the conversion, as before + continue + def _canonical_dict_values( self, columns: dict[str, DataValue], schema: Schema ) -> dict[str, DataValue]: @@ -237,6 +267,10 @@ def _init_from_table( ) table = arrow_utils.normalize_table_to_large_types(table) + # A dict keyed by, or a set of, float32 or float16 is refused where its type + # is declared, here by the table (ITL-1591): an update would narrow two + # distinct floats to one stored value and lose an entry. + require_schema_without_narrow_float_keys(table.schema) # Extract context from table if not provided externally if constants.CONTEXT_KEY in table.column_names and data_context is None: diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 22736f37f..337c65421 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -27,6 +27,9 @@ from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants from orcapod.types import ContentHash +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash @@ -559,6 +562,9 @@ def build( raise schema_utils.schema_hash_rejected_columns_error( found, tag_columns_tuple, data_tags_tuple, system_tag_columns_tuple ) + # Nor is a dict keyed by, or a set of, float32 or float16 (ITL-1591): refused + # here first, as the stream refuses it, before any key column or hash. + require_schema_without_narrow_float_keys(table.schema) # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..bce6d0ca1 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -20,6 +20,9 @@ from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.utils import arrow_utils, schema_utils logger = logging.getLogger(__name__) @@ -102,6 +105,11 @@ def __init__( found, tag_columns, data_tags, system_tag_columns ) + # Nor is a dict keyed by, or a set of, float32 or float16 (developer, November + # 28, 2026, ITL-1591): two distinct floats can narrow to one stored value, so + # an entry would be lost. A check of types, as the two above. + require_schema_without_narrow_float_keys(table.schema) + data_table, data_context_table = arrow_utils.split_by_column_groups( table, [constants.CONTEXT_KEY] ) diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 7f9578b3b..87de34fdd 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -34,6 +34,7 @@ require_restorable_none, with_context, ) +from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError from orcapod.logical_types.registry import ( make_arrow_extension_type, @@ -330,7 +331,11 @@ def _storage( UserClassLogicalType, ), ) - except (NestedNoneNotRestorableError, NestedTypeNotStorableError) as exc: + except ( + NestedNoneNotRestorableError, + NestedTypeNotStorableError, + NarrowFloatKeyError, + ) as exc: raise with_context( f"{python_type.__qualname__}.{field_name} ({annotation})", exc ) from exc diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py new file mode 100644 index 000000000..9f7cded39 --- /dev/null +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -0,0 +1,217 @@ +"""No dict key and no set element is declared ``float32`` or ``float16`` (ITL-1591). + +Developer decisions D16 and D25, November 28, 2026. A Python float stored under a +``float32`` or ``float16`` type is narrowed, and two distinct values can narrow to one +stored value (``1e-50`` and ``2e-50`` both become ``0.0``). For a plain value that is a +loss of precision; for the keys of a dict or the elements of a set it loses an entry, +because the container read back holds one of them. So a declared type whose dict key or +set element is ``float32`` or ``float16`` is refused where it is declared, in a Python +schema or annotation and in an Arrow schema or table alike. The refusal reads types +only, never a value. + +What counts, at the top of a type and at any depth inside it (a list item, a struct +child, a dict or map key or value, a logical type's storage): + +- the key of a dict: the type converter's dict shape (``nested_storage.dict_entry_fields``, + a list of ``{key, value}`` structs) or an Arrow ``map``; +- the element of a set: the native ``set[T]`` container (a ``ListLogicalType`` of the + set category), as a live extension type or as its storage with the identifier in + ``ARROW:extension:*`` field metadata. + +A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is +accepted, and so is a ``float64`` key or element. + +The rule is here once. The type converter applies it to every dict and set type it +builds from a Python declaration (``require_no_narrow_float_keys``); the source builder, +``ArrowTableStream`` and a datagram over an Arrow table apply it to an Arrow schema +(``require_schema_without_narrow_float_keys``). +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import TYPE_CHECKING + +from orcapod.errors import InputValidationError +from orcapod.semantic_types.nested_storage import dict_entry_fields + +if TYPE_CHECKING: + import pyarrow as pa + +NARROW_FLOAT_KEYS_NOT_SUPPORTED = ( + "float32 and float16 are not supported as a dict key type or a set element type" +) +"""The start of every refusal of this rule.""" + +_REMEDY = ( + "A float stored under such a type is narrowed, so two distinct keys or elements can " + "become one stored value and an entry is lost. Declare the key or element as float64 " + "(float in Python, pa.float64() in Arrow), or use another type (an integer or a " + "string)." +) + +_EXTENSION_METADATA_KEY = b"ARROW:extension:metadata" + + +class NarrowFloatKeyError(InputValidationError, ValueError): + """A declared type has a ``float32`` or ``float16`` dict key or set element.""" + + +def _is_narrow_float(arrow_type: pa.DataType) -> bool: + import pyarrow as pa + + if isinstance(arrow_type, pa.BaseExtensionType): + arrow_type = arrow_type.storage_type + return pa.types.is_float32(arrow_type) or pa.types.is_float16(arrow_type) + + +def _is_set_metadata(raw: bytes | None) -> bool: + """Whether extension metadata ``raw`` is that of a native set container.""" + from orcapod.logical_types.list_logical_type_factory import SET_CATEGORY + + if not raw: + return False + try: + metadata = json.loads(raw) + except ValueError: + return False + return isinstance(metadata, dict) and metadata.get("category") == SET_CATEGORY + + +def _dict_key( + arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None +) -> str | None: + """Say so when ``arrow_type`` stores a dict whose key is a narrow float.""" + import pyarrow as pa + + if pa.types.is_map(arrow_type): + key_type = arrow_type.key_type + elif (entry_fields := dict_entry_fields(arrow_type)) is not None: + key_type = entry_fields[0].type + else: + return None + return f"dict key type {key_type}" if _is_narrow_float(key_type) else None + + +def _set_element( + arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None +) -> str | None: + """Say so when ``arrow_type`` stores a set whose element is a narrow float.""" + import pyarrow as pa + + if isinstance(arrow_type, pa.ExtensionType): + raw = arrow_type.__arrow_ext_serialize__() + storage = arrow_type.storage_type + else: + raw = (field_metadata or {}).get(_EXTENSION_METADATA_KEY) + storage = arrow_type + if not _is_set_metadata(raw): + return None + if not (pa.types.is_list(storage) or pa.types.is_large_list(storage)): + return None + element_type = storage.value_type + if _is_narrow_float(element_type): + return f"set element type {element_type}" + return None + + +_REFUSED_PARTS = (_dict_key, _set_element) +"""The parts of a declared type that may not be a narrow float. + +Each takes one Arrow type with the metadata of the field that holds it, at any depth of +a declared type, and returns the description of what it refuses there, or ``None``. +""" + + +def narrow_float_keys( + arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None = None +) -> list[str]: + """Return what the rule refuses in ``arrow_type``, at any depth. + + Args: + arrow_type: A declared Arrow type, or the Arrow type a declared Python type + maps to. + field_metadata: The metadata of the field that holds the type, when it has + one: a set in its storage form is known by it. + + Returns: + A description of each refused part (``"dict key type float"``, + ``"set element type halffloat"``), sorted, each once; empty when the type is + accepted. + """ + import pyarrow as pa + + found = { + description + for part in _REFUSED_PARTS + if (description := part(arrow_type, field_metadata)) is not None + } + children: list[tuple[pa.DataType, Mapping[bytes, bytes] | None]] + if isinstance(arrow_type, pa.BaseExtensionType): + children = [(arrow_type.storage_type, None)] + elif ( + pa.types.is_list(arrow_type) + or pa.types.is_large_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + ): + item = arrow_type.value_field + children = [(item.type, item.metadata)] + elif pa.types.is_struct(arrow_type): + children = [(child.type, child.metadata) for child in arrow_type] + elif pa.types.is_map(arrow_type): + children = [ + (arrow_type.key_field.type, arrow_type.key_field.metadata), + (arrow_type.item_field.type, arrow_type.item_field.metadata), + ] + else: + children = [] + for child_type, child_metadata in children: + found.update(narrow_float_keys(child_type, child_metadata)) + return sorted(found) + + +def require_no_narrow_float_keys(arrow_type: pa.DataType) -> None: + """Refuse a declared type with a ``float32`` or ``float16`` dict key or set element. + + Args: + arrow_type: A declared Arrow type, or the Arrow type a declared Python type + maps to. + + Raises: + NarrowFloatKeyError: If ``arrow_type`` is, or contains at any depth, a dict + keyed by, or a set of, ``float32`` or ``float16``. The message names the + type and each such part, and the remedy. + """ + if found := narrow_float_keys(arrow_type): + raise NarrowFloatKeyError( + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: Arrow type {arrow_type} has " + f"{', '.join(found)}. {_REMEDY}" + ) + + +def require_schema_without_narrow_float_keys(arrow_schema: pa.Schema) -> None: + """Refuse an Arrow schema with a ``float32`` or ``float16`` dict key or set element. + + Applied to the table a source is built from, to the table of every stream and to + the table a datagram is given, so a type declared in Arrow is refused as one + declared in Python is. No value is read. + + Args: + arrow_schema: The Arrow schema of the table. + + Raises: + NarrowFloatKeyError: If a column's type is, or contains at any depth, a dict + keyed by, or a set of, ``float32`` or ``float16``. The message names each + such column, in name order, with its type and each such part, and the + remedy. + """ + lines = [ + f" - column {field.name!r} has type {field.type} ({', '.join(found)})" + for field in sorted(arrow_schema, key=lambda field: field.name) + if (found := narrow_float_keys(field.type, field.metadata)) + ] + if lines: + raise NarrowFloatKeyError( + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}:\n" + "\n".join(lines) + f"\n{_REMEDY}" + ) diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 37ee98ba6..3a55cee18 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -12,7 +12,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any if TYPE_CHECKING: import pyarrow as pa @@ -45,3 +45,39 @@ def require_storable_in_struct_field(arrow_type: pa.DataType) -> None: f"or declare the plain type (e.g. dict[str, list[int]] for " f"dict[str, set[int]]). Follow-up: {_FOLLOW_UP}." ) + + +def dict_entry_fields( + arrow_type: pa.DataType, +) -> tuple[pa.Field[Any], pa.Field[Any]] | None: + """Return the key and value fields of ``arrow_type`` when it stores a dict. + + The one definition of the dict shape: a ``dict[K, V]`` is stored as a list (large, + plain or fixed-size) of structs with exactly the two fields ``key`` and ``value``. + The converter reads such a type as a dict (``arrow_type_to_python_type``, + ``get_arrow_to_python_converter``), and the refusal of a narrow float key in a + declared type (``narrow_float_keys``, ITL-1591) asks here too. An Arrow ``map`` is + read as a dict as well and is not this shape: its key and item types are the + type's own. + + Args: + arrow_type: Any Arrow type. + + Returns: + ``(key field, value field)``, or ``None`` when ``arrow_type`` is not a list of + ``{key, value}`` structs. + """ + import pyarrow as pa + + if not ( + pa.types.is_list(arrow_type) + or pa.types.is_large_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + ): + return None + element_type = arrow_type.value_type + if not pa.types.is_struct(element_type): + return None + if {field.name for field in element_type} != {"key", "value"}: + return None + return element_type.field("key"), element_type.field("value") diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 678270275..cc4ff6996 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -44,7 +44,12 @@ unrestorable_none_error, with_context, ) +from orcapod.semantic_types.narrow_float_keys import ( + NarrowFloatKeyError, + require_no_narrow_float_keys, +) from orcapod.semantic_types.nested_storage import ( + dict_entry_fields, NestedTypeNotStorableError, require_storable_in_struct_field, ) @@ -338,6 +343,7 @@ def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: except ( NestedNoneNotRestorableError, NestedTypeNotStorableError, + NarrowFloatKeyError, ) as exc: raise with_context(f"Column {name!r} ({annotation})", exc) from exc @@ -513,9 +519,13 @@ def _register_python_class_impl( 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) - return pa.large_list( + dict_arrow = pa.large_list( pa.struct([pa.field("key", key_arrow), pa.field("value", val_arrow)]) ) + # A dict keyed by float32 or float16 is refused where it is declared + # (ITL-1591). + require_no_narrow_float_keys(dict_arrow) + return dict_arrow # Concrete class — registry or factory dispatch if isinstance(annotation, type): @@ -627,6 +637,8 @@ def _make_or_get_arrow_element_set_type( ), is_set=True, ) + # A set of float32 or float16 is refused where it is declared (ITL-1591). + require_no_narrow_float_keys(lt.get_arrow_extension_type()) existing = self._logical_type_registry.get_by_arrow_extension_name( lt.logical_type_name ) @@ -1082,7 +1094,11 @@ def python_schema_to_arrow_schema(self, python_schema: SchemaLike) -> pa.Schema: for field_name, python_type in python_schema.items(): try: arrow_type = self.python_type_to_arrow_type(python_type) - except (NestedNoneNotRestorableError, NestedTypeNotStorableError) as exc: + except ( + NestedNoneNotRestorableError, + NestedTypeNotStorableError, + NarrowFloatKeyError, + ) as exc: raise with_context( f"Column {field_name!r} ({python_type})", exc ) from exc @@ -1564,7 +1580,11 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: require_storable_in_struct_field(value_type) require_restorable_none(args[1], value_type, self._is_user_class_extension) key_value_struct = pa.struct([("key", key_type), ("value", value_type)]) - return pa.large_list(key_value_struct) + dict_arrow = pa.large_list(key_value_struct) + # A dict keyed by float32 or float16 is refused where it is declared + # (ITL-1591). + require_no_narrow_float_keys(dict_arrow) + return dict_arrow # Handle Union/Optional types elif origin is typing.Union or origin is types.UnionType: @@ -1702,17 +1722,12 @@ def _convert_arrow_to_python(self, arrow_type: pa.DataType) -> type | Any: element_type = arrow_type.value_type # Check if this is a dict representation: list> - if pa.types.is_struct(element_type): - field_names = [field.name for field in element_type] - if set(field_names) == {"key", "value"}: - # This is a dict - key_field = next(f for f in element_type if f.name == "key") - value_field = next(f for f in element_type if f.name == "value") - - key_python_type = self.arrow_type_to_python_type(key_field.type) - value_python_type = self.arrow_type_to_python_type(value_field.type) + if (entry_fields := dict_entry_fields(arrow_type)) is not None: + key_field, value_field = entry_fields + key_python_type = self.arrow_type_to_python_type(key_field.type) + value_python_type = self.arrow_type_to_python_type(value_field.type) - return dict[key_python_type, value_python_type] + return dict[key_python_type, value_python_type] # Regular list element_python_type = self.arrow_type_to_python_type(element_type) @@ -2029,30 +2044,25 @@ def _create_arrow_to_python_converter( element_type = arrow_type.value_type # Check if this is a dict representation - if pa.types.is_struct(element_type): - field_names = [field.name for field in element_type] - if set(field_names) == {"key", "value"}: - # Dict representation - key_field = next(f for f in element_type if f.name == "key") - value_field = next(f for f in element_type if f.name == "value") - - key_converter = self.get_arrow_to_python_converter(key_field.type) - value_converter = self._nested_value_converter(value_field.type) - - def convert_entries(value: Any) -> dict[Any, Any]: - if not value: - return {} - converted = {} - for item in value: - # A null entry is not a key/value pair: never drop it. - if item is None: - raise unrestorable_none_error(element_type) - converted[key_converter(item["key"])] = value_converter( - item["value"] - ) - return converted + if (entry_fields := dict_entry_fields(arrow_type)) is not None: + key_field, value_field = entry_fields + key_converter = self.get_arrow_to_python_converter(key_field.type) + value_converter = self._nested_value_converter(value_field.type) + + def convert_entries(value: Any) -> dict[Any, Any]: + if not value: + return {} + converted = {} + for item in value: + # A null entry is not a key/value pair: never drop it. + if item is None: + raise unrestorable_none_error(element_type) + converted[key_converter(item["key"])] = value_converter( + item["value"] + ) + return converted - return convert_entries + return convert_entries # Regular list element_converter = self._nested_value_converter(element_type) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py new file mode 100644 index 000000000..e6e5ea6ba --- /dev/null +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -0,0 +1,620 @@ +"""No dict key and no set element is declared ``float32`` or ``float16`` (ITL-1591). + +Developer decisions D16 and D25, November 28, 2026. A Python float stored under a +``float32`` or ``float16`` type is narrowed, and two distinct values can narrow to one +(``1e-50`` and ``2e-50`` both become ``0.0``): a dict stored two ``0.0`` keys and a set two +``0.0`` elements, so the container read back had lost an entry. A declared type whose +dict key or set element is ``float32`` or ``float16`` is therefore refused where it is +declared, in a Python schema or annotation and in an Arrow schema or table alike, at any +nesting depth, by a check of types that reads no value. The rule is +``semantic_types/narrow_float_keys.py``; the dict shape is the type converter's one +definition (``nested_storage.dict_entry_fields``), and an Arrow ``map`` is a dict too. + +A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is +accepted, and so is a ``float64`` key or element. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +import numpy as np +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import contexts, function_pod +from orcapod.core.datagrams import Data, Datagram, Tag +from orcapod.core.sources import ( + ArrowTableSource, + DataFrameSource, + DeltaTableSource, + DictSource, + ListSource, +) +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError +from orcapod.semantic_types.narrow_float_keys import ( + NARROW_FLOAT_KEYS_NOT_SUPPORTED, + NarrowFloatKeyError, + narrow_float_keys, + require_no_narrow_float_keys, + require_schema_without_narrow_float_keys, +) +from orcapod.semantic_types.nested_storage import dict_entry_fields + +NOT_SUPPORTED = NARROW_FLOAT_KEYS_NOT_SUPPORTED + + +def _converter() -> Any: + return contexts.resolve_context(None).type_converter + + +def _dict_of(key: pa.DataType, value: pa.DataType = pa.int64()) -> pa.DataType: + """The converter's stored form of ``dict[key, value]``.""" + return pa.large_list(pa.struct([("key", key), ("value", value)])) + + +def _set_storage_field(element: pa.DataType) -> pa.Field[Any]: + """A set in its storage form: the storage type, the identifier in field metadata.""" + live = _live_set(element) + return pa.field( + "item", + live.storage_type, + metadata={ + "ARROW:extension:name": live.extension_name, + "ARROW:extension:metadata": live.__arrow_ext_serialize__(), + }, + ) + + +def _live_set(element: pa.DataType) -> Any: + """The native ``set[T]`` container of a plain Arrow element, as the library builds it.""" + from orcapod.logical_types.list_logical_type_factory import ( + ArrowElement, + ListLogicalType, + ) + + return ListLogicalType( + ArrowElement(float, element), is_set=True + ).get_arrow_extension_type() + + +NARROW: list[pa.DataType] = [pa.float32(), pa.float16()] +WIDE_OR_OTHER: list[pa.DataType] = [pa.float64(), pa.int64(), pa.large_string()] + +# Every place a dict key can sit in a column's type: (name, builder of the column type +# from the key type). +DICT_PLACES: list[tuple[str, Callable[[pa.DataType], pa.DataType]]] = [ + ("top_level", _dict_of), + ( + "non_large_list", + lambda k: pa.list_(pa.struct([("key", k), ("value", pa.int64())])), + ), + ( + "value_first", + lambda k: pa.large_list(pa.struct([("value", pa.int64()), ("key", k)])), + ), + ("in_a_list", lambda k: pa.large_list(_dict_of(k))), + ("in_a_fixed_size_list", lambda k: pa.list_(_dict_of(k), 2)), + ("as_a_dict_value", lambda k: _dict_of(pa.large_string(), _dict_of(k))), + ("as_a_dict_key", lambda k: _dict_of(_dict_of(k))), + ("in_a_struct", lambda k: pa.struct([("a", pa.int64()), ("d", _dict_of(k))])), + ( + "deep", + lambda k: pa.large_list( + pa.struct([("s", pa.struct([("d", _dict_of(pa.int64(), _dict_of(k)))]))]) + ), + ), + ("map", lambda k: pa.map_(k, pa.int64())), + ("map_in_a_list", lambda k: pa.large_list(pa.map_(k, pa.int64()))), + ("as_a_map_value", lambda k: pa.map_(pa.large_string(), _dict_of(k))), +] + +# Every place a set element can sit. +SET_PLACES: list[tuple[str, Callable[[pa.DataType], pa.DataType]]] = [ + ("live_set", _live_set), + ("storage_form_in_a_list", lambda e: pa.large_list(_set_storage_field(e))), + ( + "storage_form_in_a_struct", + lambda e: pa.struct( + [pa.field("a", pa.int64()), _set_storage_field(e).with_name("s")] + ), + ), +] + + +def _cases( + places: list[tuple[str, Callable[[pa.DataType], pa.DataType]]], + parts: list[pa.DataType], +) -> list[Any]: + return [ + pytest.param(build, part, id=f"{name}-{part}") + for name, build in places + for part in parts + ] + + +class TestTheRule: + """A check of types, at every depth.""" + + @pytest.mark.parametrize(("build", "key"), _cases(DICT_PLACES, NARROW)) + def test_refuses_a_narrow_float_dict_key_wherever_the_dict_sits( + self, build: Callable[[pa.DataType], pa.DataType], key: pa.DataType + ) -> None: + column_type = build(key) + assert narrow_float_keys(column_type) == [f"dict key type {key}"] + with pytest.raises(NarrowFloatKeyError) as raised: + require_schema_without_narrow_float_keys( + pa.schema([("id", pa.int64()), ("k", column_type)]) + ) + message = str(raised.value) + assert message.startswith(NOT_SUPPORTED) + assert "'k'" in message and "'id'" not in message + assert f"dict key type {key}" in message + assert "float64" in message + + @pytest.mark.parametrize(("build", "element"), _cases(SET_PLACES, NARROW)) + def test_refuses_a_narrow_float_set_element_wherever_the_set_sits( + self, build: Callable[[pa.DataType], pa.DataType], element: pa.DataType + ) -> None: + column_type = build(element) + assert narrow_float_keys(column_type) == [f"set element type {element}"] + with pytest.raises(NarrowFloatKeyError) as raised: + require_schema_without_narrow_float_keys( + pa.schema([("id", pa.int64()), ("s", column_type)]) + ) + message = str(raised.value) + assert message.startswith(NOT_SUPPORTED) + assert "'s'" in message and f"set element type {element}" in message + + @pytest.mark.parametrize("element", NARROW, ids=str) + def test_refuses_a_top_level_set_in_its_storage_form( + self, element: pa.DataType + ) -> None: + field = _set_storage_field(element).with_name("s") + assert narrow_float_keys(field.type) == [] # a plain list without its metadata + with pytest.raises(NarrowFloatKeyError, match="set element type"): + require_schema_without_narrow_float_keys(pa.schema([field])) + + @pytest.mark.parametrize( + ("build", "part"), _cases(DICT_PLACES + SET_PLACES, WIDE_OR_OTHER) + ) + def test_accepts_every_other_key_and_element_type( + self, build: Callable[[pa.DataType], pa.DataType], part: pa.DataType + ) -> None: + column_type = build(part) + assert narrow_float_keys(column_type) == [] + require_no_narrow_float_keys(column_type) + require_schema_without_narrow_float_keys( + pa.schema([("id", pa.int64()), ("k", column_type)]) + ) + + @pytest.mark.parametrize("narrow", NARROW, ids=str) + def test_a_narrow_float_that_is_no_key_and_no_element_is_accepted( + self, narrow: pa.DataType + ) -> None: + """A plain value, a list element, a struct field and a dict VALUE.""" + require_schema_without_narrow_float_keys( + pa.schema( + [ + ("plain", narrow), + ("listed", pa.large_list(narrow)), + ("fixed", pa.list_(narrow, 2)), + ("field", pa.struct([("key", narrow), ("other", pa.int64())])), + ("lone_key", pa.large_list(pa.struct([("key", narrow)]))), + ("dict_value", _dict_of(pa.large_string(), narrow)), + ("map_value", pa.map_(pa.large_string(), narrow)), + ] + ) + ) + + def test_names_every_such_column_whatever_the_column_order(self) -> None: + fields = [ + pa.field("b", _dict_of(pa.float16())), + pa.field("fine", _dict_of(pa.float64())), + pa.field("a", pa.map_(pa.float32(), pa.int64())), + pa.field("c", _live_set(pa.float32())), + pa.field( + "both", _dict_of(pa.float32(), pa.large_list(_dict_of(pa.float16()))) + ), + ] + messages = [] + for ordered in (fields, fields[::-1], fields[2:] + fields[:2]): + with pytest.raises(NarrowFloatKeyError) as raised: + require_schema_without_narrow_float_keys(pa.schema(ordered)) + messages.append(str(raised.value)) + message = messages[0] + assert all(f"'{name}'" in message for name in ("a", "b", "c", "both")) + assert "'fine'" not in message + assert "(dict key type float, dict key type halffloat)" in message + assert "set element type float" in message + assert messages[0] == messages[1] == messages[2] + + def test_the_dict_shape_is_the_type_converters(self) -> None: + """The rule and the converter read one definition of the dict shape.""" + converted = _converter().python_type_to_arrow_type(dict[float, int]) + fields = dict_entry_fields(converted) + assert fields is not None + assert (fields[0].type, fields[1].type) == (pa.float64(), pa.int64()) + assert dict_entry_fields(pa.large_list(pa.float32())) is None + assert ( + dict_entry_fields( + pa.large_list(pa.struct([("key", pa.float32()), ("v", pa.int64())])) + ) + is None + ) + assert dict_entry_fields(pa.map_(pa.float32(), pa.int64())) is None + + def test_the_error_is_an_input_validation_error(self) -> None: + assert issubclass(NarrowFloatKeyError, InputValidationError) + assert issubclass(NarrowFloatKeyError, ValueError) + + +D = dict[np.float32, int] +S = set[np.float32] + +# Declared Python types that hold a float32 key or element, with a value of each. +PYTHON_TYPES: list[tuple[str, Any, Any]] = [ + ("dict", D, {np.float32(0.5): 1}), + ("set", S, {np.float32(0.5)}), + ("optional_dict", D | None, None), + ("optional_set", S | None, None), + ("dict_in_a_list", list[D], [{np.float32(0.5): 1}]), + ("set_in_a_list", list[S], [{np.float32(0.5)}]), + ("dict_as_a_dict_value", dict[str, D], {"a": {np.float32(0.5): 1}}), + ("optional_key", dict[np.float32 | None, int], {np.float32(0.5): 1}), +] +PYTHON_CASES = [ + pytest.param(python_type, value, id=name) + for name, python_type, value in PYTHON_TYPES +] + +# Declared Python types that must keep working, with a value of each. +ACCEPTED_PYTHON: dict[str, tuple[Any, Any]] = { + "plain": (np.float32, np.float32(0.5)), + "listed": (list[np.float32], [np.float32(0.5), np.float32(1.5)]), + "dict_value": (dict[str, np.float32], {"a": np.float32(0.5)}), + "wide_key": (dict[float, int], {1e-50: 1, 2e-50: 2}), + "wide_set": (set[float], {1e-50, 2e-50}), +} + + +@dataclasses.dataclass +class HoldsNarrowKey: + """A user class with a float32-keyed dict field.""" + + d: dict[np.float32, int] + + +class TestPythonDeclarations: + """A type declared in Python is refused when it is declared.""" + + @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) + def test_the_converter_refuses_the_type(self, python_type: Any, value: Any) -> None: + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + _converter().python_type_to_arrow_type(python_type) + + @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) + @pytest.mark.parametrize("kind", [Datagram, Tag, Data]) + def test_a_datagram_refuses_it_when_built( + self, kind: type[Datagram], python_type: Any, value: Any + ) -> None: + """At construction, before any table is asked for; in either column order.""" + for columns in ( + {"k": python_type, "x": int, "y": str}, + {"y": str, "x": int, "k": python_type}, + ): + with pytest.raises(NarrowFloatKeyError) as raised: + kind({"k": value, "x": 1, "y": "a"}, python_schema=columns) + assert "Column 'k'" in str(raised.value) + assert NOT_SUPPORTED in str(raised.value) + + @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) + def test_a_source_with_a_python_schema_refuses_it( + self, python_type: Any, value: Any + ) -> None: + with pytest.raises(NarrowFloatKeyError) as raised: + DictSource( + [{"id": 1, "g": "a", "x": 1, "k": value}], + tag_columns=["id", "g"], + tag_only_columns=True, + data_schema={"id": int, "g": str, "x": int, "k": python_type}, + ) + assert "'k'" in str(raised.value) + + @pytest.mark.parametrize("declared", [tuple[D, D], tuple[int, D]], ids=str) + def test_a_tuple_field_is_refused(self, declared: Any) -> None: + """A dict in a tuple: where a tuple type is converted (a datagram).""" + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + _converter().python_type_to_arrow_type(declared) + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + Datagram({"k": ({}, {}), "x": 1}, python_schema={"k": declared, "x": int}) + + def test_a_list_source_refuses_it(self) -> None: + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + ListSource("k", [{np.float32(0.5): 1}], data_schema={"k": D}) + + def test_a_user_class_field_is_refused(self) -> None: + with pytest.raises(NarrowFloatKeyError) as raised: + DictSource( + [{"id": 1, "c": cast(Any, HoldsNarrowKey({}))}], + tag_columns=["id"], + tag_only_columns=True, + data_schema={"id": int, "c": HoldsNarrowKey}, + ) + assert "HoldsNarrowKey.d" in str(raised.value) + + @pytest.mark.parametrize("declared", [D, S, list[S], dict[str, D]], ids=str) + def test_a_function_pod_refuses_a_declared_output_when_defined( + self, declared: Any + ) -> None: + def produce(x: int, y: int): # noqa: ANN202 - annotated below + raise AssertionError("never called") + + produce.__annotations__ = {"x": int, "y": int, "return": declared} + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + function_pod(output_keys="o")(produce) + + @pytest.mark.parametrize("declared", [D, S, list[S], dict[str, D]], ids=str) + def test_a_function_pod_refuses_a_declared_input_when_defined( + self, declared: Any + ) -> None: + """Whichever parameter declares it, of several.""" + for declared_types in ( + {"a": int, "b": declared, "c": str, "return": int}, + {"a": declared, "b": int, "c": str, "return": int}, + ): + + def consume(a, b, c): # noqa: ANN001, ANN202 - annotated below + raise AssertionError("never called") + + consume.__annotations__ = declared_types + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + function_pod(output_keys="o")(consume) + + def test_a_function_pod_refuses_one_of_several_outputs(self) -> None: + def produce(x: int) -> tuple[int, dict[np.float32, int], str]: + raise AssertionError("never called") + + with pytest.raises(NarrowFloatKeyError) as raised: + function_pod(output_keys=["n", "d", "s"])(produce) + assert "'d'" in str(raised.value) + + def test_what_must_keep_working_keeps_working(self) -> None: + """float32 as a plain value, list element and dict value; float64 keys.""" + values = {name: value for name, (_, value) in ACCEPTED_PYTHON.items()} + schema = { + name: python_type for name, (python_type, _) in ACCEPTED_PYTHON.items() + } + for order in (list(schema), list(schema)[::-1]): + datagram = Datagram( + {name: values[name] for name in order}, + python_schema={name: schema[name] for name in order}, + ) + read = Datagram(datagram.as_table()).as_dict() + assert read["wide_key"] == {1e-50: 1, 2e-50: 2} + assert read["wide_set"] == {1e-50, 2e-50} + assert read["dict_value"] == {"a": 0.5} + assert read["listed"] == [0.5, 1.5] + assert read["plain"] == 0.5 + + @function_pod(output_keys=["v", "w"]) + def keep( + listed: list[float], + ) -> tuple[dict[str, np.float32], dict[float, int]]: + return {"a": np.float32(listed[0])}, {1e-50: 1, 2e-50: 2} + + source = DictSource( + [{"id": 1, **values}], + tag_columns=["id"], + tag_only_columns=True, + data_schema={"id": int, **schema}, + ) + ((_, data),) = list(keep.pod(source).iter_data()) + assert data.as_dict() == {"v": {"a": 0.5}, "w": {1e-50: 1, 2e-50: 2}} + + +def _table(column_type: pa.DataType) -> pa.Table: + """One row, two tags, two plain data columns and a column ``k`` of the given type.""" + return pa.table( + { + "id": pa.array([1], pa.int64()), + "g": pa.array(["a"], pa.large_string()), + "x": pa.array([1], pa.int64()), + "y": pa.array([0.5], pa.float32()), + "k": pa.array([None], column_type), + } + ) + + +ARROW_CASES = _cases(DICT_PLACES, NARROW) + _cases(SET_PLACES[:1], NARROW) + + +class TestArrowDeclarations: + """A type declared in Arrow is refused where the declaration enters.""" + + def test_the_dict_reproduction_no_longer_loses_an_entry(self) -> None: + """``{1e-50: 1, 2e-50: 2}`` was stored with two ``0.0`` keys.""" + with pytest.raises(NarrowFloatKeyError) as raised: + DictSource( + [{"id": 1, "h": 0.1, "k": {1e-50: 1, 2e-50: 2}}], + tag_columns=["id"], + tag_only_columns=True, + data_schema=pa.schema( + [ + ("id", pa.int64()), + ("h", pa.float16()), + ("k", _dict_of(pa.float32())), + ] + ), + ) + message = str(raised.value) + assert message.startswith(NOT_SUPPORTED) + assert "'k'" in message and "'h'" not in message + + def test_the_set_reproduction_no_longer_loses_an_element(self) -> None: + """``{1e-50, 2e-50}`` was stored as ``[0.0, 0.0]`` and read back ``{0.0}``.""" + with pytest.raises(NarrowFloatKeyError, match="set element type float"): + DictSource( + [{"id": 1, "k": {1e-50, 2e-50}}], + tag_columns=["id"], + tag_only_columns=True, + data_schema=pa.schema( + [pa.field("id", pa.int64()), pa.field("k", _live_set(pa.float32()))] + ), + ) + + def test_a_float64_key_and_element_from_an_arrow_schema_keep_every_entry( + self, + ) -> None: + source = DictSource( + [{"id": 1, "k": {1e-50: 1, 2e-50: 2}, "s": {1e-50, 2e-50}, "h": 0.5}], + tag_columns=["id"], + tag_only_columns=True, + data_schema=pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("k", _dict_of(pa.float64())), + pa.field("s", _live_set(pa.float64())), + pa.field("h", pa.float32()), + ] + ), + ) + ((_, data),) = list(source.iter_data()) + assert data.as_dict() == { + "k": {1e-50: 1, 2e-50: 2}, + "s": {1e-50, 2e-50}, + "h": 0.5, + } + + @pytest.mark.parametrize(("build", "part"), ARROW_CASES) + def test_an_arrow_table_source_refuses_it_in_every_role_and_tag_order( + self, build: Callable[[pa.DataType], pa.DataType], part: pa.DataType + ) -> None: + table = _table(build(part)) + for tags, tag_only in ( + (["id", "g"], True), + (["g", "id"], True), + (["id", "g"], False), + (["id", "k"], True), + (["k", "id"], False), + ): + with pytest.raises(NarrowFloatKeyError) as raised: + ArrowTableSource(table, tag_columns=tags, tag_only_columns=tag_only) + assert str(raised.value).startswith(NOT_SUPPORTED) + assert "'k'" in str(raised.value) + + @pytest.mark.parametrize(("build", "part"), ARROW_CASES) + def test_a_raw_stream_refuses_it( + self, build: Callable[[pa.DataType], pa.DataType], part: pa.DataType + ) -> None: + table = _table(build(part)) + for layout in (table, table.select(["k", "y", "g", "x", "id"])): + for tags in (["id", "g"], ["g", "id"]): + with pytest.raises(NarrowFloatKeyError) as raised: + ArrowTableStream(layout, tag_columns=tags) + assert str(raised.value).startswith(NOT_SUPPORTED) + + @pytest.mark.parametrize(("build", "part"), ARROW_CASES) + @pytest.mark.parametrize("kind", [Datagram, Tag, Data]) + def test_a_datagram_over_a_table_refuses_it( + self, + kind: type[Datagram], + build: Callable[[pa.DataType], pa.DataType], + part: pa.DataType, + ) -> None: + with pytest.raises(NarrowFloatKeyError) as raised: + kind(_table(build(part))) + assert "'k'" in str(raised.value) + + def test_a_record_batch_is_refused_like_a_table(self) -> None: + batch = _table(_dict_of(pa.float32())).to_batches()[0] + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + Datagram(batch) + + def test_no_value_is_read(self) -> None: + """A table with no rows is refused the same way: the types decide.""" + empty = _table(_dict_of(pa.float32())).slice(0, 0) + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + ArrowTableStream(empty, tag_columns=["id", "g"]) + + def test_a_data_frame_source_refuses_it(self) -> None: + schema = pa.schema( + [("id", pa.int64()), ("x", pa.int64()), ("k", _dict_of(pa.float32()))] + ) + rows = {"id": [1], "x": [1], "k": [[{"key": 0.5, "value": 1}]]} + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + DataFrameSource( + rows, tag_columns=["id"], tag_only_columns=True, schema=schema + ) + frame = pl.DataFrame( + rows, + schema={ + "id": pl.Int64, + "x": pl.Int64, + "k": pl.List(pl.Struct({"key": pl.Float32, "value": pl.Int64})), + }, + ) + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + DataFrameSource(frame, tag_columns=["id"], tag_only_columns=True) + + def test_a_delta_table_source_refuses_it(self, tmp_path: Path) -> None: + from deltalake import write_deltalake + + table = pa.table( + { + "id": pa.array([1], pa.int64()), + "x": pa.array([1], pa.int64()), + "k": pa.array( + [[{"key": 0.5, "value": 1}]], + pa.list_(pa.struct([("key", pa.float32()), ("value", pa.int64())])), + ), + } + ) + path = str(tmp_path / "t") + write_deltalake(path, table) + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + DeltaTableSource(path, tag_columns=["id"], tag_only_columns=True) + + def test_a_narrow_float_that_is_no_key_passes_through_a_stream(self) -> None: + """A plain float32 column, a list of them and a float32 dict value are kept.""" + table = pa.table( + { + "id": pa.array([1, 2], pa.int64()), + "g": pa.array(["a", "b"], pa.large_string()), + "plain": pa.array([0.5, 1.5], pa.float32()), + "half": pa.array([0.5, 1.5], pa.float16()), + "listed": pa.array([[0.5], [1.5]], pa.large_list(pa.float32())), + "dict_value": pa.array( + [[{"key": "a", "value": 0.5}], []], + _dict_of(pa.large_string(), pa.float32()), + ), + "wide_key": pa.array( + [[{"key": 1e-50, "value": 1}, {"key": 2e-50, "value": 2}], []], + _dict_of(pa.float64()), + ), + } + ) + for tags in (["id", "g"], ["g", "id"]): + source = ArrowTableSource(table, tag_columns=tags, tag_only_columns=True) + out = source.as_table() + for name in ("plain", "half", "listed", "dict_value", "wide_key"): + assert out.column(name).type == table.column(name).type + assert out.column(name).to_pylist() == table.column(name).to_pylist() + rows = [data.as_dict() for _, data in source.iter_data()] + assert rows[0]["wide_key"] == {1e-50: 1, 2e-50: 2} + assert rows[0]["dict_value"] == {"a": 0.5} + + def test_a_plain_arrow_declared_float32_value_is_still_narrowed(self) -> None: + """Known limitation: a plain value (not a key or element) is narrowed as before.""" + source = DictSource( + [{"id": 1, "h": 0.1}], + tag_columns=["id"], + tag_only_columns=True, + data_schema=pa.schema([("id", pa.int64()), ("h", pa.float32())]), + ) + assert source.as_table().column("h").to_pylist() == [float(np.float32(0.1))] From e271151f39079c9095b94dfbe4c32a513b76ea1c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:05:33 -0800 Subject: [PATCH 02/32] fix(semantic-types): validate narrow float keys at declarations Address the independent review of ITL-1591 while preserving operator output and cache replay. --- .zed/rules | 10 +- CLAUDE.md | 10 +- changelog.d/ITL-1591.md | 21 +- docs/dev/design_issues/ITL-1591-NFK1.md | 20 +- src/orcapod/core/datagrams/datagram.py | 26 +- src/orcapod/core/nodes/source_node.py | 18 +- src/orcapod/core/sources/csv_source.py | 5 + src/orcapod/core/sources/data_frame_source.py | 5 + src/orcapod/core/sources/derived_source.py | 1 + src/orcapod/core/sources/dict_source.py | 4 + src/orcapod/core/sources/polling_source.py | 4 + src/orcapod/core/sources/stream_builder.py | 6 +- .../core/streams/arrow_table_stream.py | 8 - src/orcapod/pipeline/graph.py | 11 + src/orcapod/pipeline/job.py | 16 +- src/orcapod/pipeline/serialization.py | 40 ++- .../semantic_types/narrow_float_keys.py | 166 +++++---- src/orcapod/semantic_types/nested_storage.py | 2 +- .../semantic_types/universal_converter.py | 5 + src/orcapod/utils/schema_utils.py | 5 + .../test_narrow_float_keys_refused.py | 317 ++++++++++++++++-- 21 files changed, 544 insertions(+), 156 deletions(-) diff --git a/.zed/rules b/.zed/rules index 696badf2e..03df2a16e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1423,10 +1423,12 @@ data. The rules: declared, Python-declared and Arrow-declared alike, at any depth, by a check of types that never reads a value. One rule, `semantic_types/narrow_float_keys.py`: the type converter applies it to every dict and set type it builds (sources' Python schemas, datagrams, - user-class fields, a function pod's inputs and outputs when the pod is defined), and - `SourceStreamBuilder.build`, `ArrowTableStream.__init__` and a datagram given an Arrow - table apply it to the table's schema; never check it elsewhere. A dict is the converter's - one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an + user-class fields, a function pod's inputs and outputs when the pod is defined). + `SourceStreamBuilder.build` checks schemas at source ingestion, and explicit Arrow + declarations are checked before conversion or on restore. A raw `ArrowTableStream` and + Arrow-held datagrams carry already-built schemas, including operator and cached results. + A list of structs produced by aggregation can have the same Arrow shape as a dict. + A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an Arrow map; a set is the native set container, live or in its storage form. `float32` and `float16` stay valid as a plain column, a list element, a struct field and a dict value; the silent narrowing of such plain values from an Arrow declaration is ITL-1613. diff --git a/CLAUDE.md b/CLAUDE.md index 4716405f3..8a2eb7844 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1471,10 +1471,12 @@ data. The rules: declared, Python-declared and Arrow-declared alike, at any depth, by a check of types that never reads a value. One rule, `semantic_types/narrow_float_keys.py`: the type converter applies it to every dict and set type it builds (sources' Python schemas, datagrams, - user-class fields, a function pod's inputs and outputs when the pod is defined), and - `SourceStreamBuilder.build`, `ArrowTableStream.__init__` and a datagram given an Arrow - table apply it to the table's schema; never check it elsewhere. A dict is the converter's - one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an + user-class fields, a function pod's inputs and outputs when the pod is defined). + `SourceStreamBuilder.build` checks schemas at source ingestion, and explicit Arrow + declarations are checked before conversion or on restore. A raw `ArrowTableStream` and + Arrow-held datagrams carry already-built schemas, including operator and cached results. + A list of structs produced by aggregation can have the same Arrow shape as a dict. + A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an Arrow map; a set is the native set container, live or in its storage form. `float32` and `float16` stay valid as a plain column, a list element, a struct field and a dict value; the silent narrowing of such plain values from an Arrow declaration is ITL-1613. diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index dc2645c42..8809af167 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -7,8 +7,8 @@ depth (a dict in a list, a dict as a dict value, a dict in a tuple or a user-class field, an Arrow `map`), now raises `NarrowFloatKeyError` (an `InputValidationError`) naming the column and the key or element type, where the type is declared: a source's Python or - Arrow schema, the table given to a source or to an `ArrowTableStream`, a datagram's - schema or table, and a function pod's parameters and outputs when the pod is defined + Arrow schema, a datagram's Python schema or explicitly typed new column, and a function + pod's parameters and outputs when the pod is defined (`-> dict[np.float32, int]`, `set[np.float32]`). The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. `float32` and `float16` are still accepted as a plain @@ -19,6 +19,17 @@ - A plain value (not a dict key or set element) stored into a column that an Arrow schema declares `float32` or `float16` is still narrowed without a warning: `0.1` under `pa.float16()` is stored as `0.0999755859375` (ITL-1613). -- A struct column whose fields are exactly `key` and `value` has the stored shape of a dict - once `Batch`, `GroupBy` or `MergeJoin` collects it into a list. With a `float32` or - `float16` field `key`, that result is refused as a dict keyed by a narrow float. +- A raw `ArrowTableStream` still accepts an already-built Arrow table with the dict + shape. Updating an Arrow-held datagram can still narrow two keys to one. For example, + + ```python + import pyarrow as pa + from orcapod.core.datagrams import Data + from orcapod.core.streams import ArrowTableStream + + key_type = pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())])) + table = pa.table({"id": [1], "k": pa.array([[]], type=key_type)}) + ArrowTableStream(table, tag_columns=["id"]) + row = Data(table).update(k={1e-50: 1, 2e-50: 2}) + assert row.as_dict()["k"] == {0.0: 2} + ``` diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index c8f86996b..0ae9d937a 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -19,13 +19,15 @@ or annotation and in an Arrow schema or table alike, at any nesting depth, by a types that reads no value. One rule, `semantic_types/narrow_float_keys.py` (`NarrowFloatKeyError`, an `InputValidationError`): the type converter applies it to every dict and set type it builds (so a source's Python schema, a datagram's, a user-class field -and a function pod's declared inputs and outputs, when the pod is defined), and the source -builder, `ArrowTableStream` and a datagram given an Arrow table apply it to the table's -schema. A dict is the converter's one dict shape (`nested_storage.dict_entry_fields`, now -used by the converter's two readers too) or an Arrow map. `float32` and `float16` stay -accepted as a plain column, a list element, a struct field and a dict value. +and a function pod's declared inputs and outputs, when the pod is defined). The source +builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before +source value conversion, when a datagram adds a column with a declared type, and when a +saved source declaration is restored. A dict declaration uses the converter's dict shape +(`nested_storage.dict_entry_fields`) or an Arrow map. Plain narrow-float columns, list +elements, struct fields and dict values remain accepted. -Left as it is: a plain value in an Arrow-declared `float32` or `float16` column is still -narrowed silently (ITL-1613). A struct column whose fields are exactly `key` and `value` -becomes the dict shape once `Batch`, `GroupBy` or `MergeJoin` puts it in a list, and is -refused there when its `key` is `float32` or `float16`. +Open points: an Arrow-held datagram can still narrow two keys to one when updated with +Python floats. A raw `ArrowTableStream` still accepts the same Arrow type. Both APIs also +carry already-built operator results, including a list of structs whose fields happen to +be named `key` and `value`. Such a result has the same Arrow shape as a dict. An +Arrow-declared plain value can still narrow silently (ITL-1613). diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 6151af0be..6906b7ad6 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -41,10 +41,10 @@ NarrowFloatKeyError, require_schema_without_narrow_float_keys, ) -from orcapod.semantic_types.nested_none import with_context from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils +from orcapod.utils.schema_utils import declared_arrow_schema logger = logging.getLogger(__name__) @@ -226,9 +226,9 @@ def _refuse_narrow_float_keys(self, python_schema: SchemaLike) -> None: """ for name, python_type in python_schema.items(): try: - self.converter.python_type_to_arrow_type(python_type) - except NarrowFloatKeyError as exc: - raise with_context(f"Column {name!r} ({python_type})", exc) from exc + declared_arrow_schema({name: python_type}, self.converter) + except NarrowFloatKeyError: + raise except Exception: # noqa: BLE001 - reported by the conversion, as before continue @@ -267,11 +267,6 @@ def _init_from_table( ) table = arrow_utils.normalize_table_to_large_types(table) - # A dict keyed by, or a set of, float32 or float16 is refused where its type - # is declared, here by the table (ITL-1591): an update would narrow two - # distinct floats to one stored value and lose an entry. - require_schema_without_narrow_float_keys(table.schema) - # Extract context from table if not provided externally if constants.CONTEXT_KEY in table.column_names and data_context is None: data_context = table[constants.CONTEXT_KEY].to_pylist()[0] @@ -1127,10 +1122,12 @@ def _new_columns_table( ) ) if arrow_fields: + arrow_schema = pa.schema(list(arrow_fields.values())) + require_schema_without_narrow_float_keys(arrow_schema) tables.append( self.converter.python_dicts_to_arrow_table( [{n: updates[n] for n in arrow_fields}], - arrow_schema=pa.schema(list(arrow_fields.values())), + arrow_schema=arrow_schema, ) ) return arrow_utils.hstack_tables(*tables).select(list(updates)) @@ -1183,6 +1180,15 @@ def with_columns( f"Use update() to modify existing columns." ) + if column_types: + self._refuse_narrow_float_keys( + { + name: declared + for name, declared in column_types.items() + if name in updates + and not isinstance(declared, (pa.DataType, pa.Field)) + } + ) has_arrow_types = column_types is not None and any( isinstance(t, (pa.DataType, pa.Field)) for t in column_types.values() ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5b69d510d..c5465bbe6 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -21,6 +21,10 @@ import pyarrow as pa from orcapod import contexts +from orcapod.semantic_types.narrow_float_keys import ( + NarrowFloatKeyError, + require_schema_without_narrow_float_keys, +) from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase @@ -402,6 +406,8 @@ def _columns_without_arrow_type( seen.add(name) try: declared_arrow_schema({name: python_type}, converter) + except NarrowFloatKeyError: + raise except (ValueError, TypeError): missing.append((name, python_type)) return missing @@ -558,6 +564,8 @@ def __init__( raise ValueError( "arrow_schemas is given by tag_schema and data_schema already" ) + require_schema_without_narrow_float_keys(tag_schema) + require_schema_without_narrow_float_keys(data_schema) converter = self.data_context.type_converter # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). @@ -600,6 +608,7 @@ def _keep_saved( content_hash: str | None, saved_types: Mapping[str, Mapping[str, str]], nullable: Mapping[str, Collection[str]], + inherited_types: bool, ) -> None: """Keep what a saved job recorded for this slot (ITL-1138, ITL-640). @@ -617,6 +626,7 @@ def _keep_saved( content_hash: The saved content hash text, or ``None`` if not saved. saved_types: The saved type texts, ``{"tag": {...}, "data": {...}}``. nullable: The saved nullable column names per role. + inherited_types: The saved types came from an upstream result. """ if pipeline_hash is not None: self._saved_pipeline_hash = ContentHash.from_string(pipeline_hash) @@ -627,6 +637,7 @@ def _keep_saved( # types are both derived from them by ``_resolve``, together. self._given_arrow_schemas = None self._saved_arrow_texts = { + "inherited_types": inherited_types, "tag": dict(saved_types.get("tag", {})), "data": dict(saved_types.get("data", {})), "nullable": {role: list(names) for role, names in nullable.items()}, @@ -690,7 +701,12 @@ def _resolve(self) -> bool: arrow: list[pa.Schema] = [] for role in ("tag", "data"): names = texts["nullable"][role] - python[role] = deserialize_schema(texts[role], converter, nullable=names) + python[role] = deserialize_schema( + texts[role], + converter, + nullable=names, + inherited_types=texts["inherited_types"], + ) if any(isinstance(value, str) for value in python[role].values()): return False try: diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index e6d087c68..432ff258c 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -10,6 +10,9 @@ import pyarrow as pa from typing_extensions import override +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.source_ids import location_source_name @@ -309,6 +312,8 @@ def __init__( # Every later read (a check, ITL-1102) opens the file found now, whatever the # working directory is then. self._access_path = os.path.abspath(file_path) + if schema is not None: + require_schema_without_narrow_float_keys(schema) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._system_tag_columns: Collection[str] = system_tag_columns diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 54a563f88..5e62bd28f 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -7,6 +7,9 @@ import polars as pl import pyarrow as pa +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder @@ -65,6 +68,8 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) + if schema is not None: + require_schema_without_narrow_float_keys(schema) df = pl.DataFrame(data) # Convert any Object-dtype columns to Arrow-compatible types. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aeef4bfd5..ddcaeb152 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -623,6 +623,7 @@ def _derive_from( data_tags=self._data_tags(), source_name=self.source_name, kind_part=self.kind_part(), + inherited_types=True, record_id_columns=self._record_id_columns or (), ) return result.stream diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index d45d68a92..170ec0285 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -5,6 +5,9 @@ import pyarrow as pa +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder @@ -65,6 +68,7 @@ def __init__( # pa.Schema directly via data_schema; route to the converter accordingly. rows = [dict(row) for row in data] if isinstance(data_schema, pa.Schema): + require_schema_without_narrow_float_keys(data_schema) require_supported_nullable_types(data_schema) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..a79355aa5 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -22,6 +22,9 @@ import pyarrow as pa from typing_extensions import override +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import hash_source_name from orcapod.logical_types.canonical_form import declaration_form_schema @@ -330,6 +333,7 @@ def __init__( self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): + require_schema_without_narrow_float_keys(unified_schema) require_supported_nullable_types(unified_schema) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 337c65421..6ea04f94b 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -470,6 +470,7 @@ def build( data_tags: Collection[str] = (), *, hash_in_key_order: bool = False, + inherited_types: bool = False, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -489,6 +490,8 @@ def build( which changes when rows are reordered unless ``hash_in_key_order`` is given; pass an explicit value when the source id must survive reordering. + inherited_types: The table retains already-built upstream types, as + when a derived source copies a tag into data. record_id_columns: The key columns whose values identify a row, in key order: the row identifier is their canonical JSON (``key_row_identifier``), which follows the row regardless of its @@ -564,7 +567,8 @@ def build( ) # Nor is a dict keyed by, or a set of, float32 or float16 (ITL-1591): refused # here first, as the stream refuses it, before any key column or hash. - require_schema_without_narrow_float_keys(table.schema) + if not inherited_types: + require_schema_without_narrow_float_keys(table.schema) # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index bce6d0ca1..df49eaff6 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -20,9 +20,6 @@ from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.utils import arrow_utils, schema_utils logger = logging.getLogger(__name__) @@ -105,11 +102,6 @@ def __init__( found, tag_columns, data_tags, system_tag_columns ) - # Nor is a dict keyed by, or a set of, float32 or float16 (developer, November - # 28, 2026, ITL-1591): two distinct floats can narrow to one stored value, so - # an entry would be lost. A check of types, as the two above. - require_schema_without_narrow_float_keys(table.schema) - data_table, data_context_table = arrow_utils.split_by_column_groups( table, [constants.CONTEXT_KEY] ) diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 0b58b8f37..cd116f504 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -323,6 +323,13 @@ def load(cls, path: str | Path) -> "Pipeline": ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated). """ + return cls._load(path, inherited_source_slots=frozenset()) + + @classmethod + def _load( + cls, path: str | Path, *, inherited_source_slots: frozenset[str] + ) -> "Pipeline": + """Load a blueprint with the provenance of any sources bound in a job.""" import json as _json from orcapod.pipeline.serialization import ( FALL_THROUGH_TAGS_KEY, @@ -427,6 +434,7 @@ def load(cls, path: str | Path) -> "Pipeline": ) if not node_name: node_name = descriptor.get("label") or "unknown" + inherited_types = node_name in inherited_source_slots # Which columns may be null: recorded (``require_nullability_records``). saved_nullable: dict[str, list[str]] if "tag_schema" in source_config and "data_schema" in source_config: @@ -442,6 +450,7 @@ def load(cls, path: str | Path) -> "Pipeline": saved_tag, context.type_converter, nullable=saved_nullable["tag"], + inherited_types=inherited_types, ) ) data_schema = Schema( @@ -449,6 +458,7 @@ def load(cls, path: str | Path) -> "Pipeline": saved_data, context.type_converter, nullable=saved_nullable["data"], + inherited_types=inherited_types, ) ) saved_context = resolve_saved_context( @@ -483,6 +493,7 @@ def load(cls, path: str | Path) -> "Pipeline": content_hash=descriptor.get("content_hash"), saved_types={"tag": saved_tag, "data": saved_data}, nullable=saved_nullable, + inherited_types=inherited_types, ) # Restore label from descriptor if set explicitly stored_label = descriptor.get("label") diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..4fc611ef7 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1791,6 +1791,7 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, + source_config_has_inherited_types, ) path = _Path(path) @@ -1826,12 +1827,21 @@ def load( "must be given to PipelineJob.load. " + "; ".join(missing) + "." ) + saved_sources: dict[str, Any] = data.get("bindings", {}).get("sources", {}) + inherited_source_slots = frozenset( + name + for name, config in saved_sources.items() + if source_config_has_inherited_types(config) + ) + # Reconstruct pipeline from embedded blueprint data with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as tmp: tmp_path = tmp.name _json.dump(data["pipeline"], tmp) try: - pipeline = Pipeline.load(tmp_path) + pipeline = Pipeline._load( # pyright: ignore[reportPrivateUsage] # job bindings identify inherited source types + tmp_path, inherited_source_slots=inherited_source_slots + ) except ValueError as exc: # The embedded pipeline was read from a temporary file: name the job file. message = str(exc) @@ -1848,9 +1858,7 @@ def load( if isinstance(node, SourceNodeBase) } sources: dict[str, cp.StreamProtocol] = {} - for spec_name, src_config in ( - data.get("bindings", {}).get("sources", {}).items() - ): + for spec_name, src_config in saved_sources.items(): # Every source states its plain tags (ITL-1019): a refusal is the file's # error, not a source that could not be rebuilt. try: diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 0f647fe96..d84698fc4 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -24,6 +24,11 @@ require_readable, ) +from orcapod.semantic_types.narrow_float_keys import ( + NarrowFloatKeyError, + require_schema_without_narrow_float_keys, +) + if TYPE_CHECKING: import pyarrow as pa @@ -690,9 +695,9 @@ def resolve_source_from_config( # All sources accept db_registry — always forward it. # Sources that don't embed database references simply ignore it. return cls.from_config(config, db_registry=db_registry) - except Warning: - # A warning turned into an error (a ProvisionalHashWarning under an error - # filter) propagates; it is not a source that could not be rebuilt (ITL-1331). + except (NarrowFloatKeyError, Warning): + # An invalid declaration and a warning turned into an error propagate + # instead of becoming a proxy for a source that could not be rebuilt. raise except Exception: if fallback_to_proxy: @@ -735,6 +740,17 @@ def saved_source_id(config: dict[str, Any]) -> str: return "unknown" +def source_config_has_inherited_types(config: object) -> bool: + """Whether a saved source config describes types inherited from an upstream.""" + if not isinstance(config, dict): + return False + fields = cast("dict[str, object]", config) + kind = fields.get("source_type") + if kind == "cached": + return source_config_has_inherited_types(fields.get("inner_source")) + return kind == "derived" + + def _source_proxy_from_config( config: dict[str, Any], node_descriptor: dict[str, Any] | None = None, @@ -810,16 +826,19 @@ def _source_proxy_from_config( expected_class_name = SOURCE_REGISTRY[source_type].__name__ # A config without the nullability record (written before ITL-1043) is lossy. + inherited_types = source_config_has_inherited_types(config) tag_schema = Schema( deserialize_schema( tag_schema_dict, nullable=None if saved_nullable is None else saved_nullable["tag"], + inherited_types=inherited_types, ) ) data_schema = Schema( deserialize_schema( data_schema_dict, nullable=None if saved_nullable is None else saved_nullable["data"], + inherited_types=inherited_types, ) ) @@ -1098,6 +1117,8 @@ def deserialize_schema( schema_dict: dict[str, str], type_converter: Any | None = None, nullable: Collection[str] | None = None, + *, + inherited_types: bool = False, ) -> dict[str, Any]: """Reconstruct a Python-type schema from Arrow type string values. @@ -1111,6 +1132,7 @@ def deserialize_schema( produced by `serialize_schema`. type_converter: Optional type converter for Arrow→Python conversion. When ``None``, the default data context's converter is used. + inherited_types: The saved types describe already-built upstream results. nullable: The columns saved as nullable (one group of ``serialize_nullability``); each becomes ``T | None``. ``None`` when the file records no nullability: every column is then restored as ``T``. @@ -1122,6 +1144,8 @@ def deserialize_schema( Raises: ValueError: If ``nullable`` names a column that is not in ``schema_dict``. """ + import pyarrow as pa + if type_converter is None: from orcapod.contexts import resolve_context @@ -1133,6 +1157,10 @@ def deserialize_schema( for name, type_str in schema_dict.items(): try: arrow_type = parse_arrow_type_string(type_str, type_converter) + if not inherited_types: + require_schema_without_narrow_float_keys( + pa.schema([(name, arrow_type)]) + ) result[name] = _python_type_of_saved_column( name, arrow_type, @@ -1141,7 +1169,7 @@ def deserialize_schema( ) except LogicalTypeIdentifierError as exc: raise exc.for_column(name) from exc - except (SavedSchemaVersionError, Warning): + except (NarrowFloatKeyError, SavedSchemaVersionError, Warning): # A warning turned into an error (a provisional library value type under an # error filter) propagates (ITL-1331). raise @@ -1534,7 +1562,9 @@ def deserialize_arrow_schema( "restored." ) from exc fields.append(pa.field(name, arrow_type, nullable=name in nullable)) - return pa.schema(fields) + schema = pa.schema(fields) + require_schema_without_narrow_float_keys(schema) + return schema def parse_arrow_type_string(type_str: str, type_converter: Any | None = None) -> Any: diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 9f7cded39..40cd0aeed 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -22,8 +22,7 @@ accepted, and so is a ``float64`` key or element. The rule is here once. The type converter applies it to every dict and set type it -builds from a Python declaration (``require_no_narrow_float_keys``); the source builder, -``ArrowTableStream`` and a datagram over an Arrow table apply it to an Arrow schema +builds from a Python declaration (``require_no_narrow_float_keys``); source ingestion and explicit Arrow declarations apply it to an Arrow schema (``require_schema_without_narrow_float_keys``). """ @@ -31,7 +30,8 @@ import json from collections.abc import Mapping -from typing import TYPE_CHECKING +from types import UnionType +from typing import TYPE_CHECKING, Literal, Union, cast, get_args, get_origin from orcapod.errors import InputValidationError from orcapod.semantic_types.nested_storage import dict_entry_fields @@ -51,6 +51,7 @@ "string)." ) +_EXTENSION_NAME_KEY = b"ARROW:extension:name" _EXTENSION_METADATA_KEY = b"ARROW:extension:metadata" @@ -58,6 +59,26 @@ class NarrowFloatKeyError(InputValidationError, ValueError): """A declared type has a ``float32`` or ``float16`` dict key or set element.""" +def require_supported_python_float_key(annotation: object, *, is_set: bool) -> None: + """Report an unsupported NumPy half float in a key or set element declaration.""" + import numpy as np + + origin = get_origin(annotation) + args = get_args(annotation) + if origin in (Union, UnionType): + non_none = [arg for arg in args if arg is not type(None)] + if len(non_none) == 1: + require_supported_python_float_key(non_none[0], is_set=is_set) + if annotation is np.float16 or ( + origin is Literal + and {type(value) for value in args if value is not None} == {np.float16} + ): + part = "set element" if is_set else "dict key" + raise NarrowFloatKeyError( + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {part} type {annotation}. {_REMEDY}" + ) + + def _is_narrow_float(arrow_type: pa.DataType) -> bool: import pyarrow as pa @@ -66,23 +87,35 @@ def _is_narrow_float(arrow_type: pa.DataType) -> bool: return pa.types.is_float32(arrow_type) or pa.types.is_float16(arrow_type) -def _is_set_metadata(raw: bytes | None) -> bool: - """Whether extension metadata ``raw`` is that of a native set container.""" - from orcapod.logical_types.list_logical_type_factory import SET_CATEGORY +def _native_container_metadata( + name: bytes | None, raw: bytes | None +) -> dict[str, object]: + """Read metadata only when the extension identifier names a native container.""" + if not name or not raw: + return {} + + from orcapod.logical_types.list_logical_type_factory import ( + LIST_CATEGORY, + SET_CATEGORY, + ) - if not raw: - return False try: - metadata = json.loads(raw) + metadata: object = json.loads(raw) except ValueError: - return False - return isinstance(metadata, dict) and metadata.get("category") == SET_CATEGORY - - -def _dict_key( - arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None -) -> str | None: - """Say so when ``arrow_type`` stores a dict whose key is a narrow float.""" + return {} + if not isinstance(metadata, dict): + return {} + fields = cast("dict[str, object]", metadata) + category = fields.get("category") + if category not in (LIST_CATEGORY, SET_CATEGORY): + return {} + if not name.startswith(f"{category}[".encode()) or not name.endswith(b"]"): + return {} + return fields + + +def _dict_key(arrow_type: pa.DataType) -> str | None: + """Describe a narrow float key in a plain dict's storage type.""" import pyarrow as pa if pa.types.is_map(arrow_type): @@ -94,36 +127,6 @@ def _dict_key( return f"dict key type {key_type}" if _is_narrow_float(key_type) else None -def _set_element( - arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None -) -> str | None: - """Say so when ``arrow_type`` stores a set whose element is a narrow float.""" - import pyarrow as pa - - if isinstance(arrow_type, pa.ExtensionType): - raw = arrow_type.__arrow_ext_serialize__() - storage = arrow_type.storage_type - else: - raw = (field_metadata or {}).get(_EXTENSION_METADATA_KEY) - storage = arrow_type - if not _is_set_metadata(raw): - return None - if not (pa.types.is_list(storage) or pa.types.is_large_list(storage)): - return None - element_type = storage.value_type - if _is_narrow_float(element_type): - return f"set element type {element_type}" - return None - - -_REFUSED_PARTS = (_dict_key, _set_element) -"""The parts of a declared type that may not be a narrow float. - -Each takes one Arrow type with the metadata of the field that holds it, at any depth of -a declared type, and returns the description of what it refuses there, or ``None``. -""" - - def narrow_float_keys( arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None = None ) -> list[str]: @@ -142,32 +145,47 @@ def narrow_float_keys( """ import pyarrow as pa - found = { - description - for part in _REFUSED_PARTS - if (description := part(arrow_type, field_metadata)) is not None - } - children: list[tuple[pa.DataType, Mapping[bytes, bytes] | None]] + metadata = field_metadata or {} if isinstance(arrow_type, pa.BaseExtensionType): - children = [(arrow_type.storage_type, None)] - elif ( - pa.types.is_list(arrow_type) - or pa.types.is_large_list(arrow_type) - or pa.types.is_fixed_size_list(arrow_type) - ): + if isinstance(arrow_type, pa.ExtensionType): + metadata = { + _EXTENSION_NAME_KEY: arrow_type.extension_name.encode(), + _EXTENSION_METADATA_KEY: arrow_type.__arrow_ext_serialize__(), + } + else: + metadata = {} + arrow_type = arrow_type.storage_type + + native = _native_container_metadata( + metadata.get(_EXTENSION_NAME_KEY), metadata.get(_EXTENSION_METADATA_KEY) + ) + if native and (pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type)): + from orcapod.logical_types.list_logical_type_factory import SET_CATEGORY + item = arrow_type.value_field - children = [(item.type, item.metadata)] - elif pa.types.is_struct(arrow_type): - children = [(child.type, child.metadata) for child in arrow_type] - elif pa.types.is_map(arrow_type): - children = [ - (arrow_type.key_field.type, arrow_type.key_field.metadata), - (arrow_type.item_field.type, arrow_type.item_field.metadata), - ] - else: - children = [] - for child_type, child_metadata in children: - found.update(narrow_float_keys(child_type, child_metadata)) + found: set[str] = set() + if native["category"] == SET_CATEGORY and _is_narrow_float(item.type): + found.add(f"set element type {item.type}") + element_name = native.get("element_ext_name") + element_raw = native.get("element_ext_metadata") + item_metadata = dict(item.metadata or {}) + if isinstance(element_name, str): + item_metadata[_EXTENSION_NAME_KEY] = element_name.encode() + item_metadata[_EXTENSION_METADATA_KEY] = ( + element_raw.encode() if isinstance(element_raw, str) else b"" + ) + found.update(narrow_float_keys(item.type, item_metadata)) + return sorted(found) + + if pa.types.is_dictionary(arrow_type): + return narrow_float_keys(arrow_type.value_type) + + found: set[str] = set() + if (description := _dict_key(arrow_type)) is not None: + found.add(description) + for index in range(arrow_type.num_fields): + child = arrow_type.field(index) + found.update(narrow_float_keys(child.type, child.metadata)) return sorted(found) @@ -193,9 +211,9 @@ def require_no_narrow_float_keys(arrow_type: pa.DataType) -> None: def require_schema_without_narrow_float_keys(arrow_schema: pa.Schema) -> None: """Refuse an Arrow schema with a ``float32`` or ``float16`` dict key or set element. - Applied to the table a source is built from, to the table of every stream and to - the table a datagram is given, so a type declared in Arrow is refused as one - declared in Python is. No value is read. + Applied to a source's Arrow declaration and to explicitly declared mutations. + Operator results and their caches can have the same Arrow shape as a dict, + so their already-built schemas do not go through this check. No value is read. Args: arrow_schema: The Arrow schema of the table. diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 3a55cee18..43e73cde9 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -76,7 +76,7 @@ def dict_entry_fields( ): return None element_type = arrow_type.value_type - if not pa.types.is_struct(element_type): + if not pa.types.is_struct(element_type) or element_type.num_fields != 2: return None if {field.name for field in element_type} != {"key", "value"}: return None diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index cc4ff6996..270c14cfe 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.narrow_float_keys import ( NarrowFloatKeyError, require_no_narrow_float_keys, + require_supported_python_float_key, ) from orcapod.semantic_types.nested_storage import ( dict_entry_fields, @@ -489,6 +490,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])." ) + require_supported_python_float_key(args[0], is_set=True) 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( @@ -514,6 +516,7 @@ 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])." ) + require_supported_python_float_key(args[0], is_set=False) key_arrow = self.register_python_class(args[0]) val_arrow = self.register_python_class(args[1]) require_storable_in_struct_field(key_arrow) @@ -1574,6 +1577,7 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: raise ValueError( f"dict type must have exactly two type arguments, got: {args}" ) + require_supported_python_float_key(args[0], is_set=False) key_type = self.python_type_to_arrow_type(args[0]) value_type = self.python_type_to_arrow_type(args[1]) require_storable_in_struct_field(key_type) @@ -1624,6 +1628,7 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: raise ValueError( f"set type must have exactly one type argument, got: {args}" ) + require_supported_python_float_key(args[0], is_set=True) element_type = self.python_type_to_arrow_type(args[0]) require_restorable_none( args[0], element_type, self._is_user_class_extension diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 0ca064757..bd00d00d7 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -10,6 +10,7 @@ import pyarrow as pa from orcapod.errors import InputValidationError +from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError from orcapod.types import ContentHash, Schema, SchemaLike from orcapod.utils.output_containers import EXCLUDED_OUTPUT_CONTAINERS @@ -618,6 +619,8 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register """ try: return converter.python_schema_to_arrow_schema(schema) + except NarrowFloatKeyError: + raise except (TypeError, ValueError): pass optional = getattr(schema, "optional_fields", frozenset()) @@ -628,6 +631,8 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register ) try: converted = converter.python_schema_to_arrow_schema(single) + except NarrowFloatKeyError: + raise except (TypeError, ValueError): converter.ensure_types_registered_for_schemas(single) converted = converter.python_schema_to_arrow_schema(single) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index e6e5ea6ba..fe86b0999 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -17,6 +17,7 @@ from __future__ import annotations import dataclasses +import json from collections.abc import Callable from pathlib import Path from typing import Any, cast @@ -35,7 +36,6 @@ DictSource, ListSource, ) -from orcapod.core.streams import ArrowTableStream from orcapod.errors import InputValidationError from orcapod.semantic_types.narrow_float_keys import ( NARROW_FLOAT_KEYS_NOT_SUPPORTED, @@ -508,39 +508,11 @@ def test_an_arrow_table_source_refuses_it_in_every_role_and_tag_order( assert str(raised.value).startswith(NOT_SUPPORTED) assert "'k'" in str(raised.value) - @pytest.mark.parametrize(("build", "part"), ARROW_CASES) - def test_a_raw_stream_refuses_it( - self, build: Callable[[pa.DataType], pa.DataType], part: pa.DataType - ) -> None: - table = _table(build(part)) - for layout in (table, table.select(["k", "y", "g", "x", "id"])): - for tags in (["id", "g"], ["g", "id"]): - with pytest.raises(NarrowFloatKeyError) as raised: - ArrowTableStream(layout, tag_columns=tags) - assert str(raised.value).startswith(NOT_SUPPORTED) - - @pytest.mark.parametrize(("build", "part"), ARROW_CASES) - @pytest.mark.parametrize("kind", [Datagram, Tag, Data]) - def test_a_datagram_over_a_table_refuses_it( - self, - kind: type[Datagram], - build: Callable[[pa.DataType], pa.DataType], - part: pa.DataType, - ) -> None: - with pytest.raises(NarrowFloatKeyError) as raised: - kind(_table(build(part))) - assert "'k'" in str(raised.value) - - def test_a_record_batch_is_refused_like_a_table(self) -> None: - batch = _table(_dict_of(pa.float32())).to_batches()[0] - with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - Datagram(batch) - def test_no_value_is_read(self) -> None: """A table with no rows is refused the same way: the types decide.""" empty = _table(_dict_of(pa.float32())).slice(0, 0) with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - ArrowTableStream(empty, tag_columns=["id", "g"]) + ArrowTableSource(empty, tag_columns=["id", "g"]) def test_a_data_frame_source_refuses_it(self) -> None: schema = pa.schema( @@ -618,3 +590,288 @@ def test_a_plain_arrow_declared_float32_value_is_still_narrowed(self) -> None: data_schema=pa.schema([("id", pa.int64()), ("h", pa.float32())]), ) assert source.as_table().column("h").to_pylist() == [float(np.float32(0.1))] + + +@pytest.mark.parametrize("cls", [Datagram, Tag, Data]) +@pytest.mark.parametrize("declaration", ["python", "type", "field"]) +def test_datagram_with_columns_refuses_declared_narrow_dict_key(cls, declaration): + arrow_type = _dict_of(pa.float32()) + declared = { + "python": dict[np.float32, int], + "type": arrow_type, + "field": pa.field("k", arrow_type), + }[declaration] + with pytest.raises(NarrowFloatKeyError, match="column 'k'|Column 'k'"): + cls({"id": 1}).with_columns({"k": declared}, k={1e-50: 1, 2e-50: 2}) + + +@pytest.mark.parametrize("arrow_type", NARROW) +@pytest.mark.parametrize("stored", [False, True]) +@pytest.mark.parametrize("outer_set", [False, True]) +def test_native_nested_set_refuses_narrow_element( + arrow_type: pa.DataType, stored: bool, outer_set: bool +) -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + from orcapod.logical_types.list_logical_type_factory import ( + ArrowElement, + ListLogicalType, + ) + + inner = ListLogicalType(ArrowElement(float, arrow_type), is_set=True) + outer = ListLogicalType(inner, is_set=outer_set).get_arrow_extension_type() + storage = pa.array([[]], type=outer.storage_type) + live = pa.ExtensionArray.from_storage(outer, storage) + table = pa.table({"id": [1], "k": live}) + if stored: + table = pa.Table.from_arrays( + [table["id"], storage], schema=storage_form_schema(table.schema) + ) + with pytest.raises(NarrowFloatKeyError, match="set element type"): + ArrowTableSource(table, tag_columns="id", source_id="nested-set") + + +@pytest.mark.parametrize("operator", ["batch", "group_by", "merge_join"]) +def test_struct_aggregation_keeps_narrow_float_as_data(operator: str) -> None: + from orcapod.core.operators import Batch, GroupBy, MergeJoin + + pair = {"key": 0.5, "value": 1} + pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) + table = pa.table({"id": [1], "pair": pa.array([pair], type=pair_type)}) + source = ArrowTableSource( + table, tag_columns="id", tag_only_columns=True, source_id="pair" + ) + if operator == "batch": + result = Batch().static_process(source) + elif operator == "group_by": + result = GroupBy("id").static_process(source) + else: + result = MergeJoin().static_process(source, source) + assert result.as_table()["pair"].to_pylist() == [ + [pair, pair] if operator == "merge_join" else [pair] + ] + assert next(result.iter_data())[1].as_table()["pair"].to_pylist() == ( + result.as_table()["pair"].to_pylist() + ) + + +def test_struct_aggregation_replays_from_delta(tmp_path: Path) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.operators import Batch + from orcapod.core.sources.derived_source import DerivedSource + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import PipelineJob + from orcapod.types import CacheMode + + pair = {"key": 0.5, "value": 1} + pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) + table = pa.table({"id": [1], "pair": pa.array([pair], type=pair_type)}) + source = ArrowTableSource( + table, tag_columns="id", tag_only_columns=True, source_id="pairs" + ) + writer = OperatorJobNode( + operator=Batch(), + input_streams=(source,), + pipeline_database=DeltaTableDatabase(tmp_path), + cache_mode=CacheMode.LOG, + ) + writer.run() + replay = OperatorJobNode( + operator=Batch(), + input_streams=(source,), + pipeline_database=DeltaTableDatabase(tmp_path), + cache_mode=CacheMode.REPLAY, + ) + replay.run() + + rows = replay.as_table() + assert rows["pair"].type == pa.large_list(pair_type) + assert rows["pair"].to_pylist() == [[pair]] + assert next(replay.iter_data())[1].as_dict()["pair"] == {0.5: 1} + derived = DerivedSource(replay, tags_as_data={"id": "copied_id"}, source_id="copy") + assert derived.as_table()["pair"].to_pylist() == [[pair]] + + job = PipelineJob(database=DeltaTableDatabase(tmp_path / "job")) + with job: + derived.batch(label="batch") + path = tmp_path / "job.json" + job.save(path) + assert PipelineJob.load(path).nodes["copy"].arrow_schemas[1].field("pair").type == ( + rows["pair"].type + ) + + +@pytest.mark.parametrize( + "schema", + [ + pa.schema([("id", pa.int64()), ("k", _dict_of(pa.float32()))]), + {"id": int, "k": set[np.float16]}, + ], +) +def test_polling_source_refuses_declared_schema_without_fetch( + schema: pa.Schema | dict[str, Any], +) -> None: + from unittest.mock import Mock + + from orcapod.core.sources.polling_source import PollingSource + from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol + + impl = Mock(spec=DynamicSourceProtocol) + impl.schema.return_value = schema + with pytest.raises(NarrowFloatKeyError, match="column 'k'|Column 'k'"): + PollingSource(impl, "id", source_id="poll", record_id_columns="id") + impl.fetch.assert_not_called() + + +@pytest.mark.parametrize("reader", ["config", "node"]) +@pytest.mark.parametrize("type_text", ["dict", "set"]) +def test_saved_arrow_schema_refuses_narrow_keys(reader: str, type_text: str) -> None: + from orcapod.pipeline.serialization import ( + arrow_type_texts, + deserialize_arrow_schema, + deserialize_schema, + ) + + arrow_type = ( + _dict_of(pa.float32()) if type_text == "dict" else _live_set(pa.float16()) + ) + columns = arrow_type_texts(pa.schema([("k", arrow_type)]), _converter()) + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): + if reader == "config": + deserialize_arrow_schema({"columns": columns, "nullable": []}) + else: + deserialize_schema(columns, _converter(), []) + + +def test_saved_job_rejects_prohibited_source_declaration(tmp_path: Path) -> None: + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import PipelineJob + + table = _table(_dict_of(pa.float64())) + source = ArrowTableSource( + table, tag_columns="id", tag_only_columns=True, source_id="pairs" + ) + job = PipelineJob(database=DeltaTableDatabase(tmp_path / "store")) + with job: + source.batch(label="batch") + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + for node in saved["pipeline"]["nodes"].values(): + if node["node_type"] == "source": + node["source_config"]["data_schema"]["k"] = str(_dict_of(pa.float32())) + node["output_schema"]["data"]["k"] = str(_dict_of(pa.float32())) + path.write_text(json.dumps(saved)) + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): + PipelineJob.load(path) + + +@pytest.mark.parametrize("declared_in_arrow", [False, True]) +def test_pipeline_input_slot_refuses_declared_narrow_type( + declared_in_arrow: bool, +) -> None: + from orcapod.core.nodes.source_node import SourceNode + from orcapod.types import Schema + + with pytest.raises(NarrowFloatKeyError, match="column 'k'|Column 'k'"): + if declared_in_arrow: + SourceNode( + "inputs", pa.schema([]), pa.schema([("k", _dict_of(pa.float32()))]) + ) + else: + SourceNode("inputs", Schema({}), Schema({"k": dict[np.float32, int]})) + + +@pytest.mark.parametrize("cls", [Datagram, Tag, Data]) +@pytest.mark.parametrize("kind", ["dataclass", "structural", "pydantic"]) +def test_datagram_refuses_declared_user_class_field(cls, kind): + from orcapod import dataclass as structural_dataclass + from pydantic import ConfigDict, create_model + + annotation = dict[np.float32, int] + if kind == "pydantic": + model_config = ConfigDict(arbitrary_types_allowed=True) + model = create_model( + "NarrowKeyModel", __config__=model_config, bad=(annotation, ...) + ) + else: + model = type("NarrowKeyClass", (), {"__annotations__": {"bad": annotation}}) + model = ( + structural_dataclass(model) + if kind == "structural" + else dataclasses.dataclass(model) + ) + with pytest.raises(NarrowFloatKeyError, match=r"k.*bad|bad"): + cls({"k": model(bad={})}, python_schema={"k": model}) + + +@pytest.mark.parametrize("is_source", [False, True]) +def test_plain_list_with_unrelated_extension_metadata_is_allowed(is_source): + field = pa.field( + "k", + pa.large_list(pa.float32()), + metadata={b"ARROW:extension:metadata": b'{"category":"set"}'}, + ) + table = pa.Table.from_arrays( + [pa.array([1]), pa.array([[0.5]], type=field.type)], + schema=pa.schema([pa.field("id", pa.int64()), field]), + ) + result = ArrowTableSource(table, tag_columns="id") if is_source else Datagram(table) + assert result.as_table()["k"].to_pylist() == [[0.5]] + + +@pytest.mark.parametrize("container", ["union", "dictionary", "list_view", "run_end"]) +def test_declared_mutation_refuses_map_through_other_arrow_containers( + container: str, +) -> None: + inner = pa.map_(pa.float32(), pa.int64()) + if container == "union": + outer = pa.union([pa.field("map", inner)], mode="sparse") + elif container == "dictionary": + outer = pa.dictionary(pa.int8(), inner) # pyright: ignore[reportArgumentType] # Arrow accepts map values + elif container == "list_view": + outer = pa.large_list_view(inner) + else: + outer = pa.run_end_encoded(pa.int16(), inner) # pyright: ignore[reportArgumentType] # Arrow accepts map values + with pytest.raises(NarrowFloatKeyError, match="dict key type"): + Datagram({"id": 1}).with_columns({"k": outer}, k=[]) + + +@pytest.mark.parametrize("source", ["dict", "frame", "csv"]) +def test_narrow_key_diagnostic_precedes_source_value_conversion( + tmp_path: Path, source: str +) -> None: + from orcapod.core.sources.csv_source import CSVSource + + schema = pa.schema([("id", pa.int64()), ("k", _dict_of(pa.float32()))]) + with pytest.raises(NarrowFloatKeyError, match="float64"): + if source == "dict": + DictSource([{"id": 1, "k": "oops"}], "id", data_schema=schema) + elif source == "frame": + DataFrameSource({"id": [1], "k": ["oops"]}, "id", schema=schema) + else: + path = tmp_path / "narrow.csv" + path.write_text("id,k\n1,oops\n") + CSVSource(str(path), "id", schema=schema) + + +@pytest.mark.parametrize("annotation", [set[np.float16], dict[np.float16, int]]) +def test_pod_refuses_python_float16_key_or_element(annotation): + def run(k): + return len(k) + + run.__annotations__ = {"k": annotation, "return": int} + with pytest.raises(NarrowFloatKeyError, match="float64"): + function_pod(output_keys="n")(run) + + +def test_duplicate_key_struct_is_not_dict_shape() -> None: + pair = pa.struct( + [("key", pa.float32()), ("key", pa.int64()), ("value", pa.int64())] + ) + arrow_type = pa.large_list(pair) + assert dict_entry_fields(arrow_type) is None + table = pa.schema([("id", pa.int64()), ("k", arrow_type)]).empty_table() + with pytest.raises(ValueError, match=r"column 'k'|Column 'k'"): + ArrowTableSource(table, tag_columns="id") + with pytest.raises(ValueError, match=r"column 'k'|Column 'k'"): + DictSource([{"id": 1, "k": []}], "id", data_schema=table.schema) From a2e9a40a3f747ea226e90f4b434939e39bd77091 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:25:19 -0800 Subject: [PATCH 03/32] fix(semantic_types): validate declarations and preserve blueprint input types --- changelog.d/ITL-1591.md | 6 +- docs/dev/design_issues/ITL-1591-NFK1.md | 6 +- src/orcapod/core/datagrams/datagram.py | 50 ++---- src/orcapod/core/nodes/source_node.py | 27 +++- src/orcapod/core/sources/data_frame_source.py | 2 + src/orcapod/core/sources/polling_source.py | 2 + src/orcapod/pipeline/graph.py | 14 +- src/orcapod/pipeline/job.py | 16 +- src/orcapod/utils/schema_utils.py | 17 +++ .../test_narrow_float_keys_refused.py | 142 +++++++++++++++++- 10 files changed, 217 insertions(+), 65 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 8809af167..a08e18498 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -7,11 +7,11 @@ depth (a dict in a list, a dict as a dict value, a dict in a tuple or a user-class field, an Arrow `map`), now raises `NarrowFloatKeyError` (an `InputValidationError`) naming the column and the key or element type, where the type is declared: a source's Python or - Arrow schema, a datagram's Python schema or explicitly typed new column, and a function - pod's parameters and outputs when the pod is defined + Arrow schema, a pipeline's declared input slot, a datagram's Python schema or + explicitly typed new column, and a function pod's parameters and outputs when the pod is defined (`-> dict[np.float32, int]`, `set[np.float32]`). The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in - Arrow), or use another type. `float32` and `float16` are still accepted as a plain + Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain column, a list element, a struct field and a dict value. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 0ae9d937a..756cb91c9 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -22,7 +22,11 @@ dict and set type it builds (so a source's Python schema, a datagram's, a user-c and a function pod's declared inputs and outputs, when the pod is defined). The source builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before source value conversion, when a datagram adds a column with a declared type, and when a -saved source declaration is restored. A dict declaration uses the converter's dict shape +saved source declaration is restored. DataFrameSource and PollingSource check incoming Arrow +schemas before Polars can drop native set identity. Saved pipeline input slots record +whether their schemas came from a stream, so loading a blueprint can retain an operator +result's types. Public slot declarations check both the Python types and any Arrow override. +A dict declaration uses the converter's dict shape (`nested_storage.dict_entry_fields`) or an Arrow map. Plain narrow-float columns, list elements, struct fields and dict values remain accepted. diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 6906b7ad6..1ab3b19d9 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -38,13 +38,12 @@ 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.narrow_float_keys import ( - NarrowFloatKeyError, require_schema_without_narrow_float_keys, ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import declared_arrow_schema +from orcapod.utils.schema_utils import require_python_schema_without_narrow_float_keys logger = logging.getLogger(__name__) @@ -194,7 +193,9 @@ def _init_from_dict( else inferred ) if python_schema: - self._refuse_narrow_float_keys(python_schema) + require_python_schema_without_narrow_float_keys( + python_schema, self.converter + ) self._data_dict = self._canonical_dict_values( data_columns, self._data_python_schema ) @@ -209,29 +210,6 @@ def _init_from_dict( self._meta_table: pa.Table | None = None self._context_table: pa.Table | None = None - def _refuse_narrow_float_keys(self, python_schema: SchemaLike) -> None: - """Refuse a declared type with a ``float32`` or ``float16`` dict key or set element. - - The datagram converts its values to Arrow only when asked for a table; a type - with such a key or element is refused when it is declared, here (ITL-1591). - The rule is the type converter's, applied when it maps the declared type to - Arrow. Any other reason a declared type has no Arrow type is reported where it - is today, by the conversion. - - Args: - python_schema: The declared Python types, by column name. - - Raises: - NarrowFloatKeyError: Naming the column and its declared type. - """ - for name, python_type in python_schema.items(): - try: - declared_arrow_schema({name: python_type}, self.converter) - except NarrowFloatKeyError: - raise - except Exception: # noqa: BLE001 - reported by the conversion, as before - continue - def _canonical_dict_values( self, columns: dict[str, DataValue], schema: Schema ) -> dict[str, DataValue]: @@ -1093,11 +1071,6 @@ def _new_columns_table( if name not in updates: continue if isinstance(declared, pa.Field): - if updates[name] is None and not declared.nullable: - raise ValueError( - f"Column {name!r} is declared non-nullable" - + f" ({declared}) but its value is None" - ) arrow_fields[name] = declared.with_name(name) elif isinstance(declared, pa.DataType): arrow_fields[name] = pa.field( @@ -1105,6 +1078,14 @@ def _new_columns_table( ) else: python_schema[name] = declared + arrow_schema = pa.schema(list(arrow_fields.values())) + require_schema_without_narrow_float_keys(arrow_schema) + for name, field in arrow_fields.items(): + if updates[name] is None and not field.nullable: + raise ValueError( + f"Column {name!r} is declared non-nullable" + f" ({column_types[name]}) but its value is None" + ) inferred_names = [n for n in updates if n not in column_types] if inferred_names: python_schema.update( @@ -1122,8 +1103,6 @@ def _new_columns_table( ) ) if arrow_fields: - arrow_schema = pa.schema(list(arrow_fields.values())) - require_schema_without_narrow_float_keys(arrow_schema) tables.append( self.converter.python_dicts_to_arrow_table( [{n: updates[n] for n in arrow_fields}], @@ -1181,13 +1160,14 @@ def with_columns( ) if column_types: - self._refuse_narrow_float_keys( + require_python_schema_without_narrow_float_keys( { name: declared for name, declared in column_types.items() if name in updates and not isinstance(declared, (pa.DataType, pa.Field)) - } + }, + self.converter, ) has_arrow_types = column_types is not None and any( isinstance(t, (pa.DataType, pa.Field)) for t in column_types.values() diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index c5465bbe6..cfd4bbee9 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -66,6 +66,7 @@ arrow_schema_identity, compute_source_schema_hash, declared_arrow_schema, + require_python_schema_without_narrow_float_keys, ) if TYPE_CHECKING: @@ -549,6 +550,8 @@ def __init__( label: str | None = None, config: OrcapodConfig | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, + *, + _inherited_types: 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): @@ -574,7 +577,16 @@ 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 arrow_schemas is not None and not _inherited_types: + for schema in arrow_schemas: + require_schema_without_narrow_float_keys(schema) + converter = self.data_context.type_converter + # A supplied Arrow mapping may cover Python types the converter does + # not know. Still check both roles for prohibited Python declarations. + require_python_schema_without_narrow_float_keys(tag_schema, converter) + require_python_schema_without_narrow_float_keys(data_schema, converter) self._name = name + self._inherited_types = _inherited_types self._tag_schema = tag_schema self._data_schema = data_schema # The Arrow types of the slot's columns, which its identity is built from @@ -632,12 +644,12 @@ def _keep_saved( self._saved_pipeline_hash = ContentHash.from_string(pipeline_hash) if content_hash is not None: self._saved_content_hash = ContentHash.from_string(content_hash) + self._inherited_types = inherited_types if self._given_arrow_schemas is None or self._pending_columns(): # One state: the texts hold the types, and the Arrow pair and the Python # types are both derived from them by ``_resolve``, together. self._given_arrow_schemas = None self._saved_arrow_texts = { - "inherited_types": inherited_types, "tag": dict(saved_types.get("tag", {})), "data": dict(saved_types.get("data", {})), "nullable": {role: list(names) for role, names in nullable.items()}, @@ -654,6 +666,7 @@ def _take_saved_state_of(self, other: "SourceNodeBase") -> None: name. """ self._saved_pipeline_hash = other._saved_pipeline_hash + self._inherited_types = other._inherited_types self._given_arrow_schemas = other._given_arrow_schemas if self._name == other._name: self._label = other._label @@ -705,7 +718,7 @@ def _resolve(self) -> bool: texts[role], converter, nullable=names, - inherited_types=texts["inherited_types"], + inherited_types=self._inherited_types, ) if any(isinstance(value, str) for value in python[role].values()): return False @@ -1587,6 +1600,7 @@ def from_stream( if isinstance(stream, SourceNodeBase) else typed_arrow_schemas(stream) ), + _inherited_types=True, ) if isinstance(stream, SourceNodeBase): # A loaded job's slot keeps all its saved state (ITL-1138, ITL-640), @@ -1638,6 +1652,8 @@ def __init__( bound_source: StreamProtocol | None = None, data_context: str | contexts.DataContext | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, + *, + _inherited_types: bool = False, ) -> None: if tag_schema is None or data_schema is None: if bound_source is None: @@ -1665,12 +1681,14 @@ def __init__( tag_schema = derived_tag if data_schema is None: data_schema = derived_data + _inherited_types = True super().__init__( name=name, tag_schema=tag_schema, data_schema=data_schema, data_context=data_context, arrow_schemas=arrow_schemas, + _inherited_types=_inherited_types, ) self._bound_source: StreamProtocol | None = None self._declared_form: _DeclaredForm | None = None @@ -2197,6 +2215,7 @@ def from_stream( data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=stream.bound_source, + _inherited_types=True, ) node._take_saved_state_of(stream) return node @@ -2208,6 +2227,7 @@ def from_stream( data_schema=stream.data_schema, arrow_schemas=stream._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another bound_source=None, + _inherited_types=True, ) node._take_saved_state_of(stream) return node @@ -2236,6 +2256,7 @@ def from_stream( data_schema=data_schema, arrow_schemas=typed_arrow_schemas(stream), bound_source=stream, + _inherited_types=True, ) @classmethod @@ -2260,6 +2281,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 + _inherited_types=True, ) node._take_saved_state_of(slot) if bound_source is not None: @@ -2277,6 +2299,7 @@ def as_node(self) -> SourceNode: tag_schema=self._tag_schema, data_schema=self._data_schema, arrow_schemas=self._given_arrow_schemas, + _inherited_types=True, ) node._take_saved_state_of(self) return node diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 5e62bd28f..6878b9aad 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -70,6 +70,8 @@ def __init__( if schema is not None: require_schema_without_narrow_float_keys(schema) + if isinstance(data, (pa.Table, pa.RecordBatch)): + require_schema_without_narrow_float_keys(data.schema) df = pl.DataFrame(data) # Convert any Object-dtype columns to Arrow-compatible types. diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index a79355aa5..67ebf35e9 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -878,6 +878,8 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ + if isinstance(data, (pa.Table, pa.RecordBatch)): + require_schema_without_narrow_float_keys(data.schema) df = pl.DataFrame(data) if len(df.columns) == 0: logger.debug( diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index cd116f504..821e73162 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -248,6 +248,7 @@ def save(self, path: str | Path) -> None: "tag_schema": dict(saved["tag"]), "data_schema": dict(saved["data"]), "nullable": copy.deepcopy(saved["nullable"]), + "inherited_types": node._inherited_types, # pyright: ignore[reportPrivateUsage] # blueprint slot provenance } descriptor["reconstructable"] = True @@ -323,13 +324,6 @@ def load(cls, path: str | Path) -> "Pipeline": ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated). """ - return cls._load(path, inherited_source_slots=frozenset()) - - @classmethod - def _load( - cls, path: str | Path, *, inherited_source_slots: frozenset[str] - ) -> "Pipeline": - """Load a blueprint with the provenance of any sources bound in a job.""" import json as _json from orcapod.pipeline.serialization import ( FALL_THROUGH_TAGS_KEY, @@ -434,7 +428,10 @@ def _load( ) if not node_name: node_name = descriptor.get("label") or "unknown" - inherited_types = node_name in inherited_source_slots + # Old blueprints did not distinguish declarations from + # inherited schemas. Their saved Arrow types can describe an + # operator result, so preserve them as they were saved. + inherited_types = source_config.get("inherited_types", True) # Which columns may be null: recorded (``require_nullability_records``). saved_nullable: dict[str, list[str]] if "tag_schema" in source_config and "data_schema" in source_config: @@ -485,6 +482,7 @@ def _load( data_schema=data_schema, data_context=saved_context, arrow_schemas=arrow_schemas, + _inherited_types=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/pipeline/job.py b/src/orcapod/pipeline/job.py index 4fc611ef7..82f59257c 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1791,7 +1791,6 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, - source_config_has_inherited_types, ) path = _Path(path) @@ -1827,21 +1826,12 @@ def load( "must be given to PipelineJob.load. " + "; ".join(missing) + "." ) - saved_sources: dict[str, Any] = data.get("bindings", {}).get("sources", {}) - inherited_source_slots = frozenset( - name - for name, config in saved_sources.items() - if source_config_has_inherited_types(config) - ) - # Reconstruct pipeline from embedded blueprint data with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as tmp: tmp_path = tmp.name _json.dump(data["pipeline"], tmp) try: - pipeline = Pipeline._load( # pyright: ignore[reportPrivateUsage] # job bindings identify inherited source types - tmp_path, inherited_source_slots=inherited_source_slots - ) + pipeline = Pipeline.load(tmp_path) except ValueError as exc: # The embedded pipeline was read from a temporary file: name the job file. message = str(exc) @@ -1858,7 +1848,9 @@ def load( if isinstance(node, SourceNodeBase) } sources: dict[str, cp.StreamProtocol] = {} - for spec_name, src_config in saved_sources.items(): + for spec_name, src_config in ( + data.get("bindings", {}).get("sources", {}).items() + ): # Every source states its plain tags (ITL-1019): a refusal is the file's # error, not a source that could not be rebuilt. try: diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index bd00d00d7..734129071 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -640,6 +640,23 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register return pa.schema(fields) +def require_python_schema_without_narrow_float_keys( + schema: SchemaLike, converter: Any +) -> None: + """Check a Python declaration when its Arrow conversion is deferred or optional. + + Use the converter's narrow key and element check. Other conversion errors + belong to the path that requires the converter to produce an Arrow type. + """ + for name, python_type in schema.items(): + try: + declared_arrow_schema({name: python_type}, converter) + except NarrowFloatKeyError: + raise + except Exception: # noqa: BLE001 - conversion is optional here + continue + + def compute_schema_hash( tag_schema: "pa.Schema", data_schema: "pa.Schema", diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index fe86b0999..c1ef4fd62 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -743,16 +743,19 @@ def test_saved_arrow_schema_refuses_narrow_keys(reader: str, type_text: str) -> def test_saved_job_rejects_prohibited_source_declaration(tmp_path: Path) -> None: + from orcapod import SourceNode + from orcapod.core.operators import Batch from orcapod.databases import DeltaTableDatabase from orcapod.pipeline import PipelineJob - table = _table(_dict_of(pa.float64())) - source = ArrowTableSource( - table, tag_columns="id", tag_only_columns=True, source_id="pairs" + slot = SourceNode( + "pairs", + pa.schema([("id", pa.int64())]), + pa.schema([("k", _dict_of(pa.float64()))]), ) job = PipelineJob(database=DeltaTableDatabase(tmp_path / "store")) with job: - source.batch(label="batch") + Batch()(slot, label="batch") path = tmp_path / "job.json" job.save(path) saved = json.loads(path.read_text()) @@ -875,3 +878,134 @@ def test_duplicate_key_struct_is_not_dict_shape() -> None: ArrowTableSource(table, tag_columns="id") with pytest.raises(ValueError, match=r"column 'k'|Column 'k'"): DictSource([{"id": 1, "k": []}], "id", data_schema=table.schema) + + +@pytest.mark.parametrize( + "derived", [False, True], ids=["static-batch", "derived-source"] +) +@pytest.mark.parametrize( + "legacy", [False, True], ids=["current-blueprint", "legacy-blueprint"] +) +def test_standalone_blueprint_loads_inherited_batch_input( + tmp_path: Path, derived: bool, legacy: bool +) -> None: + from orcapod import SourceNode + from orcapod.core.operators import Batch + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import Pipeline, PipelineJob + + pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) + table = pa.table( + {"id": [1], "pair": pa.array([{"key": 0.5, "value": 1}], type=pair_type)} + ) + source = ArrowTableSource( + table, tag_columns="id", tag_only_columns=True, source_id="pairs" + ) + if derived: + job = PipelineJob( + name="parent", database=DeltaTableDatabase(tmp_path / "cache") + ) + with job: + source.batch(label="parent") + job.run() + stream = job.nodes["parent"].as_source( + tags_as_data={"id": "copied_id"}, source_id="derived_pairs" + ) + else: + stream = Batch().static_process(source) + + pipeline = Pipeline("child") + with pipeline: + Batch()(stream, label="child") + path = tmp_path / "blueprint.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + slot_config = next( + node["source_config"] + for node in saved["nodes"].values() + if node["node_type"] == "source" + ) + assert slot_config["inherited_types"] is True + if legacy: + del slot_config["inherited_types"] + path.write_text(json.dumps(saved)) + + restored = Pipeline.load(path) + slot = next(node for node in restored.nodes.values() if node.node_type == "source") + assert isinstance(slot, SourceNode) + assert slot.arrow_schemas[1].field("pair").type == pa.large_list(pair_type) + assert slot.pipeline_hash() == pipeline.nodes[slot.name].pipeline_hash() + restored.save(path) + assert len(Pipeline.load(path).nodes) == 2 + + +@pytest.mark.parametrize("width", NARROW) +@pytest.mark.parametrize("storage_form", [False, True], ids=["live", "storage"]) +@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) +def test_arrow_sources_refuse_narrow_set_before_polars( + width: pa.DataType, storage_form: bool, polling: bool +) -> None: + from unittest.mock import Mock + + from orcapod.core.sources.polling_source import PollingSource + from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol + from orcapod.types import Cursor + + extension = _live_set(width) + values = pa.array([[0.5]], type=extension.storage_type) + if storage_form: + schema = pa.schema( + [pa.field("id", pa.int64()), _set_storage_field(width).with_name("k")] + ) + table = pa.Table.from_arrays([pa.array([1]), values], schema=schema) + else: + table = pa.table( + {"id": [1], "k": pa.ExtensionArray.from_storage(extension, values)} + ) + + if polling: + impl = Mock(spec=DynamicSourceProtocol) + impl.schema.return_value = None + impl.fetch.return_value = (Cursor(value=1), table) + source = PollingSource(impl, "id", source_id="poll", record_id_columns="id") + with pytest.raises(NarrowFloatKeyError, match="column 'k'.*set element type"): + source.check_for_new_data() + else: + with pytest.raises(NarrowFloatKeyError, match="column 'k'.*set element type"): + DataFrameSource(table, tag_columns="id", source_id="dataframe") + + +@pytest.mark.parametrize( + "python_narrow,arrow_narrow", [(True, True), (True, False), (False, True)] +) +def test_source_node_validates_both_schema_declarations_with_arrow_override( + python_narrow: bool, arrow_narrow: bool +) -> None: + from orcapod import SourceNode + from orcapod.types import Schema + + with pytest.raises(NarrowFloatKeyError, match="[Cc]olumn 'k'"): + SourceNode( + "slot", + Schema({"id": int}), + Schema({"k": dict[np.float32, int] if python_narrow else dict[float, int]}), + arrow_schemas=( + pa.schema([("id", pa.int64())]), + pa.schema( + [("k", _dict_of(pa.float32() if arrow_narrow else pa.float64()))] + ), + ), + ) + + +@pytest.mark.parametrize("nonnullable", [False, True], ids=["mixed", "nonnullable"]) +def test_datagram_checks_narrow_arrow_declaration_before_values( + nonnullable: bool, +) -> None: + narrow = _dict_of(pa.float32()) + row = Data({"id": 1}) + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): + if nonnullable: + row.with_columns({"k": pa.field("k", narrow, nullable=False)}, k=None) + else: + row.with_columns({"m": int, "k": narrow}, m="invalid integer", k={}) From 3c01acd87e831bf94a7d38336111bea996a3acaf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:30:13 -0800 Subject: [PATCH 04/32] fix(semantic_types): validate remaining narrow float declarations --- changelog.d/ITL-1591.md | 4 +- docs/dev/design_issues/ITL-1591-NFK1.md | 9 +- src/orcapod/core/datagrams/datagram.py | 13 +- src/orcapod/core/nodes/source_node.py | 11 ++ src/orcapod/core/sources/data_frame_source.py | 4 +- src/orcapod/core/sources/polling_source.py | 6 +- .../semantic_types/narrow_float_keys.py | 10 +- .../semantic_types/universal_converter.py | 27 ++-- src/orcapod/utils/polars_data_utils.py | 45 ++++++- .../test_narrow_float_keys_refused.py | 124 ++++++++++++++++++ 10 files changed, 226 insertions(+), 27 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index a08e18498..aa926946e 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -9,7 +9,9 @@ column and the key or element type, where the type is declared: a source's Python or Arrow schema, a pipeline's declared input slot, a datagram's Python schema or explicitly typed new column, and a function pod's parameters and outputs when the pod is defined - (`-> dict[np.float32, int]`, `set[np.float32]`). The check reads types only, never a + (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and + Arrow column mappings given to Polars-backed sources and explicit Arrow schemas + given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain column, a list element, a struct field and a dict value. diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 756cb91c9..904f773da 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -22,10 +22,13 @@ dict and set type it builds (so a source's Python schema, a datagram's, a user-c and a function pod's declared inputs and outputs, when the pod is defined). The source builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before source value conversion, when a datagram adds a column with a declared type, and when a -saved source declaration is restored. DataFrameSource and PollingSource check incoming Arrow -schemas before Polars can drop native set identity. Saved pipeline input slots record +saved source declaration is restored. The converter checks explicit Arrow declarations +before converting Python rows, and checks Python set types even without a logical type +registry. DataFrameSource and PollingSource check incoming Arrow schemas and Arrow columns +before Polars can drop native set identity. Saved pipeline input slots record whether their schemas came from a stream, so loading a blueprint can retain an operator -result's types. Public slot declarations check both the Python types and any Arrow override. +result's types. Public slot declarations check any Arrow override and each explicitly +declared Python role, including when the other Python role comes from a bound stream. A dict declaration uses the converter's dict shape (`nested_storage.dict_entry_fields`) or an Arrow map. Plain narrow-float columns, list elements, struct fields and dict values remain accepted. diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 1ab3b19d9..fc340842e 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -1014,9 +1014,14 @@ def update(self, **updates: DataValue) -> Self: sub_schema = arrow_utils.schema_select( self._data_table.schema, list(updates.keys()) ) - update_table = self.converter.python_dicts_to_arrow_table( - [updates], arrow_schema=sub_schema + # This schema came from the held table. Only convert values for its + # existing fields, which can also represent operator-built types. + converter = self.converter + storage_rows = converter.python_dicts_to_struct_dicts( + [updates], + python_schema=converter.arrow_schema_to_python_schema(sub_schema), ) + update_table = pa.Table.from_pylist(storage_rows, schema=sub_schema) new_d = self.copy(include_cache=False) new_d._data_table = arrow_utils.hstack_tables( self._data_table.drop_columns(list(updates.keys())), update_table @@ -1178,10 +1183,10 @@ def with_columns( # Arrow type. Existing columns keep their Arrow fields (converted # from the Python schema if the table was not loaded); only the new # columns are typed (declared) or inferred (undeclared). + new_columns = self._new_columns_table(updates, column_types or {}) new_d = self.copy(include_cache=False) new_d._data_table = arrow_utils.hstack_tables( - self._ensure_data_table(), - self._new_columns_table(updates, column_types or {}), + self._ensure_data_table(), new_columns ) new_d._data_dict = None new_d._data_python_schema = None diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index cfd4bbee9..a51df3e99 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1677,6 +1677,17 @@ def __init__( if data_schema is None else declared_arrow_schema(data_schema, converter), ) + elif not _inherited_types: + # Both Arrow schemas were supplied by the caller. Only the Python + # roles that were supplied are declarations. + for schema in arrow_schemas: + require_schema_without_narrow_float_keys(schema) + converter = contexts.resolve_context(data_context).type_converter + for python_schema in (tag_schema, data_schema): + if python_schema is not None: + require_python_schema_without_narrow_float_keys( + python_schema, converter + ) if tag_schema is None: tag_schema = derived_tag if data_schema is None: diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6878b9aad..432f5bd01 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -70,9 +70,7 @@ def __init__( if schema is not None: require_schema_without_narrow_float_keys(schema) - if isinstance(data, (pa.Table, pa.RecordBatch)): - require_schema_without_narrow_float_keys(data.schema) - df = pl.DataFrame(data) + df = polars_data_utils.dataframe_from_source_input(data) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 67ebf35e9..cd9de947a 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -49,7 +49,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Cursor, PollingConfig, Schema -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( _normalize_column_list, @@ -878,9 +878,7 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - if isinstance(data, (pa.Table, pa.RecordBatch)): - require_schema_without_narrow_float_keys(data.schema) - df = pl.DataFrame(data) + df = polars_data_utils.dataframe_from_source_input(data) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 40cd0aeed..4304dd868 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -189,19 +189,25 @@ def narrow_float_keys( return sorted(found) -def require_no_narrow_float_keys(arrow_type: pa.DataType) -> None: +def require_no_narrow_float_keys( + arrow_type: pa.DataType, *, is_set_element: bool = False +) -> None: """Refuse a declared type with a ``float32`` or ``float16`` dict key or set element. Args: arrow_type: A declared Arrow type, or the Arrow type a declared Python type maps to. + is_set_element: Whether the type is itself declared as a set element. Raises: NarrowFloatKeyError: If ``arrow_type`` is, or contains at any depth, a dict keyed by, or a set of, ``float32`` or ``float16``. The message names the type and each such part, and the remedy. """ - if found := narrow_float_keys(arrow_type): + found = narrow_float_keys(arrow_type) + if is_set_element and _is_narrow_float(arrow_type): + found.insert(0, f"set element type {arrow_type}") + if found: raise NarrowFloatKeyError( f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: Arrow type {arrow_type} has " f"{', '.join(found)}. {_REMEDY}" diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 270c14cfe..3c01a1afe 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.narrow_float_keys import ( NarrowFloatKeyError, require_no_narrow_float_keys, + require_schema_without_narrow_float_keys, require_supported_python_float_key, ) from orcapod.semantic_types.nested_storage import ( @@ -57,6 +58,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.schema_utils import require_python_schema_without_narrow_float_keys if TYPE_CHECKING: from orcapod.logical_types.registry import LogicalTypeRegistry @@ -630,6 +632,8 @@ def _make_or_get_arrow_element_set_type( ListLogicalType, ) + # Check the declaration even when the set will be stored as a plain list. + require_no_narrow_float_keys(element_arrow_type, is_set_element=True) if self._logical_type_registry is None or isinstance( element_arrow_type, pa.BaseExtensionType ): @@ -640,8 +644,6 @@ def _make_or_get_arrow_element_set_type( ), is_set=True, ) - # A set of float32 or float16 is refused where it is declared (ITL-1591). - require_no_narrow_float_keys(lt.get_arrow_extension_type()) existing = self._logical_type_registry.get_by_arrow_extension_name( lt.logical_type_name ) @@ -1382,17 +1384,24 @@ def python_dicts_to_arrow_table( * ``python_schema`` omitted — the Python schema is derived from ``arrow_schema`` for value-conversion purposes; no type registration is performed. - * ``python_schema`` supplied — both schemas are used as-is and a - warning is logged if they are incompatible; no type - registration is performed in either case. + * ``python_schema`` supplied — it controls value conversion, and + the Arrow schema controls the table layout. The converter logs + a warning about possible incompatibility. Returns: A PyArrow ``Table`` containing the converted data. + + Raises: + NarrowFloatKeyError: If either declaration uses a narrow float as + a dict key or set element. """ - if python_schema is not None and arrow_schema is not None: - logger.warning( - "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." - ) + if arrow_schema is not None: + require_schema_without_narrow_float_keys(arrow_schema) + if python_schema is not None: + require_python_schema_without_narrow_float_keys(python_schema, self) + logger.warning( + "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." + ) if python_schema is None and arrow_schema is None: # Infer schema from data if not provided python_schema = infer_python_schema_from_pylist_data(python_dicts) diff --git a/src/orcapod/utils/polars_data_utils.py b/src/orcapod/utils/polars_data_utils.py index f8d1d10cb..d43ff1f2c 100644 --- a/src/orcapod/utils/polars_data_utils.py +++ b/src/orcapod/utils/polars_data_utils.py @@ -1,12 +1,55 @@ # Collection of functions to work with Arrow table data that underlies streams and/or datagrams from __future__ import annotations -from collections.abc import Collection +from collections.abc import Collection, Mapping +from typing import TYPE_CHECKING, cast import polars as pl +import pyarrow as pa +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.system_constants import constants +if TYPE_CHECKING: + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) + + +def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: + """Check Arrow declarations before Polars can drop their extension identity.""" + if isinstance(data, Mapping): + fields = [ + pa.field(name, cast("pa.DataType", column.type)) + for name, column in cast("Mapping[str, object]", data).items() + if isinstance(column, (pa.Array, pa.ChunkedArray)) + ] + if fields: + require_schema_without_narrow_float_keys(pa.schema(fields)) + elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): + require_schema_without_narrow_float_keys(data.schema) + elif not isinstance(data, (pl.DataFrame, pl.Series)): + if hasattr(data, "__arrow_c_array__"): + # PyArrow accepts a capsule provider without an explicit type. + array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] + cast("ArrowArrayExportable", data) # pyright: ignore[reportArgumentType] + ) + if isinstance(array.type, pa.StructType): + require_schema_without_narrow_float_keys(pa.schema(list(array.type))) + return pl.DataFrame(array) + elif hasattr(data, "__arrow_c_stream__"): + # Import the stream once and let Polars consume that same reader. + reader = pa.RecordBatchReader.from_stream( + cast("ArrowStreamExportable", data) + ) + require_schema_without_narrow_float_keys(reader.schema) + return pl.DataFrame(reader) + return pl.DataFrame(data) + def drop_columns_with_prefix( df: "pl.DataFrame", diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index c1ef4fd62..af820aa85 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -1009,3 +1009,127 @@ def test_datagram_checks_narrow_arrow_declaration_before_values( row.with_columns({"k": pa.field("k", narrow, nullable=False)}, k=None) else: row.with_columns({"m": int, "k": narrow}, m="invalid integer", k={}) + + +@pytest.mark.parametrize("width", NARROW) +@pytest.mark.parametrize("input_kind", ["reader", "mapping", "capsule"]) +@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) +def test_arrow_sources_check_readers_and_column_mappings(width, input_kind, polling): + from unittest.mock import Mock + + from orcapod.core.sources import PollingSource + from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol + from orcapod.types import Cursor + + extension = _live_set(width) + values = pa.array([[0.5]], type=extension.storage_type) + table = pa.table( + {"id": [1], "k": pa.ExtensionArray.from_storage(extension, values)} + ) + + class ArrowStream: + def __arrow_c_stream__(self, requested_schema=None): + return table.__arrow_c_stream__(requested_schema) + + if input_kind == "mapping": + data = {"id": [1], "k": table["k"]} + elif input_kind == "reader": + data = table.to_reader() + else: + data = ArrowStream() + + with pytest.raises(NarrowFloatKeyError, match="column 'k'.*set element type"): + if polling: + impl = Mock(spec=DynamicSourceProtocol) + impl.schema.return_value = None + impl.fetch.return_value = (Cursor(value=1), data) + source = PollingSource(impl, "id", source_id="poll", record_id_columns="id") + source.check_for_new_data() + else: + DataFrameSource(data, tag_columns="id", source_id="dataframe") + + +@pytest.mark.parametrize("entry", ["converter", "source", "datagram"]) +def test_registry_free_converter_refuses_narrow_set(entry): + from orcapod.semantic_types import UniversalTypeConverter + + converter = UniversalTypeConverter() + context = dataclasses.replace( + contexts.resolve_context(None), type_converter=converter + ) + with pytest.raises(NarrowFloatKeyError, match="set element type"): + if entry == "converter": + converter.python_type_to_arrow_type(set[np.float32]) + elif entry == "source": + DictSource( + [{"id": 1, "k": {1e-50, 2e-50}}], + data_schema={"id": int, "k": set[np.float32]}, + tag_columns="id", + data_context=context, + ) + else: + Data( + {"k": {1e-50, 2e-50}}, + python_schema={"k": set[np.float32]}, + data_context=context, + ).as_table() + + +@pytest.mark.parametrize("narrow_declaration", ["arrow", "python"]) +def test_partially_inherited_job_slot_validates_explicit_override(narrow_declaration): + from orcapod.core.nodes import SourceJobNode + from orcapod.core.operators import Batch + from orcapod.core.streams.base import typed_arrow_schemas + from orcapod.types import Schema + + pair = pa.struct([("key", pa.float32()), ("value", pa.int64())]) + source = ArrowTableSource( + pa.table({"id": [1], "k": pa.array([{"key": 0.5, "value": 1}], type=pair)}), + tag_columns="id", + tag_only_columns=True, + source_id="pair", + ) + batched = Batch().static_process(source) + tag_arrow, data_arrow = typed_arrow_schemas(batched) + # Both fully and partially inferred schemas retain the operator's layout. + assert SourceJobNode("all", bound_source=batched).arrow_schemas[1] == data_arrow + assert ( + SourceJobNode( + "partial", tag_schema=Schema({"id": list[int]}), bound_source=batched + ).arrow_schemas[1] + == data_arrow + ) + + key_type = np.float32 if narrow_declaration == "python" else float + declared_arrow = ( + data_arrow + if narrow_declaration == "arrow" + else pa.schema([pa.field("k", _dict_of(pa.float64()), nullable=False)]) + ) + with pytest.raises(NarrowFloatKeyError, match="[Cc]olumn 'k'"): + SourceJobNode( + "override", + data_schema=Schema({"k": dict[key_type, int]}), + bound_source=batched, + arrow_schemas=(tag_arrow, declared_arrow), + ) + + +@pytest.mark.parametrize("width", NARROW) +def test_direct_converter_checks_explicit_arrow_schema(width): + with pytest.raises(NarrowFloatKeyError, match="column 'k'.*dict key type"): + _converter().python_dicts_to_arrow_table( + [{"k": {1e-50: 1, 2e-50: 2}}], + arrow_schema=pa.schema([("k", _dict_of(width))]), + ) + + +def test_arrow_held_datagram_update_preserves_existing_schema(): + table = pa.table({"k": pa.array([[]], type=_dict_of(pa.float32()))}) + assert Data(table).update(k={1e-50: 1, 2e-50: 2}).as_dict()["k"] == {0.0: 2} + + +def test_datagram_checks_new_arrow_declaration_before_materializing_existing_data(): + row = Data({"m": "invalid integer"}, python_schema={"m": int}) + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): + row.with_columns({"k": _dict_of(pa.float32())}, k={}) From dee15f09dd7523538f1654e6ac6919f1550a8bfb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:48:00 -0800 Subject: [PATCH 05/32] fix(sources): preserve Polars pandas conversion --- src/orcapod/utils/polars_data_utils.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/orcapod/utils/polars_data_utils.py b/src/orcapod/utils/polars_data_utils.py index d43ff1f2c..592493595 100644 --- a/src/orcapod/utils/polars_data_utils.py +++ b/src/orcapod/utils/polars_data_utils.py @@ -1,9 +1,10 @@ # Collection of functions to work with Arrow table data that underlies streams and/or datagrams from __future__ import annotations -from collections.abc import Collection, Mapping +from collections.abc import Collection, Mapping, Sequence from typing import TYPE_CHECKING, cast +import pandas as pd import polars as pl import pyarrow as pa @@ -32,7 +33,9 @@ def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: require_schema_without_narrow_float_keys(pa.schema(fields)) elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): require_schema_without_narrow_float_keys(data.schema) - elif not isinstance(data, (pl.DataFrame, pl.Series)): + elif not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series, Sequence)): + # Polars handles these frame and sequence types before falling back to + # Arrow capsules. In particular, pandas' export erases empty object dtypes. if hasattr(data, "__arrow_c_array__"): # PyArrow accepts a capsule provider without an explicit type. array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] From cc4077ecdc9949ccdcac2536e56be605e2b6ada2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:01:28 -0800 Subject: [PATCH 06/32] fix(sources): validate pandas Arrow types and restore legacy Delta bindings --- changelog.d/ITL-1591.md | 6 +- docs/dev/design_issues/ITL-1591-NFK1.md | 6 +- src/orcapod/core/sources/data_frame_source.py | 3 +- .../core/sources/delta_table_source.py | 19 +++- src/orcapod/core/sources/polling_source.py | 5 +- src/orcapod/core/sources/stream_builder.py | 49 ++++++++++- src/orcapod/pipeline/job.py | 4 + src/orcapod/utils/polars_data_utils.py | 48 +--------- .../test_narrow_float_keys_refused.py | 88 ++++++++++++++++++- 9 files changed, 170 insertions(+), 58 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index aa926946e..346222df1 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -10,11 +10,15 @@ Arrow schema, a pipeline's declared input slot, a datagram's Python schema or explicitly typed new column, and a function pod's parameters and outputs when the pod is defined (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and - Arrow column mappings given to Polars-backed sources and explicit Arrow schemas + Arrow column mappings and Arrow-backed pandas dtypes given to Polars-backed sources + and explicit Arrow schemas given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain column, a list element, a struct field and a dict value. +- Loading a saved job preserves a Delta source whose schema matches the saved identity, + including legacy float32 or float16 keys. A newly encountered narrow key raises + `NarrowFloatKeyError` during load. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 904f773da..17f91e0d0 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -24,8 +24,10 @@ builder checks schemas at source ingestion. Explicit Arrow schemas are also chec source value conversion, when a datagram adds a column with a declared type, and when a saved source declaration is restored. The converter checks explicit Arrow declarations before converting Python rows, and checks Python set types even without a logical type -registry. DataFrameSource and PollingSource check incoming Arrow schemas and Arrow columns -before Polars can drop native set identity. Saved pipeline input slots record +registry. The shared source input adapter checks Arrow types before Polars can drop +native set identity, including Arrow-backed pandas dtypes. A restored Delta source +keeps the types recorded by its saved pipeline hash. A new narrow key at the saved +location raises a declaration error during job load. Saved pipeline input slots record whether their schemas came from a stream, so loading a blueprint can retain an operator result's types. Public slot declarations check any Arrow override and each explicitly declared Python role, including when the other Python role comes from a bound stream. diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 432f5bd01..6dec7b431 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -16,6 +16,7 @@ from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, require_custom_system_tags, + dataframe_from_source_input, require_supported_nullable_types, ) from orcapod.utils import arrow_utils, polars_data_utils @@ -70,7 +71,7 @@ def __init__( if schema is not None: require_schema_without_narrow_float_keys(schema) - df = polars_data_utils.dataframe_from_source_input(data) + df = dataframe_from_source_input(data) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index 239c00191..bf2eb3484 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -19,6 +19,9 @@ SourceStreamResult, ) from orcapod.databases.storage_utils import delta_to_pyarrow_dataset +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) from orcapod.types import PathLike from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import _normalize_column_list @@ -64,6 +67,7 @@ def __init__( source_id: str | None = None, *, tag_only_columns: TagOnlyColumns = (), + _saved_pipeline_hash: str | None = None, **kwargs: Any, ) -> None: resolved = Path(delta_table_path).resolve() @@ -97,12 +101,19 @@ def __init__( self._tag_only_columns: tuple[str, ...] = tuple( c for c in self._tag_columns if c not in data_tags ) - result = self._build(table) + result = self._build(table, inherited_types=_saved_pipeline_hash is not None) self._stream = result.stream self._tag_columns = result.tag_columns self._system_tag_columns = result.system_tag_columns if self._source_name is None: self._source_name = result.source_name + # An unchanged saved schema predates this declaration check. A different + # schema at the saved location must pass the same check as a new source. + if ( + _saved_pipeline_hash is not None + and self.pipeline_hash().to_string() != _saved_pipeline_hash + ): + require_schema_without_narrow_float_keys(table.schema) def _read_table(self) -> "pa.Table": """Read the table at the Delta version ``self._delta_table`` is loaded at.""" @@ -112,7 +123,7 @@ def _read_table(self) -> "pa.Table": self._delta_table, as_large_types=True ).to_table() - def _build(self, table: "pa.Table") -> SourceStreamResult: + def _build(self, table: "pa.Table", *, inherited_types: bool) -> SourceStreamResult: """Enrich ``table`` as this source's stream (source info, system tags).""" builder = SourceStreamBuilder(self.data_context, self.orcapod_config) return builder.build( @@ -123,6 +134,7 @@ def _build(self, table: "pa.Table") -> SourceStreamResult: kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), system_tag_columns=self._system_tag_columns, + inherited_types=inherited_types, ) @override @@ -158,7 +170,7 @@ def check_for_new_data(self) -> bool: if same_rows(self._table, table, ordered=not self._record_id_columns): self._version = version return False - stream = self._build(table).stream + stream = self._build(table, inherited_types=True).stream self._version = version self._stream = stream self._table = table @@ -194,5 +206,6 @@ def from_config( system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), source_id=name, + _saved_pipeline_hash=config.get("pipeline_hash"), ), ) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index cd9de947a..d497eb537 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -31,6 +31,7 @@ from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, + dataframe_from_source_input, require_supported_nullable_types, ) from orcapod.core.streams.view import ( @@ -49,7 +50,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Cursor, PollingConfig, Schema -from orcapod.utils import arrow_utils, polars_data_utils +from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( _normalize_column_list, @@ -878,7 +879,7 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - df = polars_data_utils.dataframe_from_source_input(data) + df = dataframe_from_source_input(data) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 6ea04f94b..15d0fe59a 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -10,10 +10,12 @@ import datetime import json -from collections.abc import Collection, Sequence +from collections.abc import Collection, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast +import pandas as pd +import polars as pl import pyarrow as pa from orcapod.core.sources.source_ids import ( @@ -34,11 +36,56 @@ from orcapod.utils.schema_utils import compute_source_schema_hash if TYPE_CHECKING: + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) + from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext from orcapod.protocols.hashing_protocols import ArrowHasherProtocol +def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: + """Validate the original Arrow fields before converting source input to Polars. + + Keep pandas frames on the pandas conversion path so that empty object + columns retain their dtype. Only their Arrow-backed dtypes declare Arrow fields. + """ + schema = None + if isinstance(data, pd.DataFrame): + schema = pa.schema( + pa.field(str(name), dtype.pyarrow_dtype) + for name, dtype in zip(data.columns, data.dtypes) + if isinstance(dtype, pd.ArrowDtype) + ) + elif isinstance(data, Mapping): + schema = pa.schema( + pa.field(name, cast("pa.DataType", column.type)) + for name, column in cast("Mapping[str, object]", data).items() + if isinstance(column, (pa.Array, pa.ChunkedArray)) + ) + elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): + schema = data.schema + elif not isinstance(data, (pl.DataFrame, pl.Series, Sequence)): + if hasattr(data, "__arrow_c_array__"): + # PyArrow accepts a capsule provider without an explicit type. + array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] + cast("ArrowArrayExportable", data) # pyright: ignore[reportArgumentType] + ) + if isinstance(array.type, pa.StructType): + schema = pa.schema(list(array.type)) + data = array + elif hasattr(data, "__arrow_c_stream__"): + # Import the stream once and let Polars consume that same reader. + data = pa.RecordBatchReader.from_stream(cast("ArrowStreamExportable", data)) + schema = data.schema + if schema is not None: + require_schema_without_narrow_float_keys(schema) + return pl.DataFrame(data) + + def _contains_null_type(arrow_type: pa.DataType) -> bool: """Return whether an Arrow type contains the Null type at any depth.""" if isinstance(arrow_type, pa.BaseExtensionType): diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..142b3b47b 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1792,6 +1792,7 @@ def load( saved_database_kind, saved_source_kind, ) + from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError path = _Path(path) with open(path) as f: @@ -1891,6 +1892,9 @@ def load( spec_name, spec_name, ) + except NarrowFloatKeyError as exc: + exc.add_note(f"{path}: source {spec_name!r}") + raise except Warning: # A warning turned into an error (a ProvisionalHashWarning under an # error filter) is the caller's request: it propagates, never read as a diff --git a/src/orcapod/utils/polars_data_utils.py b/src/orcapod/utils/polars_data_utils.py index 592493595..f8d1d10cb 100644 --- a/src/orcapod/utils/polars_data_utils.py +++ b/src/orcapod/utils/polars_data_utils.py @@ -1,58 +1,12 @@ # Collection of functions to work with Arrow table data that underlies streams and/or datagrams from __future__ import annotations -from collections.abc import Collection, Mapping, Sequence -from typing import TYPE_CHECKING, cast +from collections.abc import Collection -import pandas as pd import polars as pl -import pyarrow as pa -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.system_constants import constants -if TYPE_CHECKING: - from polars._typing import ( - ArrowArrayExportable, - ArrowStreamExportable, - FrameInitTypes, - ) - - -def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: - """Check Arrow declarations before Polars can drop their extension identity.""" - if isinstance(data, Mapping): - fields = [ - pa.field(name, cast("pa.DataType", column.type)) - for name, column in cast("Mapping[str, object]", data).items() - if isinstance(column, (pa.Array, pa.ChunkedArray)) - ] - if fields: - require_schema_without_narrow_float_keys(pa.schema(fields)) - elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): - require_schema_without_narrow_float_keys(data.schema) - elif not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series, Sequence)): - # Polars handles these frame and sequence types before falling back to - # Arrow capsules. In particular, pandas' export erases empty object dtypes. - if hasattr(data, "__arrow_c_array__"): - # PyArrow accepts a capsule provider without an explicit type. - array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] - cast("ArrowArrayExportable", data) # pyright: ignore[reportArgumentType] - ) - if isinstance(array.type, pa.StructType): - require_schema_without_narrow_float_keys(pa.schema(list(array.type))) - return pl.DataFrame(array) - elif hasattr(data, "__arrow_c_stream__"): - # Import the stream once and let Polars consume that same reader. - reader = pa.RecordBatchReader.from_stream( - cast("ArrowStreamExportable", data) - ) - require_schema_without_narrow_float_keys(reader.schema) - return pl.DataFrame(reader) - return pl.DataFrame(data) - def drop_columns_with_prefix( df: "pl.DataFrame", diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index af820aa85..a29ad056c 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -23,6 +23,7 @@ from typing import Any, cast import numpy as np +import pandas as pd import polars as pl import pyarrow as pa import pytest @@ -768,6 +769,78 @@ def test_saved_job_rejects_prohibited_source_declaration(tmp_path: Path) -> None PipelineJob.load(path) +def test_legacy_delta_job_keeps_its_source_bound( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from deltalake import write_deltalake + + from orcapod.core.sources import stream_builder + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import PipelineJob + + delta_path = tmp_path / "input" + values = pa.table( + {"id": [1], "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(pa.float32()))} + ) + write_deltalake(delta_path, values) + with monkeypatch.context() as legacy: + legacy.setattr( + stream_builder, "require_schema_without_narrow_float_keys", lambda _: None + ) + source = DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) + job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) + with job: + source.batch(label="batch") + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + for node in saved["pipeline"]["nodes"].values(): + if node["node_type"] == "source": + node["source_config"].pop("inherited_types", None) + path.write_text(json.dumps(saved)) + + restored = PipelineJob.load(path) + assert not restored.unbound_sources + reopened = restored.sources[source.source_name] + assert isinstance(reopened, DeltaTableSource) + write_deltalake(delta_path, values, mode="append") + assert reopened.check_for_new_data() + assert reopened.as_table().num_rows == 2 + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): + DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) + + +def test_saved_delta_job_reports_new_narrow_schema(tmp_path: Path) -> None: + from deltalake import write_deltalake + + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import PipelineJob + + delta_path = tmp_path / "input" + + def table(key_type: pa.DataType) -> pa.Table: + return pa.table( + { + "id": [1], + "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(key_type)), + } + ) + + write_deltalake(delta_path, table(pa.float64())) + source = DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) + job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) + with job: + source.batch(label="batch") + path = tmp_path / "job.json" + job.save(path) + + write_deltalake( + delta_path, table(pa.float32()), mode="overwrite", schema_mode="overwrite" + ) + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): + PipelineJob.load(path) + + @pytest.mark.parametrize("declared_in_arrow", [False, True]) def test_pipeline_input_slot_refuses_declared_narrow_type( declared_in_arrow: bool, @@ -1012,7 +1085,9 @@ def test_datagram_checks_narrow_arrow_declaration_before_values( @pytest.mark.parametrize("width", NARROW) -@pytest.mark.parametrize("input_kind", ["reader", "mapping", "capsule"]) +@pytest.mark.parametrize( + "input_kind", ["reader", "mapping", "capsule", "pandas", "pandas_nested"] +) @pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) def test_arrow_sources_check_readers_and_column_mappings(width, input_kind, polling): from unittest.mock import Mock @@ -1035,6 +1110,17 @@ def __arrow_c_stream__(self, requested_schema=None): data = {"id": [1], "k": table["k"]} elif input_kind == "reader": data = table.to_reader() + elif input_kind == "pandas": + data = pd.DataFrame( + {"id": [1], "k": pd.Series(table["k"], dtype=pd.ArrowDtype(extension))} + ) + elif input_kind == "pandas_nested": + nested = pa.StructArray.from_arrays( + [values], fields=[_set_storage_field(width)] + ) + data = pd.DataFrame( + {"id": [1], "k": pd.Series(nested, dtype=pd.ArrowDtype(nested.type))} + ) else: data = ArrowStream() From 004557b9b262623f56fbe75358680420eaffee6a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:28:37 -0800 Subject: [PATCH 07/32] fix(sources): validate Arrow imports and preserve legacy job bindings --- changelog.d/ITL-1591.md | 11 +-- docs/dev/design_issues/ITL-1591-NFK1.md | 9 +-- .../core/sources/delta_table_source.py | 14 +--- src/orcapod/core/sources/stream_builder.py | 51 ++++++++------ src/orcapod/pipeline/serialization.py | 20 ++++-- .../semantic_types/narrow_float_keys.py | 20 +++++- .../test_narrow_float_keys_refused.py | 70 +++++++++++++++++-- 7 files changed, 140 insertions(+), 55 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 346222df1..fd07d5c75 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -10,15 +10,16 @@ Arrow schema, a pipeline's declared input slot, a datagram's Python schema or explicitly typed new column, and a function pod's parameters and outputs when the pod is defined (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and - Arrow column mappings and Arrow-backed pandas dtypes given to Polars-backed sources - and explicit Arrow schemas + column mappings with Arrow arrays or Arrow-backed pandas Series given to + Polars-backed sources, Arrow-backed pandas frames, and explicit Arrow schemas given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain column, a list element, a struct field and a dict value. -- Loading a saved job preserves a Delta source whose schema matches the saved identity, - including legacy float32 or float16 keys. A newly encountered narrow key raises - `NarrowFloatKeyError` during load. +- Loading a saved job preserves source bindings whose rebuilt inputs match the saved + pipeline identity, including legacy float32 or float16 keys in Delta and SpiralDB + tables. A narrow key in a changed input schema raises `NarrowFloatKeyError` during + load. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 17f91e0d0..1049ad0bb 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -24,10 +24,11 @@ builder checks schemas at source ingestion. Explicit Arrow schemas are also chec source value conversion, when a datagram adds a column with a declared type, and when a saved source declaration is restored. The converter checks explicit Arrow declarations before converting Python rows, and checks Python set types even without a logical type -registry. The shared source input adapter checks Arrow types before Polars can drop -native set identity, including Arrow-backed pandas dtypes. A restored Delta source -keeps the types recorded by its saved pipeline hash. A new narrow key at the saved -location raises a declaration error during job load. Saved pipeline input slots record +registry. The shared source input adapter checks imported Arrow schemas before Polars +can drop native set identity, including Arrow-backed pandas columns in mappings. +The saved-source resolver keeps input types when the rebuilt source matches its saved +pipeline hash. A narrow key in a changed input schema raises a declaration error during +job load. Saved pipeline input slots record whether their schemas came from a stream, so loading a blueprint can retain an operator result's types. Public slot declarations check any Arrow override and each explicitly declared Python role, including when the other Python role comes from a bound stream. diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index bf2eb3484..01d897301 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -19,9 +19,6 @@ SourceStreamResult, ) from orcapod.databases.storage_utils import delta_to_pyarrow_dataset -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.types import PathLike from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import _normalize_column_list @@ -67,7 +64,6 @@ def __init__( source_id: str | None = None, *, tag_only_columns: TagOnlyColumns = (), - _saved_pipeline_hash: str | None = None, **kwargs: Any, ) -> None: resolved = Path(delta_table_path).resolve() @@ -101,19 +97,12 @@ def __init__( self._tag_only_columns: tuple[str, ...] = tuple( c for c in self._tag_columns if c not in data_tags ) - result = self._build(table, inherited_types=_saved_pipeline_hash is not None) + result = self._build(table, inherited_types=False) self._stream = result.stream self._tag_columns = result.tag_columns self._system_tag_columns = result.system_tag_columns if self._source_name is None: self._source_name = result.source_name - # An unchanged saved schema predates this declaration check. A different - # schema at the saved location must pass the same check as a new source. - if ( - _saved_pipeline_hash is not None - and self.pipeline_hash().to_string() != _saved_pipeline_hash - ): - require_schema_without_narrow_float_keys(table.schema) def _read_table(self) -> "pa.Table": """Read the table at the Delta version ``self._delta_table`` is loaded at.""" @@ -206,6 +195,5 @@ def from_config( system_tag_columns=config.get("system_tag_columns", ()), record_id_columns=config.get("record_id_columns"), source_id=name, - _saved_pipeline_hash=config.get("pipeline_hash"), ), ) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 15d0fe59a..d33d21cee 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -10,7 +10,7 @@ import datetime import json -from collections.abc import Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Mapping, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -27,11 +27,11 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError, RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.system_constants import constants -from orcapod.types import ContentHash from orcapod.semantic_types.narrow_float_keys import ( require_schema_without_narrow_float_keys, ) +from orcapod.system_constants import constants +from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.schema_utils import compute_source_schema_hash @@ -48,24 +48,35 @@ def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: - """Validate the original Arrow fields before converting source input to Polars. + """Convert source input to Polars, checking its Arrow schema at import. - Keep pandas frames on the pandas conversion path so that empty object - columns retain their dtype. Only their Arrow-backed dtypes declare Arrow fields. + Polars can discard Arrow extension identities and field metadata on import. + Import Arrow providers with PyArrow first. For column containers, read the + exported Arrow columns together, leaving the conversion of other columns to + Polars so its dtype inference (including empty pandas columns) is preserved. """ schema = None - if isinstance(data, pd.DataFrame): - schema = pa.schema( - pa.field(str(name), dtype.pyarrow_dtype) - for name, dtype in zip(data.columns, data.dtypes) - if isinstance(dtype, pd.ArrowDtype) - ) - elif isinstance(data, Mapping): - schema = pa.schema( - pa.field(name, cast("pa.DataType", column.type)) - for name, column in cast("Mapping[str, object]", data).items() - if isinstance(column, (pa.Array, pa.ChunkedArray)) - ) + if isinstance(data, (Mapping, pd.DataFrame)): + columns = cast("Mapping[object, object]", data) + fields: list[pa.Field[pa.DataType]] = [] + for name, column in columns.items(): + exported = ( + cast("object", column.array) + if isinstance(column, pd.Series) + else column + ) + if isinstance(exported, (pa.Array, pa.ChunkedArray)): + arrow_type = cast("pa.DataType", exported.type) + else: + export = cast( + "Callable[[], pa.Array[pa.Scalar[pa.DataType]] | pa.ChunkedArray[pa.Scalar[pa.DataType]]] | None", + getattr(exported, "__arrow_array__", None), + ) + if export is None: + continue + arrow_type = export().type + fields.append(pa.field(str(name), arrow_type)) + schema = pa.schema(fields) elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): schema = data.schema elif not isinstance(data, (pl.DataFrame, pl.Series, Sequence)): @@ -82,7 +93,7 @@ def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: data = pa.RecordBatchReader.from_stream(cast("ArrowStreamExportable", data)) schema = data.schema if schema is not None: - require_schema_without_narrow_float_keys(schema) + require_schema_without_narrow_float_keys(schema, source_input=True) return pl.DataFrame(data) @@ -615,7 +626,7 @@ def build( # Nor is a dict keyed by, or a set of, float32 or float16 (ITL-1591): refused # here first, as the stream refuses it, before any key column or hash. if not inherited_types: - require_schema_without_narrow_float_keys(table.schema) + require_schema_without_narrow_float_keys(table.schema, source_input=True) # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index d84698fc4..b378bd9c4 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -11,7 +11,6 @@ from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias, cast -from orcapod.types import Schema from orcapod.logical_types.canonical_form import ( declaration_form_field, declaration_form_schema, @@ -23,11 +22,12 @@ arrow_type_identifier, require_readable, ) - from orcapod.semantic_types.narrow_float_keys import ( NarrowFloatKeyError, require_schema_without_narrow_float_keys, + saved_source_schema_errors, ) +from orcapod.types import Schema if TYPE_CHECKING: import pyarrow as pa @@ -692,9 +692,19 @@ def resolve_source_from_config( ) cls = SOURCE_REGISTRY[source_type] try: - # All sources accept db_registry — always forward it. - # Sources that don't embed database references simply ignore it. - return cls.from_config(config, db_registry=db_registry) + # Let the input schema reach the identity check even if it contains a + # legacy narrow key. Explicit declarations in the config still fail early. + schema_errors: list[NarrowFloatKeyError] = [] + token = saved_source_schema_errors.set(schema_errors) + try: + source = cls.from_config(config, db_registry=db_registry) + finally: + saved_source_schema_errors.reset(token) + if schema_errors: + saved_hash = config.get("pipeline_hash") + if saved_hash is None or source.pipeline_hash().to_string() != saved_hash: + raise schema_errors[0] + return source except (NarrowFloatKeyError, Warning): # An invalid declaration and a warning turned into an error propagate # instead of becoming a proxy for a source that could not be rebuilt. diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 4304dd868..bb76aa44b 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -30,6 +30,7 @@ import json from collections.abc import Mapping +from contextvars import ContextVar from types import UnionType from typing import TYPE_CHECKING, Literal, Union, cast, get_args, get_origin @@ -59,6 +60,13 @@ class NarrowFloatKeyError(InputValidationError, ValueError): """A declared type has a ``float32`` or ``float16`` dict key or set element.""" +# The saved-source resolver owns this scope, including a separate scope for each +# nested source. Explicit schema declarations never opt into deferral. +saved_source_schema_errors: ContextVar[list[NarrowFloatKeyError] | None] = ContextVar( + "saved_source_schema_errors", default=None +) + + def require_supported_python_float_key(annotation: object, *, is_set: bool) -> None: """Report an unsupported NumPy half float in a key or set element declaration.""" import numpy as np @@ -214,7 +222,9 @@ def require_no_narrow_float_keys( ) -def require_schema_without_narrow_float_keys(arrow_schema: pa.Schema) -> None: +def require_schema_without_narrow_float_keys( + arrow_schema: pa.Schema, *, source_input: bool = False +) -> None: """Refuse an Arrow schema with a ``float32`` or ``float16`` dict key or set element. Applied to a source's Arrow declaration and to explicitly declared mutations. @@ -223,6 +233,8 @@ def require_schema_without_narrow_float_keys(arrow_schema: pa.Schema) -> None: Args: arrow_schema: The Arrow schema of the table. + source_input: The schema came from the source's input data. During saved + source reconstruction its diagnostic can wait for the identity check. Raises: NarrowFloatKeyError: If a column's type is, or contains at any depth, a dict @@ -236,6 +248,10 @@ def require_schema_without_narrow_float_keys(arrow_schema: pa.Schema) -> None: if (found := narrow_float_keys(field.type, field.metadata)) ] if lines: - raise NarrowFloatKeyError( + error = NarrowFloatKeyError( f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}:\n" + "\n".join(lines) + f"\n{_REMEDY}" ) + if source_input and (errors := saved_source_schema_errors.get()) is not None: + errors.append(error) + else: + raise error diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index a29ad056c..9815a86f5 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -785,7 +785,9 @@ def test_legacy_delta_job_keeps_its_source_bound( write_deltalake(delta_path, values) with monkeypatch.context() as legacy: legacy.setattr( - stream_builder, "require_schema_without_narrow_float_keys", lambda _: None + stream_builder, + "require_schema_without_narrow_float_keys", + lambda *args, **kwargs: None, ) source = DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) @@ -841,6 +843,59 @@ def table(key_type: pa.DataType) -> pa.Table: PipelineJob.load(path) +def test_legacy_spiral_job_keeps_its_source_bound( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.core.sources import SpiralDBTableSource, stream_builder + from orcapod.databases import DeltaTableDatabase + from orcapod.pipeline import PipelineJob + from tests.test_databases import fake_spiral_sdk + + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject("p") + table = project.create_table( + "default.pairs", key_schema=pa.schema([("id", pa.string())]) + ) + table.write( + pa.table( + { + "id": ["a"], + "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(pa.float32())), + } + ) + ) + with monkeypatch.context() as legacy: + legacy.setattr( + stream_builder, + "require_schema_without_narrow_float_keys", + lambda *args, **kwargs: None, + ) + source = SpiralDBTableSource( + "p", "pairs", tag_columns="id", tag_only_columns=True + ) + with source: + job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) + with job: + source.batch(label="batch") + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + for node in saved["pipeline"]["nodes"].values(): + if node["node_type"] == "source": + node["source_config"].pop("inherited_types", None) + path.write_text(json.dumps(saved)) + + restored = PipelineJob.load(path) + assert not restored.unbound_sources + reopened = restored.sources[source.source_name] + assert isinstance(reopened, SpiralDBTableSource) + with reopened: + assert reopened.pipeline_hash() == source.pipeline_hash() + assert reopened.as_table()["k"].to_pylist() == [ + [{"key": 0.5, "value": 1}] + ] + + @pytest.mark.parametrize("declared_in_arrow", [False, True]) def test_pipeline_input_slot_refuses_declared_narrow_type( declared_in_arrow: bool, @@ -1086,7 +1141,8 @@ def test_datagram_checks_narrow_arrow_declaration_before_values( @pytest.mark.parametrize("width", NARROW) @pytest.mark.parametrize( - "input_kind", ["reader", "mapping", "capsule", "pandas", "pandas_nested"] + "input_kind", + ["reader", "mapping", "capsule", "pandas", "pandas_nested", "pandas_in_mapping"], ) @pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) def test_arrow_sources_check_readers_and_column_mappings(width, input_kind, polling): @@ -1110,10 +1166,12 @@ def __arrow_c_stream__(self, requested_schema=None): data = {"id": [1], "k": table["k"]} elif input_kind == "reader": data = table.to_reader() - elif input_kind == "pandas": - data = pd.DataFrame( - {"id": [1], "k": pd.Series(table["k"], dtype=pd.ArrowDtype(extension))} - ) + elif input_kind in {"pandas", "pandas_in_mapping"}: + columns = { + "id": [1], + "k": pd.Series(table["k"], dtype=pd.ArrowDtype(extension)), + } + data = pd.DataFrame(columns) if input_kind == "pandas" else columns elif input_kind == "pandas_nested": nested = pa.StructArray.from_arrays( [values], fields=[_set_storage_field(width)] From aa89dd7b9ae793c047d4b04b1db0ee7606f3cf61 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:31:46 -0800 Subject: [PATCH 08/32] fix(sources): validate Arrow-backed pandas column iterables --- changelog.d/ITL-1591.md | 3 +- docs/dev/design_issues/ITL-1591-NFK1.md | 3 +- src/orcapod/core/sources/stream_builder.py | 59 ++++++++++++------- .../test_narrow_float_keys_refused.py | 29 ++++++--- 4 files changed, 64 insertions(+), 30 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index fd07d5c75..fbb2525a6 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -11,7 +11,8 @@ explicitly typed new column, and a function pod's parameters and outputs when the pod is defined (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and column mappings with Arrow arrays or Arrow-backed pandas Series given to - Polars-backed sources, Arrow-backed pandas frames, and explicit Arrow schemas + Polars-backed sources, Arrow-backed pandas frames and sequences of Series, + and explicit Arrow schemas given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 1049ad0bb..2dc593d00 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -25,7 +25,8 @@ source value conversion, when a datagram adds a column with a declared type, and saved source declaration is restored. The converter checks explicit Arrow declarations before converting Python rows, and checks Python set types even without a logical type registry. The shared source input adapter checks imported Arrow schemas before Polars -can drop native set identity, including Arrow-backed pandas columns in mappings. +can drop native set identity, including Arrow-backed pandas columns passed in +mappings, sequences and iterators. The saved-source resolver keeps input types when the rebuilt source matches its saved pipeline hash. A narrow key in a changed input schema raises a declaration error during job load. Saved pipeline input slots record diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index d33d21cee..cb8977079 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -10,8 +10,9 @@ import datetime import json -from collections.abc import Callable, Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence, Sized from dataclasses import dataclass +from itertools import chain, islice from typing import TYPE_CHECKING, Any, cast import pandas as pd @@ -56,13 +57,45 @@ def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: Polars so its dtype inference (including empty pandas columns) is preserved. """ schema = None + column_items: Iterable[tuple[object, object]] = () if isinstance(data, (Mapping, pd.DataFrame)): - columns = cast("Mapping[object, object]", data) + column_items = cast("Mapping[object, object]", data).items() + elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): + schema = data.schema + elif isinstance(data, Sequence): + if len(data) and isinstance(data[0], (pd.Series, pd.Index)): + column_items = ((column.name, column) for column in data) + elif not isinstance(data, (pl.DataFrame, pl.Series)): + if hasattr(data, "__arrow_c_array__"): + # PyArrow accepts a capsule provider without an explicit type. + array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] + cast("ArrowArrayExportable", data) # pyright: ignore[reportArgumentType] + ) + if isinstance(array.type, pa.StructType): + schema = pa.schema(list(array.type)) + data = array + elif hasattr(data, "__arrow_c_stream__"): + # Import the stream once and let Polars consume that same reader. + data = pa.RecordBatchReader.from_stream(cast("ArrowStreamExportable", data)) + schema = data.schema + elif isinstance(data, Iterable) and not isinstance(data, Sized): + # Polars also treats an iterator starting with a pandas column as a + # column container. Keep ordinary row iterators lazy. + iterator = iter(data) + head = tuple(islice(iterator, 1)) + restored = chain(head, iterator) + if head and isinstance(head[0], (pd.Series, pd.Index)): + columns = list(restored) + column_items = ((column.name, column) for column in columns) + data = iter(columns) + else: + data = restored + if schema is None: fields: list[pa.Field[pa.DataType]] = [] - for name, column in columns.items(): + for name, column in column_items: exported = ( cast("object", column.array) - if isinstance(column, pd.Series) + if isinstance(column, (pd.Series, pd.Index)) else column ) if isinstance(exported, (pa.Array, pa.ChunkedArray)): @@ -77,23 +110,7 @@ def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: arrow_type = export().type fields.append(pa.field(str(name), arrow_type)) schema = pa.schema(fields) - elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): - schema = data.schema - elif not isinstance(data, (pl.DataFrame, pl.Series, Sequence)): - if hasattr(data, "__arrow_c_array__"): - # PyArrow accepts a capsule provider without an explicit type. - array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] - cast("ArrowArrayExportable", data) # pyright: ignore[reportArgumentType] - ) - if isinstance(array.type, pa.StructType): - schema = pa.schema(list(array.type)) - data = array - elif hasattr(data, "__arrow_c_stream__"): - # Import the stream once and let Polars consume that same reader. - data = pa.RecordBatchReader.from_stream(cast("ArrowStreamExportable", data)) - schema = data.schema - if schema is not None: - require_schema_without_narrow_float_keys(schema, source_input=True) + require_schema_without_narrow_float_keys(schema, source_input=True) return pl.DataFrame(data) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 9815a86f5..95496ba04 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -1142,7 +1142,16 @@ def test_datagram_checks_narrow_arrow_declaration_before_values( @pytest.mark.parametrize("width", NARROW) @pytest.mark.parametrize( "input_kind", - ["reader", "mapping", "capsule", "pandas", "pandas_nested", "pandas_in_mapping"], + [ + "reader", + "mapping", + "capsule", + "pandas", + "pandas_nested", + "pandas_in_mapping", + "pandas_sequence", + "pandas_iterator", + ], ) @pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) def test_arrow_sources_check_readers_and_column_mappings(width, input_kind, polling): @@ -1166,12 +1175,18 @@ def __arrow_c_stream__(self, requested_schema=None): data = {"id": [1], "k": table["k"]} elif input_kind == "reader": data = table.to_reader() - elif input_kind in {"pandas", "pandas_in_mapping"}: - columns = { - "id": [1], - "k": pd.Series(table["k"], dtype=pd.ArrowDtype(extension)), - } - data = pd.DataFrame(columns) if input_kind == "pandas" else columns + elif input_kind.startswith("pandas") and input_kind != "pandas_nested": + series = pd.Series(table["k"], name="k", dtype=pd.ArrowDtype(extension)) + if input_kind in {"pandas_sequence", "pandas_iterator"}: + series_columns = [pd.Series([1], name="id"), series] + data = ( + iter(series_columns) + if input_kind == "pandas_iterator" + else series_columns + ) + else: + columns = {"id": [1], "k": series} + data = pd.DataFrame(columns) if input_kind == "pandas" else columns elif input_kind == "pandas_nested": nested = pa.StructArray.from_arrays( [values], fields=[_set_storage_field(width)] From ca6c3c1a636765d5b8c60ac4b9ded0abb97d854b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 10:49:05 -0800 Subject: [PATCH 09/32] fix(sources): validate original Arrow declarations without converting input --- docs/dev/design_issues/ITL-1591-NFK1.md | 7 +- src/orcapod/core/sources/data_frame_source.py | 9 +- src/orcapod/core/sources/polars_input.py | 209 ++++++++++++++++++ src/orcapod/core/sources/polling_source.py | 15 +- .../core/sources/spiraldb_table_source.py | 5 + src/orcapod/core/sources/stream_builder.py | 82 +------ .../test_narrow_float_keys_refused.py | 106 +++++++++ 7 files changed, 347 insertions(+), 86 deletions(-) create mode 100644 src/orcapod/core/sources/polars_input.py diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 2dc593d00..d28b71445 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -24,9 +24,10 @@ builder checks schemas at source ingestion. Explicit Arrow schemas are also chec source value conversion, when a datagram adds a column with a declared type, and when a saved source declaration is restored. The converter checks explicit Arrow declarations before converting Python rows, and checks Python set types even without a logical type -registry. The shared source input adapter checks imported Arrow schemas before Polars -can drop native set identity, including Arrow-backed pandas columns passed in -mappings, sequences and iterators. +registry. The Polars-backed sources keep the incoming Arrow declarations for the schema check +when importing arrays or streams, including Arrow-backed pandas columns passed in +mappings, sequences and iterators. The check uses those declarations and inferred +Arrow fields before building the stream. The input data follows its usual conversion path. The saved-source resolver keeps input types when the rebuilt source matches its saved pipeline hash. A narrow key in a changed input schema raises a declaration error during job load. Saved pipeline input slots record diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 6dec7b431..57844e17e 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -10,13 +10,16 @@ from orcapod.semantic_types.narrow_float_keys import ( require_schema_without_narrow_float_keys, ) +from orcapod.core.sources.polars_input import ( + dataframe_with_input_schema, + require_polars_input_types, +) from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder from orcapod.core.sources.stream_builder import ( normalize_record_id_columns, require_custom_system_tags, - dataframe_from_source_input, require_supported_nullable_types, ) from orcapod.utils import arrow_utils, polars_data_utils @@ -71,7 +74,7 @@ def __init__( if schema is not None: require_schema_without_narrow_float_keys(schema) - df = dataframe_from_source_input(data) + df, input_schema = dataframe_with_input_schema(data) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] @@ -96,6 +99,7 @@ def __init__( raise ValueError(f"TagProtocol column(s) not found in data: {missing}") arrow_table = df.to_arrow() + require_polars_input_types(arrow_table.schema, input_schema) if schema is not None: require_supported_nullable_types(schema) require_custom_system_tags(arrow_table, system_tag_columns, schema=schema) @@ -112,6 +116,7 @@ def __init__( builder = SourceStreamBuilder(self.data_context, self.orcapod_config) result = builder.build( arrow_table, + input_types_checked=True, tag_columns=tag_columns, data_tags=source_data_tags(tag_columns, tag_only_columns), source_name=self._source_name, diff --git a/src/orcapod/core/sources/polars_input.py b/src/orcapod/core/sources/polars_input.py new file mode 100644 index 000000000..a9c2600ec --- /dev/null +++ b/src/orcapod/core/sources/polars_input.py @@ -0,0 +1,209 @@ +"""Keep declared Arrow types available across Polars' source input conversion.""" + +from __future__ import annotations + +import ctypes +from collections.abc import Iterable, Iterator, Mapping, Sequence, Sized +from itertools import chain +from typing import TYPE_CHECKING, cast, final + +import pandas as pd +import polars as pl +import pyarrow as pa + +from orcapod.semantic_types.narrow_float_keys import ( + require_schema_without_narrow_float_keys, +) + +if TYPE_CHECKING: + from polars._typing import ( + ArrowArrayExportable, + ArrowStreamExportable, + FrameInitTypes, + ) + + +# The C Data and Stream interfaces allow an opaque provider to supply its schema +# without importing any arrays into PyArrow. Polars gets the original capsules. +@final +class _ArrowSchema(ctypes.Structure): + """The stable Arrow C Data Interface schema ABI.""" + + _fields_ = [ + ("format", ctypes.c_void_p), + ("name", ctypes.c_void_p), + ("metadata", ctypes.c_void_p), + ("flags", ctypes.c_int64), + ("n_children", ctypes.c_int64), + ("children", ctypes.c_void_p), + ("dictionary", ctypes.c_void_p), + ("release", ctypes.c_void_p), + ("private_data", ctypes.c_void_p), + ] + if TYPE_CHECKING: + release: int | None = None + + +_get_capsule_pointer = ctypes.pythonapi.PyCapsule_GetPointer +_get_capsule_pointer.argtypes = [ctypes.py_object, ctypes.c_char_p] +_get_capsule_pointer.restype = ctypes.c_void_p +_GetStreamSchema = ctypes.PYFUNCTYPE( + ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(_ArrowSchema) +) + + +@ctypes.CFUNCTYPE(None, ctypes.POINTER(_ArrowSchema)) +def _release_borrowed_schema(schema: ctypes._Pointer[_ArrowSchema]) -> None: # noqa: SLF001 + """Mark the copied schema released while the original owns all pointers.""" + schema.contents.release = None + + +@final +class _InspectArrowArray: + """Read the schema on export and hand Polars the same array and schema.""" + + def __init__(self, provider: ArrowArrayExportable) -> None: + self._provider = provider + self.schema: pa.Schema | None = None + + def __arrow_c_array__( + self, requested_schema: object | None = None + ) -> tuple[object, object]: + export = self._provider.__arrow_c_array__ + schema, array = ( + export() if requested_schema is None else export(requested_schema) + ) + pointer = cast("int", _get_capsule_pointer(schema, b"arrow_schema")) + borrowed = _ArrowSchema.from_buffer_copy(_ArrowSchema.from_address(pointer)) + borrowed.release = ctypes.cast(_release_borrowed_schema, ctypes.c_void_p).value + field = pa.Field._import_from_c(ctypes.addressof(borrowed)) + if isinstance(field.type, pa.StructType): + self.schema = pa.schema(list(field.type)) + return schema, array + + +@final +class _InspectArrowStream: + """Read the schema from the same stream capsule that Polars will consume.""" + + def __init__(self, provider: ArrowStreamExportable) -> None: + self._provider = provider + self.schema: pa.Schema | None = None + + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + export = self._provider.__arrow_c_stream__ + stream = export() if requested_schema is None else export(requested_schema) + pointer = cast("int", _get_capsule_pointer(stream, b"arrow_array_stream")) + # get_schema is the first member. Each call returns a separately owned + # schema and does not advance the stream. + get_schema = ctypes.cast( + ctypes.c_void_p.from_address(pointer), _GetStreamSchema + ) + schema = _ArrowSchema() + if status := get_schema(pointer, ctypes.byref(schema)): + raise pa.ArrowInvalid( + f"Arrow stream get_schema failed with status {status}" + ) + self.schema = pa.Schema._import_from_c(ctypes.addressof(schema)) + return stream + + +def _pandas_arrow_fields(columns: Iterable[object]) -> Iterator[pa.Field[pa.DataType]]: + """Read Arrow-backed pandas column declarations straight from their dtypes.""" + for column in columns: + if isinstance(column, (pd.Series, pd.Index)) and isinstance( + column.dtype, pd.ArrowDtype + ): + yield pa.field(str(column.name), column.dtype.pyarrow_dtype) + + +def dataframe_with_input_schema( + data: FrameInitTypes, +) -> tuple[pl.DataFrame, pa.Schema | None]: + """Run the usual Polars constructor and retain any original Arrow declarations. + + Polars may discard a native list or set identifier while importing, so the + source uses the incoming Arrow fields to check the declaration. For inputs + without Arrow declarations it can check the Arrow types it inferred later. + """ + schema = None + observed = None + fields: list[pa.Field[pa.DataType]] = [] + if isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): + schema = data.schema + elif isinstance(data, pa.StructArray): + schema = pa.schema(list(data.type)) + elif isinstance(data, pd.DataFrame): + fields.extend( + pa.field(str(name), dtype.pyarrow_dtype) + for name, dtype in data.dtypes.items() + if isinstance(dtype, pd.ArrowDtype) + ) + elif isinstance(data, Mapping): + for name, column in data.items(): + if isinstance(column, (pa.Array, pa.ChunkedArray)): + fields.append(pa.field(str(name), column.type)) + elif isinstance(column, (pd.Series, pd.Index)) and isinstance( + column.dtype, pd.ArrowDtype + ): + fields.append(pa.field(str(name), column.dtype.pyarrow_dtype)) + elif isinstance(data, Sequence): + if len(data) and isinstance(data[0], (pd.Series, pd.Index)): + fields.extend(_pandas_arrow_fields(data)) + elif not isinstance(data, (pl.DataFrame, pl.Series)): + if ( + not hasattr(data, "__arrow_c_stream__") + and isinstance(data, Iterable) + and not isinstance(data, Sized) + ): + data = _observe_pandas_iterator(data, fields) + elif callable(getattr(data, "__arrow_c_array__", None)): + observed = data = _InspectArrowArray(cast("ArrowArrayExportable", data)) + elif callable(getattr(data, "__arrow_c_stream__", None)): + observed = data = _InspectArrowStream(cast("ArrowStreamExportable", data)) + + def original_schema() -> pa.Schema | None: + if observed is not None: + return observed.schema + return pa.schema(fields) if fields else schema + + try: + frame = pl.DataFrame(data) + except (pa.ArrowException, pl.exceptions.PolarsError, pl.exceptions.PanicException): + # Polars can fail to import some types entirely (for example a union). + # Prefer the known declaration error if a field has a prohibited key. + if (declaration := original_schema()) is not None: + require_schema_without_narrow_float_keys(declaration, source_input=True) + raise + return frame, original_schema() + + +def _observe_pandas_iterator( + data: Iterable[object], fields: list[pa.Field[pa.DataType]] +) -> Iterator[object]: + """Observe schemas of streamed columns, leaving ordinary row data untouched.""" + iterator = iter(data) + end = object() + head = next(iterator, end) + if head is end: + return + items = chain((head,), iterator) + if isinstance(head, (pd.Series, pd.Index)): + for column in items: + fields.extend(_pandas_arrow_fields((column,))) + yield column + else: + yield from items + + +def require_polars_input_types(inferred: pa.Schema, original: pa.Schema | None) -> None: + """Check each input field once, using its original Arrow declaration if known.""" + if original is not None: + known = set(original.names) + inferred = pa.schema( + [ + *original, + *(field for field in inferred if field.name not in known), + ] + ) + require_schema_without_narrow_float_keys(inferred, source_input=True) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index d497eb537..10ef67fa5 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -25,13 +25,16 @@ from orcapod.semantic_types.narrow_float_keys import ( require_schema_without_narrow_float_keys, ) +from orcapod.core.sources.polars_input import ( + dataframe_with_input_schema, + require_polars_input_types, +) from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import hash_source_name from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, - dataframe_from_source_input, require_supported_nullable_types, ) from orcapod.core.streams.view import ( @@ -879,16 +882,18 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - df = dataframe_from_source_input(data) + df, input_schema = dataframe_with_input_schema(data) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", self.source_id, ) return None - return self._build_stream_from_df(df) + return self._build_stream_from_df(df, input_schema) - def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: + def _build_stream_from_df( + self, df: pl.DataFrame, input_schema: pa.Schema | None + ) -> ArrowTableStream | None: """Build an ``ArrowTableStream`` from a Polars DataFrame. Returns ``None`` on the infer-once path when the batch has zero rows and @@ -905,6 +910,7 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: df = df.with_columns([pl.from_arrow(c) for c in sub_table]) raw = df.to_arrow() + require_polars_input_types(raw.schema, input_schema) require_supported_nullable_types(raw.schema) arrow_table = arrow_utils.drop_system_columns(raw) @@ -951,6 +957,7 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: builder = SourceStreamBuilder(self.data_context, self.orcapod_config) result = builder.build( arrow_table, + input_types_checked=True, tag_columns=self._tag_columns, source_name=self._source_name, kind_part=self.kind_part(), diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dcce1443f..86b2ee89c 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -78,6 +78,7 @@ require_same_process, ) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError +from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError from orcapod.types import ColumnConfig, Condition from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils @@ -436,6 +437,10 @@ def __init__( ), data_tags=self._data_tags, ) + except NarrowFloatKeyError as exc: + raise NarrowFloatKeyError( + f"{location}, table {table_name!r}: {exc}" + ) from exc except ValueError as exc: raise ValueError(f"{location}, table {table_name!r}: {exc}") from exc self._table_schema: pa.Schema = arrow_utils.drop_system_columns( diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index cb8977079..90dcb4d6f 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -10,13 +10,10 @@ import datetime import json -from collections.abc import Callable, Collection, Iterable, Mapping, Sequence, Sized +from collections.abc import Collection, Sequence from dataclasses import dataclass -from itertools import chain, islice from typing import TYPE_CHECKING, Any, cast -import pandas as pd -import polars as pl import pyarrow as pa from orcapod.core.sources.source_ids import ( @@ -37,83 +34,11 @@ from orcapod.utils.schema_utils import compute_source_schema_hash if TYPE_CHECKING: - from polars._typing import ( - ArrowArrayExportable, - ArrowStreamExportable, - FrameInitTypes, - ) - from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext from orcapod.protocols.hashing_protocols import ArrowHasherProtocol -def dataframe_from_source_input(data: FrameInitTypes) -> pl.DataFrame: - """Convert source input to Polars, checking its Arrow schema at import. - - Polars can discard Arrow extension identities and field metadata on import. - Import Arrow providers with PyArrow first. For column containers, read the - exported Arrow columns together, leaving the conversion of other columns to - Polars so its dtype inference (including empty pandas columns) is preserved. - """ - schema = None - column_items: Iterable[tuple[object, object]] = () - if isinstance(data, (Mapping, pd.DataFrame)): - column_items = cast("Mapping[object, object]", data).items() - elif isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): - schema = data.schema - elif isinstance(data, Sequence): - if len(data) and isinstance(data[0], (pd.Series, pd.Index)): - column_items = ((column.name, column) for column in data) - elif not isinstance(data, (pl.DataFrame, pl.Series)): - if hasattr(data, "__arrow_c_array__"): - # PyArrow accepts a capsule provider without an explicit type. - array: pa.Array[pa.Scalar[pa.DataType]] = pa.array( # pyright: ignore[reportCallIssue] - cast("ArrowArrayExportable", data) # pyright: ignore[reportArgumentType] - ) - if isinstance(array.type, pa.StructType): - schema = pa.schema(list(array.type)) - data = array - elif hasattr(data, "__arrow_c_stream__"): - # Import the stream once and let Polars consume that same reader. - data = pa.RecordBatchReader.from_stream(cast("ArrowStreamExportable", data)) - schema = data.schema - elif isinstance(data, Iterable) and not isinstance(data, Sized): - # Polars also treats an iterator starting with a pandas column as a - # column container. Keep ordinary row iterators lazy. - iterator = iter(data) - head = tuple(islice(iterator, 1)) - restored = chain(head, iterator) - if head and isinstance(head[0], (pd.Series, pd.Index)): - columns = list(restored) - column_items = ((column.name, column) for column in columns) - data = iter(columns) - else: - data = restored - if schema is None: - fields: list[pa.Field[pa.DataType]] = [] - for name, column in column_items: - exported = ( - cast("object", column.array) - if isinstance(column, (pd.Series, pd.Index)) - else column - ) - if isinstance(exported, (pa.Array, pa.ChunkedArray)): - arrow_type = cast("pa.DataType", exported.type) - else: - export = cast( - "Callable[[], pa.Array[pa.Scalar[pa.DataType]] | pa.ChunkedArray[pa.Scalar[pa.DataType]]] | None", - getattr(exported, "__arrow_array__", None), - ) - if export is None: - continue - arrow_type = export().type - fields.append(pa.field(str(name), arrow_type)) - schema = pa.schema(fields) - require_schema_without_narrow_float_keys(schema, source_input=True) - return pl.DataFrame(data) - - def _contains_null_type(arrow_type: pa.DataType) -> bool: """Return whether an Arrow type contains the Null type at any depth.""" if isinstance(arrow_type, pa.BaseExtensionType): @@ -546,6 +471,7 @@ def build( *, hash_in_key_order: bool = False, inherited_types: bool = False, + input_types_checked: bool = False, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -567,6 +493,8 @@ def build( reordering. inherited_types: The table retains already-built upstream types, as when a derived source copies a tag into data. + input_types_checked: The source already checked the declarations using + the original Arrow types and metadata retained during import. record_id_columns: The key columns whose values identify a row, in key order: the row identifier is their canonical JSON (``key_row_identifier``), which follows the row regardless of its @@ -642,7 +570,7 @@ def build( ) # Nor is a dict keyed by, or a set of, float32 or float16 (ITL-1591): refused # here first, as the stream refuses it, before any key column or hash. - if not inherited_types: + if not inherited_types and not input_types_checked: require_schema_without_narrow_float_keys(table.schema, source_input=True) # 1. Drop system columns from raw input. diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 95496ba04..f774cb3c8 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -18,6 +18,8 @@ import dataclasses import json +import subprocess +import sys from collections.abc import Callable from pathlib import Path from typing import Any, cast @@ -896,6 +898,27 @@ def test_legacy_spiral_job_keeps_its_source_bound( ] +def test_direct_spiral_source_reports_narrow_schema(tmp_path: Path) -> None: + from orcapod.sources import SpiralDBTableSource + from tests.test_databases import fake_spiral_sdk + + with fake_spiral_sdk.install(tmp_path): + project = fake_spiral_sdk.ExternalProject("p") + table = project.create_table( + "default.pairs", key_schema=pa.schema([("id", pa.string())]) + ) + table.write( + pa.table( + { + "id": ["a"], + "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(pa.float32())), + } + ) + ) + with pytest.raises(NarrowFloatKeyError, match=r"(?s)table 'pairs'.*column 'k'"): + SpiralDBTableSource("p", "pairs", tag_columns="id", tag_only_columns=True) + + @pytest.mark.parametrize("declared_in_arrow", [False, True]) def test_pipeline_input_slot_refuses_declared_narrow_type( declared_in_arrow: bool, @@ -1103,6 +1126,82 @@ def test_arrow_sources_refuse_narrow_set_before_polars( DataFrameSource(table, tag_columns="id", source_id="dataframe") +def _polars_source_table(data: Any, *, polling: bool) -> pa.Table: + from unittest.mock import Mock + + from orcapod.sources import PollingSource + from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol + from orcapod.types import Cursor + + if polling: + impl = Mock(spec=DynamicSourceProtocol) + impl.schema.return_value = None + impl.fetch.return_value = (Cursor(value=1), data) + source = PollingSource(impl, "id", source_id="poll", record_id_columns="id") + else: + source = DataFrameSource( + data, tag_columns="id", source_id="dataframe", tag_only_columns=True + ) + return source.as_table() + + +@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) +def test_portable_native_list_of_pairs_keeps_its_rows(polling: bool) -> None: + written = subprocess.check_output( + [ + sys.executable, + "-c", + """ +from dataclasses import dataclass +import sys + +import numpy as np +import pyarrow as pa +from orcapod import contexts + +@dataclass(frozen=True) +class PortablePair: + key: np.float32 + value: int + +table = contexts.resolve_context(None).type_converter.python_dicts_to_arrow_table( + [{"id": 1, "k": [PortablePair(np.float32(0.5), 1)]}], + python_schema={"id": int, "k": list[PortablePair]}, +) +with pa.ipc.new_file(sys.stdout.buffer, table.schema) as writer: + writer.write(table) +""", + ] + ) + table = pa.ipc.open_file(pa.BufferReader(written)).read_all() + metadata = table.schema.field("k").metadata + assert metadata is not None + assert bytes(metadata[b"ARROW:extension:name"]).startswith(b"list[") + result = _polars_source_table(table, polling=polling) + assert result["k"].type == table["k"].type + assert result["k"].to_pylist() == [[{"key": 0.5, "value": 1}]] + + +@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) +def test_pandas_python_string_is_exported_once( + polling: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + data = pd.DataFrame( + {"id": [1, 2], "k": pd.Series(["a", None], dtype="string[python]")} + ) + string_array = pd.arrays.StringArray + export = string_array.__arrow_array__ + exports = [] + + def count_export(array, *args, **kwargs): + exports.append(len(array)) + return export(array, *args, **kwargs) + + monkeypatch.setattr(string_array, "__arrow_array__", count_export) + assert _polars_source_table(data, polling=polling)["k"].to_pylist() == ["a", None] + assert exports == [2] + + @pytest.mark.parametrize( "python_narrow,arrow_narrow", [(True, True), (True, False), (False, True)] ) @@ -1146,6 +1245,7 @@ def test_datagram_checks_narrow_arrow_declaration_before_values( "reader", "mapping", "capsule", + "array_capsule", "pandas", "pandas_nested", "pandas_in_mapping", @@ -1171,6 +1271,10 @@ class ArrowStream: def __arrow_c_stream__(self, requested_schema=None): return table.__arrow_c_stream__(requested_schema) + class ArrowArray: + def __arrow_c_array__(self, requested_schema=None): + return table.to_batches()[0].__arrow_c_array__(requested_schema) + if input_kind == "mapping": data = {"id": [1], "k": table["k"]} elif input_kind == "reader": @@ -1194,6 +1298,8 @@ def __arrow_c_stream__(self, requested_schema=None): data = pd.DataFrame( {"id": [1], "k": pd.Series(nested, dtype=pd.ArrowDtype(nested.type))} ) + elif input_kind == "array_capsule": + data = ArrowArray() else: data = ArrowStream() From a442fb85462e1c9fcedaa5da40671de9d8cdcb2d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:08:02 -0800 Subject: [PATCH 10/32] fix(sources): retain Arrow declarations in nested column mappings --- changelog.d/ITL-1591.md | 4 +- docs/dev/design_issues/ITL-1591-NFK1.md | 5 +- src/orcapod/core/sources/polars_input.py | 58 ++++++++++++++---- src/orcapod/core/sources/polling_source.py | 3 +- .../test_narrow_float_keys_refused.py | 60 +++++++++++++++++-- 5 files changed, 108 insertions(+), 22 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index fbb2525a6..e68d130f3 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -10,8 +10,8 @@ Arrow schema, a pipeline's declared input slot, a datagram's Python schema or explicitly typed new column, and a function pod's parameters and outputs when the pod is defined (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and - column mappings with Arrow arrays or Arrow-backed pandas Series given to - Polars-backed sources, Arrow-backed pandas frames and sequences of Series, + nested and top-level column mappings with Arrow arrays or Arrow-backed pandas Series + given to Polars-backed sources, Arrow-backed pandas frames and sequences of Series, and explicit Arrow schemas given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index d28b71445..42adb2412 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -26,8 +26,9 @@ saved source declaration is restored. The converter checks explicit Arrow declar before converting Python rows, and checks Python set types even without a logical type registry. The Polars-backed sources keep the incoming Arrow declarations for the schema check when importing arrays or streams, including Arrow-backed pandas columns passed in -mappings, sequences and iterators. The check uses those declarations and inferred -Arrow fields before building the stream. The input data follows its usual conversion path. +column mappings at any depth, sequences and iterators. The check uses those declarations +and inferred Arrow fields before building the stream. The input data follows its usual +conversion path. The saved-source resolver keeps input types when the rebuilt source matches its saved pipeline hash. A narrow key in a changed input schema raises a declaration error during job load. Saved pipeline input slots record diff --git a/src/orcapod/core/sources/polars_input.py b/src/orcapod/core/sources/polars_input.py index a9c2600ec..0b4b30166 100644 --- a/src/orcapod/core/sources/polars_input.py +++ b/src/orcapod/core/sources/polars_input.py @@ -117,16 +117,50 @@ def _pandas_arrow_fields(columns: Iterable[object]) -> Iterator[pa.Field[pa.Data yield pa.field(str(column.name), column.dtype.pyarrow_dtype) +PolarsInputSchema = pa.Schema | Mapping[str, object] | None + + +def _mapping_arrow_fields( + columns: Mapping[str, object], inferred: Iterable[pa.Field[pa.DataType]] +) -> Iterable[pa.Field[pa.DataType]]: + """Overlay Arrow declarations on the inferred fields of a column mapping.""" + fields = {field.name: field for field in inferred} + for name, column in columns.items(): + name = str(name) + if isinstance(column, (pa.Array, pa.ChunkedArray)): + fields[name] = pa.field(name, column.type) + elif isinstance(column, (pd.Series, pd.Index)) and isinstance( + column.dtype, pd.ArrowDtype + ): + fields[name] = pa.field(name, column.dtype.pyarrow_dtype) + elif isinstance(column, dict): + # Polars turns nested column mappings into structs. Keep original + # Arrow types at their leaves and inferred types for their siblings. + field = fields.get(name) + field_type = field.type if field is not None else None + if field_type is not None and not isinstance(field_type, pa.StructType): + continue + children = _mapping_arrow_fields( + column, () if field_type is None else field_type + ) + if children: + struct = pa.struct(children) + fields[name] = ( + pa.field(name, struct) if field is None else field.with_type(struct) + ) + return fields.values() + + def dataframe_with_input_schema( data: FrameInitTypes, -) -> tuple[pl.DataFrame, pa.Schema | None]: +) -> tuple[pl.DataFrame, PolarsInputSchema]: """Run the usual Polars constructor and retain any original Arrow declarations. Polars may discard a native list or set identifier while importing, so the source uses the incoming Arrow fields to check the declaration. For inputs without Arrow declarations it can check the Arrow types it inferred later. """ - schema = None + schema: PolarsInputSchema = None observed = None fields: list[pa.Field[pa.DataType]] = [] if isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): @@ -140,13 +174,7 @@ def dataframe_with_input_schema( if isinstance(dtype, pd.ArrowDtype) ) elif isinstance(data, Mapping): - for name, column in data.items(): - if isinstance(column, (pa.Array, pa.ChunkedArray)): - fields.append(pa.field(str(name), column.type)) - elif isinstance(column, (pd.Series, pd.Index)) and isinstance( - column.dtype, pd.ArrowDtype - ): - fields.append(pa.field(str(name), column.dtype.pyarrow_dtype)) + schema = data elif isinstance(data, Sequence): if len(data) and isinstance(data[0], (pd.Series, pd.Index)): fields.extend(_pandas_arrow_fields(data)) @@ -162,7 +190,7 @@ def dataframe_with_input_schema( elif callable(getattr(data, "__arrow_c_stream__", None)): observed = data = _InspectArrowStream(cast("ArrowStreamExportable", data)) - def original_schema() -> pa.Schema | None: + def original_schema() -> PolarsInputSchema: if observed is not None: return observed.schema return pa.schema(fields) if fields else schema @@ -173,7 +201,7 @@ def original_schema() -> pa.Schema | None: # Polars can fail to import some types entirely (for example a union). # Prefer the known declaration error if a field has a prohibited key. if (declaration := original_schema()) is not None: - require_schema_without_narrow_float_keys(declaration, source_input=True) + require_polars_input_types(pa.schema([]), declaration) raise return frame, original_schema() @@ -196,9 +224,13 @@ def _observe_pandas_iterator( yield from items -def require_polars_input_types(inferred: pa.Schema, original: pa.Schema | None) -> None: +def require_polars_input_types( + inferred: pa.Schema, original: PolarsInputSchema +) -> None: """Check each input field once, using its original Arrow declaration if known.""" - if original is not None: + if isinstance(original, Mapping): + inferred = pa.schema(_mapping_arrow_fields(original, inferred)) + elif original is not None: known = set(original.names) inferred = pa.schema( [ diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 10ef67fa5..d2c4d6aec 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -64,6 +64,7 @@ if TYPE_CHECKING: from polars._typing import FrameInitTypes + from orcapod.core.sources.polars_input import PolarsInputSchema from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.types import Schema @@ -892,7 +893,7 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: return self._build_stream_from_df(df, input_schema) def _build_stream_from_df( - self, df: pl.DataFrame, input_schema: pa.Schema | None + self, df: pl.DataFrame, input_schema: PolarsInputSchema ) -> ArrowTableStream | None: """Build an ``ArrowTableStream`` from a Polars DataFrame. diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index f774cb3c8..a7d9cfcb4 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -1146,7 +1146,12 @@ def _polars_source_table(data: Any, *, polling: bool) -> pa.Table: @pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) -def test_portable_native_list_of_pairs_keeps_its_rows(polling: bool) -> None: +@pytest.mark.parametrize( + "nested_mapping", [False, True], ids=["table", "nested-mapping"] +) +def test_portable_native_list_of_pairs_keeps_its_rows( + polling: bool, nested_mapping: bool +) -> None: written = subprocess.check_output( [ sys.executable, @@ -1177,9 +1182,56 @@ class PortablePair: metadata = table.schema.field("k").metadata assert metadata is not None assert bytes(metadata[b"ARROW:extension:name"]).startswith(b"list[") - result = _polars_source_table(table, polling=polling) - assert result["k"].type == table["k"].type - assert result["k"].to_pylist() == [[{"key": 0.5, "value": 1}]] + pairs = [{"key": 0.5, "value": 1}] + if nested_mapping: + struct = pa.StructArray.from_arrays( + [table["k"].combine_chunks()], fields=[table.schema.field("k")] + ) + data = {"id": [1], "outer": {"nested": struct, "other": [2]}} + result = _polars_source_table(data, polling=polling) + assert result["outer"].to_pylist() == [{"nested": {"k": pairs}, "other": 2}] + else: + result = _polars_source_table(table, polling=polling) + assert result["k"].type == table["k"].type + assert result["k"].to_pylist() == [pairs] + + +@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) +@pytest.mark.parametrize("width", NARROW, ids=str) +@pytest.mark.parametrize( + "shape", ["array", "pandas", "set-in-struct", "set-in-list", "map-in-struct"] +) +def test_nested_mapping_checks_arrow_declarations( + polling: bool, width: pa.DataType, shape: str +) -> None: + set_field = _set_storage_field(width) + set_storage = pa.array([[0.5]], type=set_field.type) + diagnostic = "set element type" + if shape == "set-in-struct": + column = pa.StructArray.from_arrays([set_storage], fields=[set_field]) + elif shape == "set-in-list": + column = pa.LargeListArray.from_arrays( + pa.array([0, 1], type=pa.int64()), + set_storage, + type=pa.large_list(set_field), + ) + elif shape == "map-in-struct": + mapping = pa.array([[(0.5, 1)]], type=pa.map_(width, pa.int64())) + column = pa.StructArray.from_arrays([mapping], names=["mapping"]) + diagnostic = "dict key type" + else: + extension = _live_set(width) + array = pa.ExtensionArray.from_storage(extension, set_storage) + column = ( + pd.Series(array, dtype=pd.ArrowDtype(extension)) + if shape == "pandas" + else array + ) + data = {"id": [1], "outer": {"column": column}} + with pytest.raises( + NarrowFloatKeyError, match=f"column 'outer'.*{diagnostic} {width}" + ): + _polars_source_table(data, polling=polling) @pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) From 926881d8c8b3bc7f719ed3d0bb2630ae34868e0b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:16:07 -0800 Subject: [PATCH 11/32] fix(semantic-types): reject narrow storage in registered set elements --- changelog.d/ITL-1591.md | 3 +- docs/dev/design_issues/ITL-1591-NFK1.md | 5 +- .../semantic_types/universal_converter.py | 4 + .../test_narrow_float_keys_refused.py | 79 ++++++++++++++++++- 4 files changed, 87 insertions(+), 4 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index e68d130f3..0897ef733 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -9,7 +9,8 @@ column and the key or element type, where the type is declared: a source's Python or Arrow schema, a pipeline's declared input slot, a datagram's Python schema or explicitly typed new column, and a function pod's parameters and outputs when the pod is defined - (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and + (`-> dict[np.float32, int]`, `set[np.float32]`), including set elements with registered + logical types stored as `float32` or `float16`. This also covers Arrow readers and nested and top-level column mappings with Arrow arrays or Arrow-backed pandas Series given to Polars-backed sources, Arrow-backed pandas frames and sequences of Series, and explicit Arrow schemas diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 42adb2412..15645c1b7 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -23,8 +23,9 @@ and a function pod's declared inputs and outputs, when the pod is defined). The builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before source value conversion, when a datagram adds a column with a declared type, and when a saved source declaration is restored. The converter checks explicit Arrow declarations -before converting Python rows, and checks Python set types even without a logical type -registry. The Polars-backed sources keep the incoming Arrow declarations for the schema check +before converting Python rows. It checks Python set elements backed by registered logical +types as well as plain elements, including when no logical type registry is configured. +The Polars-backed sources keep the incoming Arrow declarations for the schema check when importing arrays or streams, including Arrow-backed pandas columns passed in column mappings at any depth, sequences and iterators. The check uses those declarations and inferred Arrow fields before building the stream. The input data follows its usual diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 3c01a1afe..793925dbc 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -595,6 +595,10 @@ def _make_or_get_list_logical_type( """ from orcapod.logical_types.list_logical_type_factory import ListLogicalType + if is_set: + require_no_narrow_float_keys( + element_logical_type.get_arrow_extension_type(), is_set_element=True + ) prefix = "set" if is_set else "list" list_ext_name = f"{prefix}[{element_logical_type.logical_type_name}]" diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index a7d9cfcb4..a376e9508 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -22,13 +22,14 @@ import sys from collections.abc import Callable from pathlib import Path -from typing import Any, cast +from typing import Any, cast, final import numpy as np import pandas as pd import polars as pl import pyarrow as pa import pytest +from typing_extensions import override from orcapod import contexts, function_pod from orcapod.core.datagrams import Data, Datagram, Tag @@ -61,6 +62,82 @@ def _dict_of(key: pa.DataType, value: pa.DataType = pa.int64()) -> pa.DataType: return pa.large_list(pa.struct([("key", key), ("value", value)])) +@pytest.mark.parametrize( + ("storage_type", "refused"), + [(pa.float16(), True), (pa.float32(), True), (pa.float64(), False)], + ids=["float16", "float32", "float64"], +) +@pytest.mark.parametrize("entry_point", ["convert", "register", "pod"]) +def test_registered_float_storage_set_declaration( + storage_type: pa.DataType, refused: bool, entry_point: str +) -> None: + """Python declarations check the storage of a registered set element.""" + from orcapod.logical_types.base_logical_type import BaseLogicalType + from orcapod.logical_types.protocols import TypeConverterProtocol + from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, + ) + from orcapod.semantic_types.universal_converter import UniversalTypeConverter + + @dataclasses.dataclass(frozen=True) + class Measurement: + magnitude: float + + name = f"test.narrow_set.measurement.{storage_type}.{entry_point}" + arrow_extension = cast( + "Callable[[], pa.ExtensionType]", make_arrow_extension_type(name, storage_type) + )() + polars_extension = cast( + "Callable[[], pl.BaseExtension]", make_polars_extension_type(name, storage_type) + )() + + @final + class LogicalMeasurement(BaseLogicalType): + logical_type_name = name + python_type = Measurement + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + return arrow_extension + + def get_polars_extension_type(self) -> pl.BaseExtension: + return polars_extension + + def python_to_storage( + self, value: Measurement, converter: TypeConverterProtocol | None + ) -> float: + return value.magnitude + + def storage_to_python( + self, storage_value: float, converter: TypeConverterProtocol | None + ) -> Measurement: + return Measurement(storage_value) + + converter = contexts.resolve_context(None).type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(LogicalMeasurement()) + + def declare(annotation: type) -> object: + if entry_point == "convert": + return converter.python_type_to_arrow_type(annotation) + if entry_point == "register": + return converter.register_python_class(annotation) + + def produce(x: int) -> set[Measurement]: + raise AssertionError("never called") + + produce.__annotations__["return"] = annotation + return function_pod(output_keys="v")(produce) + + assert declare(list[Measurement]) is not None + if refused: + with pytest.raises(NarrowFloatKeyError, match="set element"): + declare(set[Measurement]) + else: + assert declare(set[Measurement]) is not None + + def _set_storage_field(element: pa.DataType) -> pa.Field[Any]: """A set in its storage form: the storage type, the identifier in field metadata.""" live = _live_set(element) From 5de7201379d49b15ba1ce8f6f8fc24837bd66cf4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 14:05:48 -0800 Subject: [PATCH 12/32] fix(semantic-types): preserve inherited and inferred logical sets --- changelog.d/ITL-1591.md | 3 +- docs/dev/design_issues/ITL-1591-NFK1.md | 4 +- .../semantic_types/universal_converter.py | 4 - .../test_narrow_float_keys_refused.py | 173 +++++++++++++----- 4 files changed, 135 insertions(+), 49 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 0897ef733..e68d130f3 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -9,8 +9,7 @@ column and the key or element type, where the type is declared: a source's Python or Arrow schema, a pipeline's declared input slot, a datagram's Python schema or explicitly typed new column, and a function pod's parameters and outputs when the pod is defined - (`-> dict[np.float32, int]`, `set[np.float32]`), including set elements with registered - logical types stored as `float32` or `float16`. This also covers Arrow readers and + (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and nested and top-level column mappings with Arrow arrays or Arrow-backed pandas Series given to Polars-backed sources, Arrow-backed pandas frames and sequences of Series, and explicit Arrow schemas diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 15645c1b7..cc01b6b78 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -23,8 +23,8 @@ and a function pod's declared inputs and outputs, when the pod is defined). The builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before source value conversion, when a datagram adds a column with a declared type, and when a saved source declaration is restored. The converter checks explicit Arrow declarations -before converting Python rows. It checks Python set elements backed by registered logical -types as well as plain elements, including when no logical type registry is configured. +before converting Python rows and checks plain Python set element types, including when +no logical type registry is configured. The Polars-backed sources keep the incoming Arrow declarations for the schema check when importing arrays or streams, including Arrow-backed pandas columns passed in column mappings at any depth, sequences and iterators. The check uses those declarations diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 793925dbc..3c01a1afe 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -595,10 +595,6 @@ def _make_or_get_list_logical_type( """ from orcapod.logical_types.list_logical_type_factory import ListLogicalType - if is_set: - require_no_narrow_float_keys( - element_logical_type.get_arrow_extension_type(), is_set_element=True - ) prefix = "set" if is_set else "list" list_ext_name = f"{prefix}[{element_logical_type.logical_type_name}]" diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index a376e9508..513170300 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -33,6 +33,7 @@ from orcapod import contexts, function_pod from orcapod.core.datagrams import Data, Datagram, Tag +from orcapod.core.operators import Index from orcapod.core.sources import ( ArrowTableSource, DataFrameSource, @@ -40,7 +41,15 @@ DictSource, ListSource, ) +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.list_logical_type_factory import ListLogicalType +from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.logical_types.registry import ( + make_arrow_extension_type, + make_polars_extension_type, +) from orcapod.semantic_types.narrow_float_keys import ( NARROW_FLOAT_KEYS_NOT_SUPPORTED, NarrowFloatKeyError, @@ -49,6 +58,7 @@ require_schema_without_narrow_float_keys, ) from orcapod.semantic_types.nested_storage import dict_entry_fields +from orcapod.semantic_types.universal_converter import UniversalTypeConverter NOT_SUPPORTED = NARROW_FLOAT_KEYS_NOT_SUPPORTED @@ -62,29 +72,14 @@ def _dict_of(key: pa.DataType, value: pa.DataType = pa.int64()) -> pa.DataType: return pa.large_list(pa.struct([("key", key), ("value", value)])) -@pytest.mark.parametrize( - ("storage_type", "refused"), - [(pa.float16(), True), (pa.float32(), True), (pa.float64(), False)], - ids=["float16", "float32", "float64"], -) -@pytest.mark.parametrize("entry_point", ["convert", "register", "pod"]) -def test_registered_float_storage_set_declaration( - storage_type: pa.DataType, refused: bool, entry_point: str -) -> None: - """Python declarations check the storage of a registered set element.""" - from orcapod.logical_types.base_logical_type import BaseLogicalType - from orcapod.logical_types.protocols import TypeConverterProtocol - from orcapod.logical_types.registry import ( - make_arrow_extension_type, - make_polars_extension_type, - ) - from orcapod.semantic_types.universal_converter import UniversalTypeConverter - - @dataclasses.dataclass(frozen=True) - class Measurement: - magnitude: float - - name = f"test.narrow_set.measurement.{storage_type}.{entry_point}" +def _make_logical_type( + name: str, + element_class: type, + storage_type: pa.DataType, + encode: Callable[[Any], Any], + decode: Callable[[Any], Any], +) -> BaseLogicalType: + """Build a custom logical type using the given storage conversions.""" arrow_extension = cast( "Callable[[], pa.ExtensionType]", make_arrow_extension_type(name, storage_type) )() @@ -93,9 +88,9 @@ class Measurement: )() @final - class LogicalMeasurement(BaseLogicalType): + class LogicalElement(BaseLogicalType): logical_type_name = name - python_type = Measurement + python_type = element_class @override def get_arrow_extension_type(self) -> pa.ExtensionType: @@ -105,18 +100,39 @@ def get_polars_extension_type(self) -> pl.BaseExtension: return polars_extension def python_to_storage( - self, value: Measurement, converter: TypeConverterProtocol | None - ) -> float: - return value.magnitude + self, value: Any, converter: TypeConverterProtocol | None + ) -> Any: + return encode(value) def storage_to_python( - self, storage_value: float, converter: TypeConverterProtocol | None - ) -> Measurement: - return Measurement(storage_value) + self, storage_value: Any, converter: TypeConverterProtocol | None + ) -> Any: + return decode(storage_value) + + return LogicalElement() + - converter = contexts.resolve_context(None).type_converter +@dataclasses.dataclass(frozen=True) +class _Measurement: + magnitude: float + + +def _logical_measurement(name: str, storage_type: pa.DataType) -> BaseLogicalType: + """Represent a measurement by its magnitude in Arrow.""" + return _make_logical_type( + name, _Measurement, storage_type, lambda value: value.magnitude, _Measurement + ) + + +@pytest.mark.parametrize("entry_point", ["convert", "register", "pod"]) +def test_registered_float64_storage_set_declaration(entry_point: str) -> None: + """Python declarations accept registered elements with float64 storage.""" + context = contexts.create_registry().get_context("v1") + converter = context.type_converter assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type(LogicalMeasurement()) + converter.register_logical_type( + _logical_measurement(f"test.wide_set.measurement.{entry_point}", pa.float64()) + ) def declare(annotation: type) -> object: if entry_point == "convert": @@ -124,18 +140,93 @@ def declare(annotation: type) -> object: if entry_point == "register": return converter.register_python_class(annotation) - def produce(x: int) -> set[Measurement]: + def produce(x: int) -> set[_Measurement]: raise AssertionError("never called") produce.__annotations__["return"] = annotation - return function_pod(output_keys="v")(produce) + return function_pod(output_keys="v", data_context=context)(produce) - assert declare(list[Measurement]) is not None - if refused: - with pytest.raises(NarrowFloatKeyError, match="set element"): - declare(set[Measurement]) - else: - assert declare(set[Measurement]) is not None + assert declare(list[_Measurement]) is not None + assert declare(set[_Measurement]) is not None + + +def test_set_of_logical_sequences_preserves_repeated_coordinates() -> None: + """A logical sequence represented by key/value structs can appear in a set.""" + + @dataclasses.dataclass(frozen=True) + class Frames: + events: tuple[tuple[float, int], ...] + + converter = contexts.create_registry().get_context("v1").type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type( + _make_logical_type( + "test.narrow_set.frames", + Frames, + _dict_of(pa.float32()), + lambda frames: [ + {"key": key, "value": value} for key, value in frames.events + ], + lambda rows: Frames(tuple((row["key"], row["value"]) for row in rows)), + ) + ) + rows = [{"v": {Frames(((0.5, 1), (0.5, 2)))}}] + table = converter.python_dicts_to_arrow_table(rows, {"v": set[Frames]}) + assert converter.arrow_table_to_python_dicts(table) == rows + + +@pytest.mark.parametrize("storage_type", [pa.float16(), pa.float32()], ids=str) +def test_index_preserves_empty_logical_set_column(storage_type: pa.DataType) -> None: + """An out-of-bounds Index retains the native set type in its empty result.""" + context = contexts.create_registry().get_context("v1") + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + logical = _logical_measurement( + f"test.narrow_set.indexed.{storage_type}", storage_type + ) + converter.register_logical_type(logical) + inner = ListLogicalType(logical, is_set=True) + outer = ListLogicalType(inner) + converter.register_logical_type(outer) + set_type = inner.get_arrow_extension_type() + list_type = outer.get_arrow_extension_type() + assert ( + converter.get_logical_type_by_arrow_extension_name(set_type.extension_name) + is None + ) + values = pa.ExtensionArray.from_storage( + list_type, pa.array([[[0.5, 0.75]]], type=list_type.storage_type) + ) + table = pa.Table.from_arrays( + [pa.array([1]), values], + schema=pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("x", list_type, nullable=False), + ] + ), + ) + stream = ArrowTableStream(table, tag_columns=["id"], data_context=context) + + result = Index("x", 1).static_process(stream).as_table() + assert result.num_rows == 0 + result_type = result.schema.field("x").type + assert isinstance(result_type, pa.ExtensionType) + assert result_type.extension_name == set_type.extension_name + assert result_type.storage_type == set_type.storage_type + assert result_type.__arrow_ext_serialize__() == set_type.__arrow_ext_serialize__() + + +def test_schema_free_conversion_accepts_inferred_logical_set() -> None: + """Schema inference can round-trip a set of float32-backed logical elements.""" + converter = contexts.create_registry().get_context("v1").type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type( + _logical_measurement("test.narrow_set.inferred", pa.float32()) + ) + rows = [{"v": {_Measurement(0.5)}}] + table = converter.python_dicts_to_arrow_table(rows) + assert converter.arrow_table_to_python_dicts(table) == rows def _set_storage_field(element: pa.DataType) -> pa.Field[Any]: From 22a7fcb87e4fa7da0334982dfb6d8f6559c85aaf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 14:12:40 -0800 Subject: [PATCH 13/32] test(semantic-types): type logical test fixtures by their protocol --- tests/test_semantic_types/test_narrow_float_keys_refused.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 513170300..4c9e33192 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -45,7 +45,7 @@ from orcapod.errors import InputValidationError from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.list_logical_type_factory import ListLogicalType -from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.logical_types.protocols import LogicalTypeProtocol, TypeConverterProtocol from orcapod.logical_types.registry import ( make_arrow_extension_type, make_polars_extension_type, @@ -78,7 +78,7 @@ def _make_logical_type( storage_type: pa.DataType, encode: Callable[[Any], Any], decode: Callable[[Any], Any], -) -> BaseLogicalType: +) -> LogicalTypeProtocol: """Build a custom logical type using the given storage conversions.""" arrow_extension = cast( "Callable[[], pa.ExtensionType]", make_arrow_extension_type(name, storage_type) @@ -117,7 +117,7 @@ class _Measurement: magnitude: float -def _logical_measurement(name: str, storage_type: pa.DataType) -> BaseLogicalType: +def _logical_measurement(name: str, storage_type: pa.DataType) -> LogicalTypeProtocol: """Represent a measurement by its magnitude in Arrow.""" return _make_logical_type( name, _Measurement, storage_type, lambda value: value.magnitude, _Measurement From b55bec48f5bd89b9126b69d209ae64935a76a95c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 14:33:18 -0800 Subject: [PATCH 14/32] test(semantic-types): register the wide set fixture explicitly --- tests/test_semantic_types/test_narrow_float_keys_refused.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 4c9e33192..e954ed3c6 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -642,6 +642,9 @@ def test_the_set_reproduction_no_longer_loses_an_element(self) -> None: def test_a_float64_key_and_element_from_an_arrow_schema_keep_every_entry( self, ) -> None: + # Register the native set decoder in the context used by source rows. + converter = contexts.resolve_context(None).type_converter + set_type = converter.register_python_class(set[float]) source = DictSource( [{"id": 1, "k": {1e-50: 1, 2e-50: 2}, "s": {1e-50, 2e-50}, "h": 0.5}], tag_columns=["id"], @@ -650,7 +653,7 @@ def test_a_float64_key_and_element_from_an_arrow_schema_keep_every_entry( [ pa.field("id", pa.int64()), pa.field("k", _dict_of(pa.float64())), - pa.field("s", _live_set(pa.float64())), + pa.field("s", set_type), pa.field("h", pa.float32()), ] ), From 9c7326e2e7574c8693f0a2b0faa600b573c5c8bd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 14:35:16 -0800 Subject: [PATCH 15/32] test(semantic-types): narrow the wide set fixture converter type --- tests/test_semantic_types/test_narrow_float_keys_refused.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index e954ed3c6..d0a639099 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -644,6 +644,7 @@ def test_a_float64_key_and_element_from_an_arrow_schema_keep_every_entry( ) -> None: # Register the native set decoder in the context used by source rows. converter = contexts.resolve_context(None).type_converter + assert isinstance(converter, UniversalTypeConverter) set_type = converter.register_python_class(set[float]) source = DictSource( [{"id": 1, "k": {1e-50: 1, 2e-50: 2}, "s": {1e-50, 2e-50}, "h": 0.5}], From 0dc177d8141611569f321eac37108ccdc1e7319d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 15:39:43 -0800 Subject: [PATCH 16/32] fix(serialization): preserve legacy narrow keys in saved schemas --- .zed/rules | 3 +- CLAUDE.md | 3 +- changelog.d/ITL-1591.md | 8 +- docs/dev/design_issues/ITL-1591-NFK1.md | 15 ++-- src/orcapod/core/nodes/source_node.py | 12 +-- src/orcapod/pipeline/graph.py | 8 -- src/orcapod/pipeline/serialization.py | 40 ++------- .../test_narrow_float_keys_refused.py | 90 +++++++++++-------- 8 files changed, 76 insertions(+), 103 deletions(-) diff --git a/.zed/rules b/.zed/rules index 039f1c70f..1a764ff1d 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1565,7 +1565,8 @@ data. The rules: applies it to every dict and set type it builds (sources' Python schemas, datagrams, user-class fields, a function pod's inputs and outputs when the pod is defined). `SourceStreamBuilder.build` checks schemas at source ingestion, and explicit Arrow - declarations are checked before conversion or on restore. A raw `ArrowTableStream` and + declarations are checked before conversion. Saved schema text is read with its original + types by the serialization helpers. A raw `ArrowTableStream` and Arrow-held datagrams carry already-built schemas, including operator and cached results. A list of structs produced by aggregation can have the same Arrow shape as a dict. A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an diff --git a/CLAUDE.md b/CLAUDE.md index a90635501..4d905810c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1613,7 +1613,8 @@ data. The rules: applies it to every dict and set type it builds (sources' Python schemas, datagrams, user-class fields, a function pod's inputs and outputs when the pod is defined). `SourceStreamBuilder.build` checks schemas at source ingestion, and explicit Arrow - declarations are checked before conversion or on restore. A raw `ArrowTableStream` and + declarations are checked before conversion. Saved schema text is read with its original + types by the serialization helpers. A raw `ArrowTableStream` and Arrow-held datagrams carry already-built schemas, including operator and cached results. A list of structs produced by aggregation can have the same Arrow shape as a dict. A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index e68d130f3..917398d70 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -17,10 +17,10 @@ value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain column, a list element, a struct field and a dict value. -- Loading a saved job preserves source bindings whose rebuilt inputs match the saved - pipeline identity, including legacy float32 or float16 keys in Delta and SpiralDB - tables. A narrow key in a changed input schema raises `NarrowFloatKeyError` during - load. +- Loading saved jobs and blueprints preserves legacy schema types, including float32 + or float16 keys and set elements. Saved jobs also preserve bindings whose rebuilt + inputs match the saved pipeline identity, including Delta and SpiralDB tables. A narrow + key in a changed live input schema raises `NarrowFloatKeyError` during load. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index cc01b6b78..6de813c98 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -21,10 +21,9 @@ types that reads no value. One rule, `semantic_types/narrow_float_keys.py` dict and set type it builds (so a source's Python schema, a datagram's, a user-class field and a function pod's declared inputs and outputs, when the pod is defined). The source builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before -source value conversion, when a datagram adds a column with a declared type, and when a -saved source declaration is restored. The converter checks explicit Arrow declarations -before converting Python rows and checks plain Python set element types, including when -no logical type registry is configured. +source value conversion and when a datagram adds a column with a declared type. The +converter checks explicit Arrow declarations before converting Python rows and checks +plain Python set element types, including when no logical type registry is configured. The Polars-backed sources keep the incoming Arrow declarations for the schema check when importing arrays or streams, including Arrow-backed pandas columns passed in column mappings at any depth, sequences and iterators. The check uses those declarations @@ -32,10 +31,10 @@ and inferred Arrow fields before building the stream. The input data follows its conversion path. The saved-source resolver keeps input types when the rebuilt source matches its saved pipeline hash. A narrow key in a changed input schema raises a declaration error during -job load. Saved pipeline input slots record -whether their schemas came from a stream, so loading a blueprint can retain an operator -result's types. Public slot declarations check any Arrow override and each explicitly -declared Python role, including when the other Python role comes from a bound stream. +job load. Schema readers preserve the types recorded in saved jobs, proxies and +blueprints, including legacy narrow float keys and elements. Public slot declarations +check any Arrow override and each explicitly declared Python role, including when the +other Python role comes from a bound stream. A dict declaration uses the converter's dict shape (`nested_storage.dict_entry_fields`) or an Arrow map. Plain narrow-float columns, list elements, struct fields and dict values remain accepted. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 58d760f3f..ba5e68c85 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -588,7 +588,6 @@ def __init__( require_python_schema_without_narrow_float_keys(tag_schema, converter) require_python_schema_without_narrow_float_keys(data_schema, converter) self._name = name - self._inherited_types = _inherited_types self._tag_schema = tag_schema self._data_schema = data_schema # The Arrow types of the slot's columns, which its identity is built from @@ -622,7 +621,6 @@ def _keep_saved( content_hash: str | None, saved_types: Mapping[str, Mapping[str, str]], nullable: Mapping[str, Collection[str]], - inherited_types: bool, ) -> None: """Keep what a saved job recorded for this slot (ITL-1138, ITL-640). @@ -640,13 +638,11 @@ def _keep_saved( content_hash: The saved content hash text, or ``None`` if not saved. saved_types: The saved type texts, ``{"tag": {...}, "data": {...}}``. nullable: The saved nullable column names per role. - inherited_types: The saved types came from an upstream result. """ if pipeline_hash is not None: self._saved_pipeline_hash = ContentHash.from_string(pipeline_hash) if content_hash is not None: self._saved_content_hash = ContentHash.from_string(content_hash) - self._inherited_types = inherited_types if self._given_arrow_schemas is None or self._pending_columns(): # One state: the texts hold the types, and the Arrow pair and the Python # types are both derived from them by ``_resolve``, together. @@ -668,7 +664,6 @@ def _take_saved_state_of(self, other: "SourceNodeBase") -> None: name. """ self._saved_pipeline_hash = other._saved_pipeline_hash - self._inherited_types = other._inherited_types self._given_arrow_schemas = other._given_arrow_schemas if self._name == other._name: self._label = other._label @@ -716,12 +711,7 @@ def _resolve(self) -> bool: arrow: list[pa.Schema] = [] for role in ("tag", "data"): names = texts["nullable"][role] - python[role] = deserialize_schema( - texts[role], - converter, - nullable=names, - inherited_types=self._inherited_types, - ) + python[role] = deserialize_schema(texts[role], converter, nullable=names) if any(isinstance(value, str) for value in python[role].values()): return False try: diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 7676baaea..23dcb9f48 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -240,7 +240,6 @@ def save(self, path: str | Path) -> None: "tag_schema": dict(saved["tag"]), "data_schema": dict(saved["data"]), "nullable": copy.deepcopy(saved["nullable"]), - "inherited_types": node._inherited_types, # pyright: ignore[reportPrivateUsage] # blueprint slot provenance } descriptor["reconstructable"] = True @@ -437,10 +436,6 @@ def load(cls, path: str | Path) -> "Pipeline": ) if not node_name: node_name = descriptor.get("label") or "unknown" - # Old blueprints did not distinguish declarations from - # inherited schemas. Their saved Arrow types can describe an - # operator result, so preserve them as they were saved. - inherited_types = source_config.get("inherited_types", True) # Which columns may be null: recorded (``require_nullability_records``). saved_nullable: dict[str, list[str]] if "tag_schema" in source_config and "data_schema" in source_config: @@ -456,7 +451,6 @@ def load(cls, path: str | Path) -> "Pipeline": saved_tag, context.type_converter, nullable=saved_nullable["tag"], - inherited_types=inherited_types, ) ) data_schema = Schema( @@ -464,7 +458,6 @@ def load(cls, path: str | Path) -> "Pipeline": saved_data, context.type_converter, nullable=saved_nullable["data"], - inherited_types=inherited_types, ) ) saved_context = resolve_saved_context( @@ -500,7 +493,6 @@ def load(cls, path: str | Path) -> "Pipeline": content_hash=descriptor.get("content_hash"), saved_types={"tag": saved_tag, "data": saved_data}, nullable=saved_nullable, - inherited_types=inherited_types, ) # Restore label from descriptor if set explicitly stored_label = descriptor.get("label") diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index daea495df..4df2a23ab 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -24,7 +24,6 @@ ) from orcapod.semantic_types.narrow_float_keys import ( NarrowFloatKeyError, - require_schema_without_narrow_float_keys, saved_source_schema_errors, ) from orcapod.types import Schema @@ -693,7 +692,7 @@ def resolve_source_from_config( cls = SOURCE_REGISTRY[source_type] try: # Let the input schema reach the identity check even if it contains a - # legacy narrow key. Explicit declarations in the config still fail early. + # legacy narrow key. This checks live input, independently of saved schemas. schema_errors: list[NarrowFloatKeyError] = [] token = saved_source_schema_errors.set(schema_errors) try: @@ -706,7 +705,7 @@ def resolve_source_from_config( raise schema_errors[0] return source except (NarrowFloatKeyError, Warning): - # An invalid declaration and a warning turned into an error propagate + # A changed input schema and a warning turned into an error propagate # instead of becoming a proxy for a source that could not be rebuilt. raise except Exception: @@ -750,17 +749,6 @@ def saved_source_id(config: dict[str, Any]) -> str: return "unknown" -def source_config_has_inherited_types(config: object) -> bool: - """Whether a saved source config describes types inherited from an upstream.""" - if not isinstance(config, dict): - return False - fields = cast("dict[str, object]", config) - kind = fields.get("source_type") - if kind == "cached": - return source_config_has_inherited_types(fields.get("inner_source")) - return kind == "derived" - - def saved_source_identifiers(config: dict[str, Any]) -> set[tuple[str, str]]: """Read the source ID and content hash available without rebuilding a source.""" inner = config.get("inner_source") @@ -853,19 +841,16 @@ def _source_proxy_from_config( expected_class_name = SOURCE_REGISTRY[source_type].__name__ # A config without the nullability record (written before ITL-1043) is lossy. - inherited_types = source_config_has_inherited_types(config) tag_schema = Schema( deserialize_schema( tag_schema_dict, nullable=None if saved_nullable is None else saved_nullable["tag"], - inherited_types=inherited_types, ) ) data_schema = Schema( deserialize_schema( data_schema_dict, nullable=None if saved_nullable is None else saved_nullable["data"], - inherited_types=inherited_types, ) ) @@ -1144,8 +1129,6 @@ def deserialize_schema( schema_dict: dict[str, str], type_converter: Any | None = None, nullable: Collection[str] | None = None, - *, - inherited_types: bool = False, ) -> dict[str, Any]: """Reconstruct a Python-type schema from Arrow type string values. @@ -1159,7 +1142,6 @@ def deserialize_schema( produced by `serialize_schema`. type_converter: Optional type converter for Arrow→Python conversion. When ``None``, the default data context's converter is used. - inherited_types: The saved types describe already-built upstream results. nullable: The columns saved as nullable (one group of ``serialize_nullability``); each becomes ``T | None``. ``None`` when the file records no nullability: every column is then restored as ``T``. @@ -1171,8 +1153,6 @@ def deserialize_schema( Raises: ValueError: If ``nullable`` names a column that is not in ``schema_dict``. """ - import pyarrow as pa - if type_converter is None: from orcapod.contexts import resolve_context @@ -1184,10 +1164,6 @@ def deserialize_schema( for name, type_str in schema_dict.items(): try: arrow_type = parse_arrow_type_string(type_str, type_converter) - if not inherited_types: - require_schema_without_narrow_float_keys( - pa.schema([(name, arrow_type)]) - ) result[name] = _python_type_of_saved_column( name, arrow_type, @@ -1196,7 +1172,7 @@ def deserialize_schema( ) except LogicalTypeIdentifierError as exc: raise exc.for_column(name) from exc - except (NarrowFloatKeyError, SavedSchemaVersionError, Warning): + except (SavedSchemaVersionError, Warning): # A warning turned into an error (a provisional library value type under an # error filter) propagates (ITL-1331). raise @@ -1589,13 +1565,15 @@ def deserialize_arrow_schema( "restored." ) from exc fields.append(pa.field(name, arrow_type, nullable=name in nullable)) - schema = pa.schema(fields) - require_schema_without_narrow_float_keys(schema) - return schema + return pa.schema(fields) def parse_arrow_type_string(type_str: str, type_converter: Any | None = None) -> Any: - """Parse an Arrow type string into a ``pa.DataType``. + """Restore a saved Arrow type string as a ``pa.DataType``. + + Saved types describe schemas that already existed. Declaration checks belong + at the points where callers introduce a type, so reading the text preserves + legacy types, including narrow float dict keys and set elements. Handles both primitive types (``"int64"``, ``"large_string"``) and nested types (``"list"``, ``"struct"``, diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index d0a639099..f6ff6cd5b 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -897,50 +897,73 @@ def test_polling_source_refuses_declared_schema_without_fetch( impl.fetch.assert_not_called() -@pytest.mark.parametrize("reader", ["config", "node"]) -@pytest.mark.parametrize("type_text", ["dict", "set"]) -def test_saved_arrow_schema_refuses_narrow_keys(reader: str, type_text: str) -> None: +@pytest.mark.parametrize("width", NARROW) +@pytest.mark.parametrize("kind", ["dict", "set"]) +def test_saved_arrow_schema_preserves_narrow_keys( + width: pa.DataType, kind: str +) -> None: + from orcapod import SourceNode from orcapod.pipeline.serialization import ( arrow_type_texts, deserialize_arrow_schema, deserialize_schema, ) - arrow_type = ( - _dict_of(pa.float32()) if type_text == "dict" else _live_set(pa.float16()) - ) - columns = arrow_type_texts(pa.schema([("k", arrow_type)]), _converter()) + arrow_type = _dict_of(width) if kind == "dict" else _live_set(width) + schema = pa.schema([pa.field("k", arrow_type, nullable=False)]) + columns = arrow_type_texts(schema) + restored = deserialize_arrow_schema({"columns": columns, "nullable": []}) + assert arrow_type_texts(restored) == columns + assert not restored.field("k").nullable + expected = dict[float, int] if kind == "dict" else set[float] + assert deserialize_schema(columns, nullable=[]) == {"k": expected} + with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - if reader == "config": - deserialize_arrow_schema({"columns": columns, "nullable": []}) - else: - deserialize_schema(columns, _converter(), []) + SourceNode("declared", pa.schema([("id", pa.int64())]), schema) -def test_saved_job_rejects_prohibited_source_declaration(tmp_path: Path) -> None: - from orcapod import SourceNode - from orcapod.core.operators import Batch +def test_saved_cached_source_keeps_its_legacy_identity(tmp_path: Path) -> None: + """A saved inner-source identity can outlive the in-memory source.""" + from orcapod.pipeline.serialization import ( + arrow_type_texts, + resolve_source_from_config, + ) from orcapod.databases import DeltaTableDatabase from orcapod.pipeline import PipelineJob + from orcapod.sources import CachedSource + + @function_pod(output_keys="doubled") + def double(v: int | None) -> int: + return 2 * (v or 0) - slot = SourceNode( - "pairs", - pa.schema([("id", pa.int64())]), - pa.schema([("k", _dict_of(pa.float64()))]), + source = ArrowTableSource( + pa.table({"id": [1], "v": [3], "k": [0.5]}), + tag_columns="id", + tag_only_columns=True, + source_id="input", ) - job = PipelineJob(database=DeltaTableDatabase(tmp_path / "store")) + job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) with job: - Batch()(slot, label="batch") + double.pod( + CachedSource(source, cache_database=DeltaTableDatabase(tmp_path / "cache")), + label="double", + ) path = tmp_path / "job.json" job.save(path) saved = json.loads(path.read_text()) - for node in saved["pipeline"]["nodes"].values(): - if node["node_type"] == "source": - node["source_config"]["data_schema"]["k"] = str(_dict_of(pa.float32())) - node["output_schema"]["data"]["k"] = str(_dict_of(pa.float32())) + sources = saved["bindings"]["sources"] + inner = sources["input"]["inner_source"] + legacy = pa.schema([("k", _live_set(pa.float32()))]) + inner["data_schema"].update(arrow_type_texts(legacy)) path.write_text(json.dumps(saved)) - with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - PipelineJob.load(path) + + proxy = resolve_source_from_config(inner, fallback_to_proxy=True) + assert proxy.output_schema()[1]["k"] == set[float] | None + resaved = tmp_path / "resaved.json" + restored = PipelineJob.load(path) + assert restored.unbound_sources == ["input"] + restored.save(resaved) + assert json.loads(resaved.read_text())["bindings"]["sources"] == sources def test_legacy_delta_job_keeps_its_source_bound( @@ -969,11 +992,6 @@ def test_legacy_delta_job_keeps_its_source_bound( source.batch(label="batch") path = tmp_path / "job.json" job.save(path) - saved = json.loads(path.read_text()) - for node in saved["pipeline"]["nodes"].values(): - if node["node_type"] == "source": - node["source_config"].pop("inherited_types", None) - path.write_text(json.dumps(saved)) restored = PipelineJob.load(path) assert not restored.unbound_sources @@ -1053,11 +1071,6 @@ def test_legacy_spiral_job_keeps_its_source_bound( source.batch(label="batch") path = tmp_path / "job.json" job.save(path) - saved = json.loads(path.read_text()) - for node in saved["pipeline"]["nodes"].values(): - if node["node_type"] == "source": - node["source_config"].pop("inherited_types", None) - path.write_text(json.dumps(saved)) restored = PipelineJob.load(path) assert not restored.unbound_sources @@ -1207,7 +1220,7 @@ def test_duplicate_key_struct_is_not_dict_shape() -> None: "derived", [False, True], ids=["static-batch", "derived-source"] ) @pytest.mark.parametrize( - "legacy", [False, True], ids=["current-blueprint", "legacy-blueprint"] + "legacy", [False, True], ids=["current-blueprint", "old-provenance-marker"] ) def test_standalone_blueprint_loads_inherited_batch_input( tmp_path: Path, derived: bool, legacy: bool @@ -1248,9 +1261,8 @@ def test_standalone_blueprint_loads_inherited_batch_input( for node in saved["nodes"].values() if node["node_type"] == "source" ) - assert slot_config["inherited_types"] is True if legacy: - del slot_config["inherited_types"] + slot_config["inherited_types"] = False path.write_text(json.dumps(saved)) restored = Pipeline.load(path) From 34dcdec68256d56ebda34bdbffdfc7b98b642c26 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 16:13:51 -0800 Subject: [PATCH 17/32] fix(semantic_types): honor logical types in narrow-key checks --- .zed/rules | 4 +- CLAUDE.md | 4 +- changelog.d/ITL-1591.md | 4 +- docs/dev/design_issues/ITL-1591-NFK1.md | 5 +- .../semantic_types/narrow_float_keys.py | 204 ++++++++++++------ .../test_narrow_float_keys_refused.py | 158 +++++++++++++- 6 files changed, 308 insertions(+), 71 deletions(-) diff --git a/.zed/rules b/.zed/rules index 1a764ff1d..8d4acc7f7 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1570,7 +1570,9 @@ data. The rules: Arrow-held datagrams carry already-built schemas, including operator and cached results. A list of structs produced by aggregation can have the same Arrow shape as a dict. A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an - Arrow map; a set is the native set container, live or in its storage form. `float32` and + Arrow map; a set is the native set container, live or in its storage form. The check + follows native container elements and user-class field declarations. Custom logical + types interpret their own storage. `float32` and `float16` stay valid as a plain column, a list element, a struct field and a dict value; the silent narrowing of such plain values from an Arrow declaration is ITL-1613. - The type converter keys synthesized struct classes by the large-normalized struct, so diff --git a/CLAUDE.md b/CLAUDE.md index 4d905810c..625a01a61 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1618,7 +1618,9 @@ data. The rules: Arrow-held datagrams carry already-built schemas, including operator and cached results. A list of structs produced by aggregation can have the same Arrow shape as a dict. A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an - Arrow map; a set is the native set container, live or in its storage form. `float32` and + Arrow map; a set is the native set container, live or in its storage form. The check + follows native container elements and user-class field declarations. Custom logical + types interpret their own storage. `float32` and `float16` stay valid as a plain column, a list element, a struct field and a dict value; the silent narrowing of such plain values from an Arrow declaration is ITL-1613. - The type converter keys synthesized struct classes by the large-normalized struct, so diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 917398d70..5b1dcedbd 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -16,7 +16,9 @@ given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain - column, a list element, a struct field and a dict value. + column, a list element, a struct field and a dict value. Custom logical types still + accept their own storage layouts, including sequences of structs with `key` and + `value` fields. - Loading saved jobs and blueprints preserves legacy schema types, including float32 or float16 keys and set elements. Saved jobs also preserve bindings whose rebuilt inputs match the saved pipeline identity, including Delta and SpiralDB tables. A narrow diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 6de813c98..93338cfd2 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -36,7 +36,10 @@ blueprints, including legacy narrow float keys and elements. Public slot declara check any Arrow override and each explicitly declared Python role, including when the other Python role comes from a bound stream. A dict declaration uses the converter's dict shape -(`nested_storage.dict_entry_fields`) or an Arrow map. Plain narrow-float columns, list +(`nested_storage.dict_entry_fields`) or an Arrow map. The check follows native container +elements and declared user-class fields. A custom logical type defines the meaning of +its own storage, including a sequence of structs with `key` and `value` fields. +Plain narrow-float columns, list elements, struct fields and dict values remain accepted. Open points: an Arrow-held datagram can still narrow two keys to one when updated with diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index bb76aa44b..3ff46c6a4 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -9,8 +9,7 @@ schema or annotation and in an Arrow schema or table alike. The refusal reads types only, never a value. -What counts, at the top of a type and at any depth inside it (a list item, a struct -child, a dict or map key or value, a logical type's storage): +What counts, at the top of a type and inside its declared containers and fields: - the key of a dict: the type converter's dict shape (``nested_storage.dict_entry_fields``, a list of ``{key, value}`` structs) or an Arrow ``map``; @@ -18,6 +17,9 @@ set category), as a live extension type or as its storage with the identifier in ``ARROW:extension:*`` field metadata. +Custom logical types own the interpretation of their storage. Native containers +declare an element type, and user-class types declare fields in their identity record. + A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is accepted, and so is a ``float64`` key or element. @@ -90,49 +92,135 @@ def require_supported_python_float_key(annotation: object, *, is_set: bool) -> N def _is_narrow_float(arrow_type: pa.DataType) -> bool: import pyarrow as pa - if isinstance(arrow_type, pa.BaseExtensionType): - arrow_type = arrow_type.storage_type return pa.types.is_float32(arrow_type) or pa.types.is_float16(arrow_type) -def _native_container_metadata( - name: bytes | None, raw: bytes | None -) -> dict[str, object]: - """Read metadata only when the extension identifier names a native container.""" - if not name or not raw: - return {} - - from orcapod.logical_types.list_logical_type_factory import ( - LIST_CATEGORY, - SET_CATEGORY, - ) - - try: - metadata: object = json.loads(raw) - except ValueError: - return {} - if not isinstance(metadata, dict): - return {} - fields = cast("dict[str, object]", metadata) - category = fields.get("category") - if category not in (LIST_CATEGORY, SET_CATEGORY): - return {} - if not name.startswith(f"{category}[".encode()) or not name.endswith(b"]"): - return {} - return fields - - def _dict_key(arrow_type: pa.DataType) -> str | None: """Describe a narrow float key in a plain dict's storage type.""" import pyarrow as pa if pa.types.is_map(arrow_type): - key_type = arrow_type.key_type + key = arrow_type.key_field elif (entry_fields := dict_entry_fields(arrow_type)) is not None: - key_type = entry_fields[0].type + key = entry_fields[0] else: return None - return f"dict key type {key_type}" if _is_narrow_float(key_type) else None + if _EXTENSION_NAME_KEY not in (key.metadata or {}) and _is_narrow_float(key.type): + return f"dict key type {key.type}" + return None + + +def _declared_fields(arrow_type: pa.DataType, record: dict[str, object]) -> set[str]: + """Check user-class fields using the declared tokens alongside their Arrow types.""" + import pyarrow as pa + + if not pa.types.is_struct(arrow_type): + return set() + found: set[str] = set() + for name, token in cast("list[tuple[str, object]]", record["fields"]): + if arrow_type.get_field_index(name) != -1: + found.update(_declared_field(arrow_type.field(name).type, token)) + return found + + +def _non_null_token(token: object) -> object: + """Return the value type of an optional field or element.""" + if isinstance(token, dict) and "union" in token: + members = cast("list[object]", token["union"]) + non_null = [member for member in members if member != "None"] + if len(non_null) == 1: + return non_null[0] + return token + + +def _declared_field(arrow_type: pa.DataType, token: object) -> set[str]: + """Follow a field declaration whose extension wrappers were stripped for storage.""" + import pyarrow as pa + + unwrapped = _non_null_token(token) + if not isinstance(unwrapped, dict): + return set() + declaration = cast("dict[str, object]", unwrapped) + if "class" in declaration: + return _declared_fields( + arrow_type, cast("dict[str, object]", declaration["class"]) + ) + generic = declaration.get("generic") + if generic == "dict": + return set(narrow_float_keys(arrow_type)) + if generic in ("list", "set") and ( + pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type) + ): + item = cast("pa.DataType", arrow_type.value_type) + element = _non_null_token(cast("list[object]", declaration["args"])[0]) + if ( + generic == "set" + and _is_narrow_float(item) + and ( + isinstance(element, str) + or (isinstance(element, dict) and "literal" in element) + ) + ): + return {f"set element type {item}"} + return _declared_field(item, element) + return set() + + +def _logical_keys(arrow_type: pa.DataType, name: bytes, raw: bytes) -> set[str]: + """Check Orcapod containers and user classes, using their extension declarations.""" + import pyarrow as pa + + from orcapod.logical_types import user_class_identity as uci + from orcapod.logical_types.list_logical_type_factory import ( + LIST_CATEGORY, + SET_CATEGORY, + ) + + if not raw: + return set() + try: + decoded: object = json.loads(raw) + except ValueError: + return set() + if not isinstance(decoded, dict): + return set() + + metadata = cast("dict[str, object]", decoded) + category = metadata.get("category") + if category in (LIST_CATEGORY, SET_CATEGORY) and ( + name.startswith(f"{category}[".encode()) + and name.endswith(b"]") + and (pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type)) + ): + item = cast("pa.Field[pa.DataType]", arrow_type.value_field) + element_name = metadata.get("element_ext_name") + if isinstance(element_name, str): + if name != f"{category}[{element_name}]".encode(): + return set() + element_raw = metadata.get("element_ext_metadata") + return _logical_keys( + item.type, + element_name.encode(), + element_raw.encode() if isinstance(element_raw, str) else b"", + ) + if category == SET_CATEGORY and _is_narrow_float(item.type): + return {f"set element type {item.type}"} + return set(narrow_float_keys(item.type, item.metadata)) + + identity = metadata.get("identity") + if not isinstance(identity, dict): + return set() + record = cast("dict[str, object]", identity) + if ( + record.get("kind") + in (uci.KIND_DATACLASS, uci.KIND_PYDANTIC, uci.KIND_STRUCTURAL) + and category == f"orcapod.{record['kind']}" + and isinstance(record.get("name"), str) + and isinstance(record.get("fields"), list) + and name == uci.identity_string(record).encode() + ): + return _declared_fields(arrow_type, record) + return set() def narrow_float_keys( @@ -143,8 +231,8 @@ def narrow_float_keys( Args: arrow_type: A declared Arrow type, or the Arrow type a declared Python type maps to. - field_metadata: The metadata of the field that holds the type, when it has - one: a set in its storage form is known by it. + field_metadata: The metadata of the field that holds the type, which can + identify a logical type in its storage form. Returns: A description of each refused part (``"dict key type float"``, @@ -153,37 +241,21 @@ def narrow_float_keys( """ import pyarrow as pa - metadata = field_metadata or {} - if isinstance(arrow_type, pa.BaseExtensionType): - if isinstance(arrow_type, pa.ExtensionType): - metadata = { - _EXTENSION_NAME_KEY: arrow_type.extension_name.encode(), - _EXTENSION_METADATA_KEY: arrow_type.__arrow_ext_serialize__(), - } - else: - metadata = {} - arrow_type = arrow_type.storage_type - - native = _native_container_metadata( - metadata.get(_EXTENSION_NAME_KEY), metadata.get(_EXTENSION_METADATA_KEY) - ) - if native and (pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type)): - from orcapod.logical_types.list_logical_type_factory import SET_CATEGORY - - item = arrow_type.value_field - found: set[str] = set() - if native["category"] == SET_CATEGORY and _is_narrow_float(item.type): - found.add(f"set element type {item.type}") - element_name = native.get("element_ext_name") - element_raw = native.get("element_ext_metadata") - item_metadata = dict(item.metadata or {}) - if isinstance(element_name, str): - item_metadata[_EXTENSION_NAME_KEY] = element_name.encode() - item_metadata[_EXTENSION_METADATA_KEY] = ( - element_raw.encode() if isinstance(element_raw, str) else b"" + if isinstance(arrow_type, pa.ExtensionType): + return sorted( + _logical_keys( + arrow_type.storage_type, + arrow_type.extension_name.encode(), + arrow_type.__arrow_ext_serialize__(), ) - found.update(narrow_float_keys(item.type, item_metadata)) - return sorted(found) + ) + if isinstance(arrow_type, pa.BaseExtensionType): + return [] + metadata = field_metadata or {} + if name := metadata.get(_EXTENSION_NAME_KEY): + return sorted( + _logical_keys(arrow_type, name, metadata.get(_EXTENSION_METADATA_KEY, b"")) + ) if pa.types.is_dictionary(arrow_type): return narrow_float_keys(arrow_type.value_type) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index f6ff6cd5b..2063e2b39 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -31,7 +31,7 @@ import pytest from typing_extensions import override -from orcapod import contexts, function_pod +from orcapod import contexts, dataclass as structural_dataclass, function_pod from orcapod.core.datagrams import Data, Datagram, Tag from orcapod.core.operators import Index from orcapod.core.sources import ( @@ -175,6 +175,162 @@ class Frames: assert converter.arrow_table_to_python_dicts(table) == rows +@dataclasses.dataclass(frozen=True) +class _Frames: + events: tuple[tuple[float, int], ...] + + +@dataclasses.dataclass(frozen=True) +class _FrameBox: + frames: _Frames + sequence: list[_Frames] + + +@dataclasses.dataclass(frozen=True) +class _Pair: + key: np.float32 + value: int + + +@structural_dataclass(name="NarrowFloatKeyPair") +class _StructuralPair: + key: np.float32 + value: int + + +@dataclasses.dataclass +class _LegacyDictField: + entries: list[dict[np.float32, int]] + + +@structural_dataclass(name="NarrowFloatLegacySetField") +class _LegacySetField: + entries: list[set[np.float32]] + + +@pytest.mark.parametrize( + ("annotation", "description"), + [ + (list[_LegacyDictField], "dict key type float"), + (list[_LegacySetField], "set element type float"), + ], +) +def test_explicit_arrow_checks_declared_fields_of_user_classes( + annotation: Any, description: str, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + from orcapod.semantic_types import universal_converter + + converter = contexts.create_registry().get_context("v1").type_converter + assert isinstance(converter, UniversalTypeConverter) + with pytest.raises(NarrowFloatKeyError, match=description): + converter.register_python_class(annotation) + + def allow_legacy_keys( + arrow_type: pa.DataType, *, is_set_element: bool = False + ) -> None: + pass + + with monkeypatch.context() as legacy: + legacy.setattr( + universal_converter, + "require_no_narrow_float_keys", + allow_legacy_keys, + ) + arrow_type = converter.register_python_class(annotation) + schema = pa.schema([("legacy", arrow_type)]) + for declaration in (schema, storage_form_schema(schema)): + with pytest.raises(NarrowFloatKeyError, match=description): + require_schema_without_narrow_float_keys(declaration) + + +_FRAMES = _Frames(((0.5, 1), (0.5, 2))) +_PAIR_ROWS = [{"key": 0.5, "value": 1}, {"key": 0.5, "value": 2}] + + +@pytest.fixture(scope="module") +def frames_converter() -> UniversalTypeConverter: + converter = contexts.resolve_context(None).type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type( + _make_logical_type( + "test.source.frames", + _Frames, + _dict_of(pa.float32()), + lambda frames: [ + {"key": key, "value": value} for key, value in frames.events + ], + lambda rows: _Frames(tuple((row["key"], row["value"]) for row in rows)), + ) + ) + return converter + + +@pytest.mark.parametrize( + ("annotation", "value", "storage"), + [ + pytest.param(_Frames, _FRAMES, _PAIR_ROWS, id="opaque-sequence"), + pytest.param(list[_Frames], [_FRAMES], [_PAIR_ROWS], id="list"), + pytest.param(set[_Frames], {_FRAMES}, [_PAIR_ROWS], id="set"), + pytest.param( + list[_FrameBox], + [_FrameBox(_FRAMES, [_FRAMES])], + [{"frames": _PAIR_ROWS, "sequence": [_PAIR_ROWS]}], + id="declared-fields-under-list", + ), + pytest.param( + list[_Pair], + [_Pair(np.float32(0.5), 1), _Pair(np.float32(0.5), 2)], + _PAIR_ROWS, + id="declared-pair-fields", + ), + pytest.param( + list[_StructuralPair], + [_StructuralPair(np.float32(0.5), 1), _StructuralPair(np.float32(0.5), 2)], + _PAIR_ROWS, + id="structural-pair-fields", + ), + ], +) +@pytest.mark.parametrize("route", ["dict", "arrow", "storage", "dataframe", "pod"]) +def test_public_ingestion_preserves_logical_sequences( + frames_converter: UniversalTypeConverter, + annotation: Any, + value: Any, + storage: Any, + route: str, +) -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + + converter = frames_converter + rows = [{"id": 1, "frames": value}] + schema = {"id": int, "frames": annotation} + if route == "pod": + + def produce(x: int) -> Any: + return value + + produce.__annotations__["return"] = annotation + pod = function_pod(output_keys="frames")(produce) + source = pod.pod(ListSource("x", [1])) + elif route == "dict": + source = DictSource( + rows, data_schema=schema, tag_columns="id", tag_only_columns=True + ) + else: + table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + if route == "storage": + table = table.cast(storage_form_schema(table.schema)) + source_type = ( + DataFrameSource if route in {"dataframe", "storage"} else ArrowTableSource + ) + source = source_type(table, tag_columns="id", tag_only_columns=True) + output = source.as_table() + assert output["frames"].to_pylist() == [storage] + if route not in {"dataframe", "storage"}: + assert converter.arrow_table_to_python_dicts(output)[0]["frames"] == value + + @pytest.mark.parametrize("storage_type", [pa.float16(), pa.float32()], ids=str) def test_index_preserves_empty_logical_set_column(storage_type: pa.DataType) -> None: """An out-of-bounds Index retains the native set type in its empty result.""" From 7c2fb6ff4b319b75b3134e8ebc2ff236e1662e01 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:31:19 -0800 Subject: [PATCH 18/32] fix(semantic-types): apply the declared Arrow dict boundary --- changelog.d/ITL-1591.md | 10 +- docs/concepts/function-pods.md | 16 +++ docs/dev/design_issues/ITL-1591-NFK1.md | 22 ++-- .../semantic_types/narrow_float_keys.py | 34 +++-- .../test_narrow_float_keys_refused.py | 118 ++++++++++++++++++ 5 files changed, 180 insertions(+), 20 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 5b1dcedbd..27a98ca25 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -16,9 +16,13 @@ given to the Python-to-Arrow converter. The check reads types only, never a value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain - column, a list element, a struct field and a dict value. Custom logical types still - accept their own storage layouts, including sequences of structs with `key` and - `value` fields. + column, a list element, a struct field and a dict value. At a declaration boundary, + a bare Arrow list (plain, large or fixed-size) of structs with exactly `key` and + `value` fields counts as a dict regardless of intent, as does an Arrow map. Custom + logical types own their storage, including when their identifiers are stored in + field metadata. The check follows native list and set element types and declared + user-class fields. Already-built operator results and their caches bypass the + declaration check, including `Batch` results with the same list-of-structs shape. - Loading saved jobs and blueprints preserves legacy schema types, including float32 or float16 keys and set elements. Saved jobs also preserve bindings whose rebuilt inputs match the saved pipeline identity, including Delta and SpiralDB tables. A narrow diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index c114460a9..7ba3cc1ea 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -292,6 +292,22 @@ lose an entry. Such a parameter or output raises `NarrowFloatKeyError` when the defined (ITL-1591). Declare the key or element as `float`. `np.float32` remains valid as a plain value, a list element and a dictionary value. +#### What counts as a dict here + +At a declared Arrow input, an Arrow map or a bare list of structs with exactly the +fields `key` and `value` counts as a dict regardless of intent. This includes plain, +large and fixed-size lists. Custom logical types own their storage, whether Arrow +carries the extension type directly or records it in field metadata. A registered +class that exposes `set[str]` or `dict[str, int]` can therefore use float32-backed +storage. The check follows the element type of Orcapod's native lists and sets and +the declared fields of its user classes. + +The check runs when a type is declared and enters the pipeline. For example, a source +that supplies a bare `large_list>` is refused. +`Batch` can produce that same type by collecting a source's plain `key`/`value` struct +column. The already-built result and its cached rows remain usable. Reading a saved +schema also preserves the types it records. + 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/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 93338cfd2..985ef14eb 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -35,15 +35,19 @@ job load. Schema readers preserve the types recorded in saved jobs, proxies and blueprints, including legacy narrow float keys and elements. Public slot declarations check any Arrow override and each explicitly declared Python role, including when the other Python role comes from a bound stream. -A dict declaration uses the converter's dict shape -(`nested_storage.dict_entry_fields`) or an Arrow map. The check follows native container -elements and declared user-class fields. A custom logical type defines the meaning of -its own storage, including a sequence of structs with `key` and `value` fields. -Plain narrow-float columns, list -elements, struct fields and dict values remain accepted. +Under D38 (November 29, 2026), a bare Arrow list (plain, large or fixed-size) of +structs with exactly `key` and `value` fields is a dict regardless of intent. +`nested_storage.dict_entry_fields` defines the shape. An Arrow map is also a dict. +Custom logical types own their storage, including when the extension identifier is +in field metadata. This includes a class that exposes `set[str]` or `dict[str, int]` +over float32-backed storage. The check follows native list and set element types and +declared user-class fields. Plain narrow-float columns, list elements, struct fields +and dict values remain accepted. Open points: an Arrow-held datagram can still narrow two keys to one when updated with Python floats. A raw `ArrowTableStream` still accepts the same Arrow type. Both APIs also -carry already-built operator results, including a list of structs whose fields happen to -be named `key` and `value`. Such a result has the same Arrow shape as a dict. An -Arrow-declared plain value can still narrow silently (ITL-1613). +carry already-built operator results. Under D28, a `Batch` result that collects a plain +`key`/`value` struct column bypasses the declaration check, as do stored results and +saved schemas. Supplying the same bare list shape with a narrow-float key as a source's +Arrow input triggers the check. An Arrow-declared plain value can still narrow silently +(ITL-1613). diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 3ff46c6a4..6955b5430 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -11,14 +11,16 @@ What counts, at the top of a type and inside its declared containers and fields: -- the key of a dict: the type converter's dict shape (``nested_storage.dict_entry_fields``, - a list of ``{key, value}`` structs) or an Arrow ``map``; +- the key of a dict: an Arrow ``map`` or a bare Arrow list (plain, large or fixed-size) + of structs with exactly ``key`` and ``value`` fields, regardless of intent (D38). + ``nested_storage.dict_entry_fields`` defines the shape; - the element of a set: the native ``set[T]`` container (a ``ListLogicalType`` of the set category), as a live extension type or as its storage with the identifier in ``ARROW:extension:*`` field metadata. -Custom logical types own the interpretation of their storage. Native containers -declare an element type, and user-class types declare fields in their identity record. +Custom logical types own their storage, in both live and field-metadata forms. Native +containers declare an element type, and user-class types declare fields in their identity +record. Only declared entry points use this rule (D28). A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is accepted, and so is a ``float64`` key or element. @@ -102,6 +104,9 @@ def _dict_key(arrow_type: pa.DataType) -> str | None: if pa.types.is_map(arrow_type): key = arrow_type.key_field elif (entry_fields := dict_entry_fields(arrow_type)) is not None: + # The item struct may be the storage form of a logical type. + if _EXTENSION_NAME_KEY in (arrow_type.field(0).metadata or {}): + return None key = entry_fields[0] else: return None @@ -203,7 +208,11 @@ def _logical_keys(arrow_type: pa.DataType, name: bytes, raw: bytes) -> set[str]: element_name.encode(), element_raw.encode() if isinstance(element_raw, str) else b"", ) - if category == SET_CATEGORY and _is_narrow_float(item.type): + if ( + category == SET_CATEGORY + and _EXTENSION_NAME_KEY not in (item.metadata or {}) + and _is_narrow_float(item.type) + ): return {f"set element type {item.type}"} return set(narrow_float_keys(item.type, item.metadata)) @@ -228,6 +237,12 @@ def narrow_float_keys( ) -> list[str]: """Return what the rule refuses in ``arrow_type``, at any depth. + A bare list (plain, large or fixed-size) of structs with exactly ``key`` and + ``value`` fields counts as a dict regardless of intent, as does an Arrow map + (D38). A logical type, including a field annotated only in metadata, owns its + storage. Follow Orcapod's native list and set element declarations and its + user-class field declarations. + Args: arrow_type: A declared Arrow type, or the Arrow type a declared Python type maps to. @@ -299,9 +314,12 @@ def require_schema_without_narrow_float_keys( ) -> None: """Refuse an Arrow schema with a ``float32`` or ``float16`` dict key or set element. - Applied to a source's Arrow declaration and to explicitly declared mutations. - Operator results and their caches can have the same Arrow shape as a dict, - so their already-built schemas do not go through this check. No value is read. + Applied at declared entry points (D28), including source Arrow inputs and + explicitly declared mutations. A bare list of structs with exactly ``key`` + and ``value`` fields is a dict at these boundaries (D38). For example, Batch + can build that shape from a struct column and carry it through the pipeline. + Supplying the same shape as a source's Arrow input triggers the check. Operator + results, caches and saved schemas bypass declaration validation. No value is read. Args: arrow_schema: The Arrow schema of the table. diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 2063e2b39..2f19e65eb 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -112,6 +112,124 @@ def storage_to_python( return LogicalElement() +@pytest.mark.parametrize("width", [pa.float32(), pa.float16()], ids=str) +def test_d38_bare_key_value_struct_lists_are_dicts(width: pa.DataType) -> None: + from orcapod.core.operators import Batch + + pair_type = pa.struct([("key", width), ("value", pa.int64())]) + pair = {"key": 0.5, "value": 1} + source = ArrowTableSource( + pa.table({"id": [1], "pairs": pa.array([pair], type=pair_type)}), + tag_columns="id", + tag_only_columns=True, + ) + result = Batch().static_process(source).as_table(columns={"source": False}) + assert result["pairs"].type == pa.large_list(pair_type) + assert result["pairs"].to_pylist() == [[pair]] + + for list_type in ( + pa.list_(pair_type), + pa.large_list(pair_type), + pa.list_(pair_type, 1), + ): + table = pa.table({"id": [1], "pairs": pa.array([[pair]], type=list_type)}) + with pytest.raises(NarrowFloatKeyError, match="column 'pairs'.*dict key type"): + ArrowTableSource(table, tag_columns="id", tag_only_columns=True) + + +def test_d38_logical_storage_is_opaque_in_both_arrow_forms() -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + + @dataclasses.dataclass(frozen=True) + class Opaque: + value: object + + pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) + for storage in (pa.large_list(pair_type), pair_type): + logical = _make_logical_type( + f"test.narrow_keys.opaque.{storage.id}", + Opaque, + storage, + lambda value: value.value, + Opaque, + ).get_arrow_extension_type() + schema = pa.schema([("v", logical), ("nested", pa.large_list(logical))]) + require_schema_without_narrow_float_keys(schema) + require_schema_without_narrow_float_keys(storage_form_schema(schema)) + + +@dataclasses.dataclass(frozen=True) +class _StringSet: + values: set[str] + + +@dataclasses.dataclass(frozen=True) +class _StringDict: + values: dict[str, int] + + +def test_d38_custom_set_and_dict_classes_own_float32_storage() -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + + converter = contexts.create_registry().get_context("v1").type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type( + _make_logical_type( + "test.narrow_keys.string_set", + _StringSet, + pa.large_list(pa.float32()), + lambda value: [float(item) for item in value.values], + lambda stored: _StringSet({str(item) for item in stored}), + ) + ) + converter.register_logical_type( + _make_logical_type( + "test.narrow_keys.string_dict", + _StringDict, + _dict_of(pa.float32()), + lambda value: [ + {"key": float(key), "value": item} for key, item in value.values.items() + ], + lambda stored: _StringDict( + {str(row["key"]): row["value"] for row in stored} + ), + ) + ) + rows = [{"items": _StringSet({"0.5"}), "pairs": _StringDict({"0.5": 1})}] + table = converter.python_dicts_to_arrow_table( + rows, python_schema={"items": _StringSet, "pairs": _StringDict} + ) + require_schema_without_narrow_float_keys(table.schema) + require_schema_without_narrow_float_keys(storage_form_schema(table.schema)) + assert converter.arrow_table_to_python_dicts(table) == rows + + +@pytest.mark.parametrize( + ("numpy_type", "arrow_type"), + [(np.float32, pa.float32()), (np.float16, pa.float16())], +) +def test_d38_python_and_map_declarations_are_refused_and_saved_schemas_load( + numpy_type: Any, arrow_type: pa.DataType +) -> None: + from orcapod.pipeline.serialization import ( + arrow_type_texts, + deserialize_arrow_schema, + ) + + for declaration in (list[dict[numpy_type, int]], list[set[numpy_type]]): + with pytest.raises(NarrowFloatKeyError): + Data({"v": []}, python_schema={"v": declaration}) + + schema = pa.schema([("v", pa.list_(pa.map_(arrow_type, pa.int64())))]) + with pytest.raises(NarrowFloatKeyError, match="dict key type"): + require_schema_without_narrow_float_keys(schema) + + saved = pa.schema([("v", _dict_of(arrow_type)), ("s", _live_set(arrow_type))]) + columns = arrow_type_texts(saved) + restored = deserialize_arrow_schema({"columns": columns, "nullable": ["v", "s"]}) + assert arrow_type_texts(restored) == columns + + @dataclasses.dataclass(frozen=True) class _Measurement: magnitude: float From 891b36162c981a98bf29a9161de4e143757a3fc1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:33:02 -0800 Subject: [PATCH 19/32] test(semantic-types): redeclare the public Batch result at a source --- .../test_narrow_float_keys_refused.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 2f19e65eb..de15cfbfa 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -123,16 +123,16 @@ def test_d38_bare_key_value_struct_lists_are_dicts(width: pa.DataType) -> None: tag_columns="id", tag_only_columns=True, ) - result = Batch().static_process(source).as_table(columns={"source": False}) + result = Batch()(source).as_table() assert result["pairs"].type == pa.large_list(pair_type) assert result["pairs"].to_pylist() == [[pair]] - for list_type in ( - pa.list_(pair_type), - pa.large_list(pair_type), - pa.list_(pair_type, 1), + for pairs in ( + pa.array([[pair]], type=pa.list_(pair_type)), + result["pairs"], + pa.array([[pair]], type=pa.list_(pair_type, 1)), ): - table = pa.table({"id": [1], "pairs": pa.array([[pair]], type=list_type)}) + table = pa.table({"id": [1], "pairs": pairs}) with pytest.raises(NarrowFloatKeyError, match="column 'pairs'.*dict key type"): ArrowTableSource(table, tag_columns="id", tag_only_columns=True) From 1a9401bdd8d29208b97b81894e696f9b3d3721dc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:35:11 -0800 Subject: [PATCH 20/32] test(semantic-types): construct the redeclared source from Arrow arrays --- tests/test_semantic_types/test_narrow_float_keys_refused.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index de15cfbfa..3c38020a1 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -132,7 +132,7 @@ def test_d38_bare_key_value_struct_lists_are_dicts(width: pa.DataType) -> None: result["pairs"], pa.array([[pair]], type=pa.list_(pair_type, 1)), ): - table = pa.table({"id": [1], "pairs": pairs}) + table = pa.Table.from_arrays([pa.array([1]), pairs], names=["id", "pairs"]) with pytest.raises(NarrowFloatKeyError, match="column 'pairs'.*dict key type"): ArrowTableSource(table, tag_columns="id", tag_only_columns=True) From 195bbe4d612fa98e98fb92d530a9ca9a461ea1cf Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:17:12 -0800 Subject: [PATCH 21/32] fix(semantic-types): validate narrow keys at declared boundaries --- changelog.d/ITL-1591.md | 3 + docs/dev/design_issues/ITL-1591-NFK1.md | 9 +- src/orcapod/core/datagrams/datagram.py | 51 +-- src/orcapod/core/nodes/source_node.py | 14 +- src/orcapod/core/sources/csv_source.py | 4 +- src/orcapod/core/sources/data_frame_source.py | 16 +- src/orcapod/core/sources/dict_source.py | 5 +- src/orcapod/core/sources/list_source.py | 1 + src/orcapod/core/sources/polars_input.py | 67 ++- src/orcapod/core/sources/polling_source.py | 12 +- src/orcapod/core/sources/stream_builder.py | 10 +- .../semantic_types/narrow_float_keys.py | 383 ++++++++++-------- .../semantic_types/universal_converter.py | 78 ++-- src/orcapod/utils/schema_utils.py | 12 +- .../test_narrow_float_keys_refused.py | 152 ++++++- 15 files changed, 531 insertions(+), 286 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 27a98ca25..8c6b1d020 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -30,6 +30,9 @@ ### Known limitations +- Inference still accepts undeclared float32 keys and set elements in Python data. + For example, `Data({"k": {np.float32(0.5): 1}}).as_table()` succeeds + (ITL-1668, ITL-1667). - A plain value (not a dict key or set element) stored into a column that an Arrow schema declares `float32` or `float16` is still narrowed without a warning: `0.1` under `pa.float16()` is stored as `0.0999755859375` (ITL-1613). diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 985ef14eb..f5f21fe7a 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -26,8 +26,7 @@ converter checks explicit Arrow declarations before converting Python rows and c plain Python set element types, including when no logical type registry is configured. The Polars-backed sources keep the incoming Arrow declarations for the schema check when importing arrays or streams, including Arrow-backed pandas columns passed in -column mappings at any depth, sequences and iterators. The check uses those declarations -and inferred Arrow fields before building the stream. The input data follows its usual +column mappings at any depth, sequences and iterators. The check uses those declarations before building the stream. The input data follows its usual conversion path. The saved-source resolver keeps input types when the rebuilt source matches its saved pipeline hash. A narrow key in a changed input schema raises a declaration error during @@ -41,10 +40,12 @@ structs with exactly `key` and `value` fields is a dict regardless of intent. Custom logical types own their storage, including when the extension identifier is in field metadata. This includes a class that exposes `set[str]` or `dict[str, int]` over float32-backed storage. The check follows native list and set element types and -declared user-class fields. Plain narrow-float columns, list elements, struct fields +declared user-class fields, as Python annotations. A class registered as a custom +logical type remains opaque inside another class. Plain narrow-float columns, list elements, struct fields and dict values remain accepted. -Open points: an Arrow-held datagram can still narrow two keys to one when updated with +Open points: an undeclared dict or set built from Python values can still infer a +float32 key or element (ITL-1668, ITL-1667). An Arrow-held datagram can still narrow two keys to one when updated with Python floats. A raw `ArrowTableStream` still accepts the same Arrow type. Both APIs also carry already-built operator results. Under D28, a `Batch` result that collects a plain `key`/`value` struct column bypasses the declaration check, as do stored results and diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 958a15693..e805d2fa6 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -38,6 +38,7 @@ 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.narrow_float_keys import ( + converting_existing_types, require_schema_without_narrow_float_keys, ) from orcapod.system_constants import constants @@ -419,10 +420,12 @@ def _ensure_data_table(self) -> pa.Table: """ if self._data_table is None: assert self._data_dict is not None - self._data_table = self.converter.python_dicts_to_arrow_table( - [self._data_dict], - self._data_python_schema, - ) + # Explicit Python types were checked when the datagram was built. + with converting_existing_types(): + self._data_table = self.converter.python_dicts_to_arrow_table( + [self._data_dict], + self._data_python_schema, + ) return self._data_table def _ensure_python_schema(self) -> Schema: @@ -448,9 +451,12 @@ def _ensure_arrow_schema(self) -> pa.Schema: if self._data_table is not None: self._data_arrow_schema = self._data_table.schema else: - self._data_arrow_schema = self.converter.python_schema_to_arrow_schema( - self._ensure_python_schema() - ) + with converting_existing_types(): + self._data_arrow_schema = ( + self.converter.python_schema_to_arrow_schema( + self._ensure_python_schema() + ) + ) return self._data_arrow_schema def _ensure_context_table(self) -> pa.Table: @@ -472,9 +478,10 @@ def _ensure_meta_table(self) -> pa.Table | None: if not self._meta: return None if self._meta_table is None: - self._meta_table = self.converter.python_dicts_to_arrow_table( - [self._meta], python_schema=self._meta_python_schema - ) + with converting_existing_types(): + self._meta_table = self.converter.python_dicts_to_arrow_table( + [self._meta], python_schema=self._meta_python_schema + ) return self._meta_table # ------------------------------------------------------------------ @@ -768,12 +775,13 @@ def with_meta_columns(self, **meta_updates: DataValue) -> Self: ) ) if prefixed: - tables.append( - self.converter.python_dicts_to_arrow_table( - [prefixed], - python_schema=Schema({k: merged[k] for k in prefixed}), + with converting_existing_types(): + tables.append( + self.converter.python_dicts_to_arrow_table( + [prefixed], + python_schema=new_inferred, + ) ) - ) meta_names = list(new_d.meta_columns) new_d._meta_table = ( arrow_utils.hstack_tables(*tables).select(meta_names) @@ -1087,22 +1095,17 @@ def _new_columns_table( else: python_schema[name] = declared arrow_schema = pa.schema(list(arrow_fields.values())) - require_schema_without_narrow_float_keys(arrow_schema) + require_schema_without_narrow_float_keys(arrow_schema, converter=self.converter) for name, field in arrow_fields.items(): if updates[name] is None and not field.nullable: raise ValueError( f"Column {name!r} is declared non-nullable" f" ({column_types[name]}) but its value is None" ) - inferred_names = [n for n in updates if n not in column_types] - if inferred_names: - python_schema.update( - infer_python_schema_from_pylist_data( - [{n: updates[n] for n in inferred_names}] - ) - ) - + inferred = {n: value for n, value in updates.items() if n not in column_types} tables: list[pa.Table] = [] + if inferred: + tables.append(self.converter.python_dicts_to_arrow_table([inferred])) if python_schema: tables.append( self.converter.python_dicts_to_arrow_table( diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 094463f88..02e70aae8 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -578,9 +578,9 @@ def __init__( raise ValueError( "arrow_schemas is given by tag_schema and data_schema already" ) - require_schema_without_narrow_float_keys(tag_schema) - require_schema_without_narrow_float_keys(data_schema) converter = self.data_context.type_converter + require_schema_without_narrow_float_keys(tag_schema, converter=converter) + require_schema_without_narrow_float_keys(data_schema, converter=converter) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). tag_schema = declaration_form_schema(tag_schema, converter) @@ -589,9 +589,9 @@ def __init__( tag_schema = Schema(converter.arrow_schema_to_python_schema(tag_schema)) data_schema = Schema(converter.arrow_schema_to_python_schema(data_schema)) elif arrow_schemas is not None and not _inherited_types: - for schema in arrow_schemas: - require_schema_without_narrow_float_keys(schema) converter = self.data_context.type_converter + for schema in arrow_schemas: + require_schema_without_narrow_float_keys(schema, converter=converter) # A supplied Arrow mapping may cover Python types the converter does # not know. Still check both roles for prohibited Python declarations. require_python_schema_without_narrow_float_keys(tag_schema, converter) @@ -1711,9 +1711,11 @@ def __init__( elif not _inherited_types: # Both Arrow schemas were supplied by the caller. Only the Python # roles that were supplied are declarations. - for schema in arrow_schemas: - require_schema_without_narrow_float_keys(schema) converter = contexts.resolve_context(data_context).type_converter + for schema in arrow_schemas: + require_schema_without_narrow_float_keys( + schema, converter=converter + ) for python_schema in (tag_schema, data_schema): if python_schema is not None: require_python_schema_without_narrow_float_keys( diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 11614eaa6..9d7f2bc6f 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -313,7 +313,9 @@ def __init__( # working directory is then. self._access_path = os.path.abspath(file_path) if schema is not None: - require_schema_without_narrow_float_keys(schema) + require_schema_without_narrow_float_keys( + schema, converter=self.data_context.type_converter + ) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._system_tag_columns: Collection[str] = system_tag_columns diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 2f74a1c8b..941900d79 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -81,7 +81,9 @@ def __init__( super().__init__(source_id=source_id, **kwargs) if schema is not None: - require_schema_without_narrow_float_keys(schema) + require_schema_without_narrow_float_keys( + schema, converter=self.data_context.type_converter + ) arrow_input_schema = None input_schema = None @@ -105,7 +107,9 @@ def __init__( ) arrow_input_schema = arrow_input.schema require_schema_without_narrow_float_keys( - arrow_input_schema, source_input=True + arrow_input_schema, + source_input=True, + converter=self.data_context.type_converter, ) # Polars rechunks native tables but preserves chunks on exporter inputs. df = cast( @@ -113,7 +117,9 @@ def __init__( pl.from_arrow(arrow_input, rechunk=isinstance(data, pa.Table)), ) else: - df, input_schema = dataframe_with_input_schema(data) + df, input_schema = dataframe_with_input_schema( + data, self.data_context.type_converter + ) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] @@ -146,7 +152,9 @@ def __init__( arrow_table = df.to_arrow() if arrow_input_schema is None: - require_polars_input_types(arrow_table.schema, input_schema) + require_polars_input_types( + arrow_table.schema, input_schema, self.data_context.type_converter + ) if schema is not None: require_supported_nullable_types(schema) if arrow_input_schema is None: diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index bbd8b2a10..27a76abb6 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -89,7 +89,9 @@ def __init__( # Accept either a Python SchemaLike (Mapping[str, type]) or a # pa.Schema directly via data_schema; route to the converter accordingly. if isinstance(data_schema, pa.Schema): - require_schema_without_narrow_float_keys(data_schema) + require_schema_without_narrow_float_keys( + data_schema, converter=self.data_context.type_converter + ) require_supported_nullable_types(data_schema) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, @@ -121,6 +123,7 @@ def __init__( kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, + input_types_checked=data_schema is None, system_tag_columns=system_tag_columns, ) diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 1433cbc71..b9fadd4ce 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -157,6 +157,7 @@ def __init__( kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, + input_types_checked=data_schema is None, ) self._stream = result.stream diff --git a/src/orcapod/core/sources/polars_input.py b/src/orcapod/core/sources/polars_input.py index 0b4b30166..0abbf907b 100644 --- a/src/orcapod/core/sources/polars_input.py +++ b/src/orcapod/core/sources/polars_input.py @@ -11,6 +11,7 @@ import polars as pl import pyarrow as pa +from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol from orcapod.semantic_types.narrow_float_keys import ( require_schema_without_narrow_float_keys, ) @@ -117,48 +118,36 @@ def _pandas_arrow_fields(columns: Iterable[object]) -> Iterator[pa.Field[pa.Data yield pa.field(str(column.name), column.dtype.pyarrow_dtype) -PolarsInputSchema = pa.Schema | Mapping[str, object] | None +PolarsInputSchema = pa.Schema | pl.Schema | Mapping[str, object] | None def _mapping_arrow_fields( - columns: Mapping[str, object], inferred: Iterable[pa.Field[pa.DataType]] -) -> Iterable[pa.Field[pa.DataType]]: - """Overlay Arrow declarations on the inferred fields of a column mapping.""" - fields = {field.name: field for field in inferred} + columns: Mapping[str, object], +) -> Iterator[pa.Field[pa.DataType]]: + """Read Arrow declarations carried by a column mapping, including nested columns.""" for name, column in columns.items(): name = str(name) if isinstance(column, (pa.Array, pa.ChunkedArray)): - fields[name] = pa.field(name, column.type) + yield pa.field(name, column.type) elif isinstance(column, (pd.Series, pd.Index)) and isinstance( column.dtype, pd.ArrowDtype ): - fields[name] = pa.field(name, column.dtype.pyarrow_dtype) + yield pa.field(name, column.dtype.pyarrow_dtype) elif isinstance(column, dict): - # Polars turns nested column mappings into structs. Keep original - # Arrow types at their leaves and inferred types for their siblings. - field = fields.get(name) - field_type = field.type if field is not None else None - if field_type is not None and not isinstance(field_type, pa.StructType): - continue - children = _mapping_arrow_fields( - column, () if field_type is None else field_type - ) + children = list(_mapping_arrow_fields(column)) if children: - struct = pa.struct(children) - fields[name] = ( - pa.field(name, struct) if field is None else field.with_type(struct) - ) - return fields.values() + yield pa.field(name, pa.struct(children)) def dataframe_with_input_schema( data: FrameInitTypes, + converter: TypeConverterProtocol, ) -> tuple[pl.DataFrame, PolarsInputSchema]: """Run the usual Polars constructor and retain any original Arrow declarations. Polars may discard a native list or set identifier while importing, so the - source uses the incoming Arrow fields to check the declaration. For inputs - without Arrow declarations it can check the Arrow types it inferred later. + source uses the incoming Arrow fields to check the declaration. For a + typed Polars input, retain the column types supplied by the caller. """ schema: PolarsInputSchema = None observed = None @@ -173,6 +162,10 @@ def dataframe_with_input_schema( for name, dtype in data.dtypes.items() if isinstance(dtype, pd.ArrowDtype) ) + elif isinstance(data, pl.DataFrame): + schema = data.schema + elif isinstance(data, pl.Series): + schema = pl.Schema({data.name: data.dtype}) elif isinstance(data, Mapping): schema = data elif isinstance(data, Sequence): @@ -201,7 +194,7 @@ def original_schema() -> PolarsInputSchema: # Polars can fail to import some types entirely (for example a union). # Prefer the known declaration error if a field has a prohibited key. if (declaration := original_schema()) is not None: - require_polars_input_types(pa.schema([]), declaration) + require_polars_input_types(pa.schema([]), declaration, converter) raise return frame, original_schema() @@ -225,17 +218,23 @@ def _observe_pandas_iterator( def require_polars_input_types( - inferred: pa.Schema, original: PolarsInputSchema + converted: pa.Schema, original: PolarsInputSchema, converter: TypeConverterProtocol ) -> None: - """Check each input field once, using its original Arrow declaration if known.""" - if isinstance(original, Mapping): - inferred = pa.schema(_mapping_arrow_fields(original, inferred)) - elif original is not None: - known = set(original.names) - inferred = pa.schema( + """Validate the declared fields of the input to Polars.""" + if original is None: + return + if isinstance(original, pa.Schema): + declaration = original + elif isinstance(original, pl.Schema): + declaration = pa.schema( [ - *original, - *(field for field in inferred if field.name not in known), + field + for field in converted + if field.name in original and original[field.name] != pl.Object ] ) - require_schema_without_narrow_float_keys(inferred, source_input=True) + else: + declaration = pa.schema(_mapping_arrow_fields(original)) + require_schema_without_narrow_float_keys( + declaration, source_input=True, converter=converter + ) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index e6aa4f1ba..ef071db6a 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -341,7 +341,9 @@ def __init__( self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): - require_schema_without_narrow_float_keys(unified_schema) + require_schema_without_narrow_float_keys( + unified_schema, converter=self.data_context.type_converter + ) require_supported_nullable_types(unified_schema) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). @@ -912,7 +914,9 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - df, input_schema = dataframe_with_input_schema(data) + df, input_schema = dataframe_with_input_schema( + data, self.data_context.type_converter + ) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", @@ -940,7 +944,9 @@ def _build_stream_from_df( df = df.with_columns([pl.from_arrow(c) for c in sub_table]) raw = df.to_arrow() - require_polars_input_types(raw.schema, input_schema) + require_polars_input_types( + raw.schema, input_schema, self.data_context.type_converter + ) require_supported_nullable_types(raw.schema) arrow_table = arrow_utils.drop_system_columns(raw) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 223f43dde..50beb254d 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -596,8 +596,8 @@ def build( reordering. inherited_types: The table retains already-built upstream types, as when a derived source copies a tag into data. - input_types_checked: The source already checked the declarations using - the original Arrow types and metadata retained during import. + input_types_checked: The source handled validation of any declarations + before passing the table to the builder. record_id_columns: The key columns whose values identify a row, in key order: the row identifier is their canonical JSON (``key_row_identifier``), which follows the row regardless of its @@ -674,7 +674,11 @@ def build( # Nor is a dict keyed by, or a set of, float32 or float16 (ITL-1591): refused # here first, as the stream refuses it, before any key column or hash. if not inherited_types and not input_types_checked: - require_schema_without_narrow_float_keys(table.schema, source_input=True) + require_schema_without_narrow_float_keys( + table.schema, + source_input=True, + converter=self._data_context.type_converter, + ) # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 6955b5430..38c506f11 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -25,18 +25,27 @@ A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is accepted, and so is a ``float64`` key or element. -The rule is here once. The type converter applies it to every dict and set type it -builds from a Python declaration (``require_no_narrow_float_keys``); source ingestion and explicit Arrow declarations apply it to an Arrow schema -(``require_schema_without_narrow_float_keys``). +The rule applies to Python declarations and explicit Arrow inputs. Inference and +conversion of values under types that already entered bypass declaration validation. """ from __future__ import annotations import json -from collections.abc import Mapping +from collections.abc import Iterator, Mapping +from contextlib import contextmanager from contextvars import ContextVar from types import UnionType -from typing import TYPE_CHECKING, Literal, Union, cast, get_args, get_origin +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Protocol, + Union, + cast, + get_args, + get_origin, +) from orcapod.errors import InputValidationError from orcapod.semantic_types.nested_storage import dict_entry_fields @@ -44,6 +53,15 @@ if TYPE_CHECKING: import pyarrow as pa + from orcapod.logical_types.protocols import LogicalTypeProtocol + + +class _LogicalTypeLookup(Protocol): + """Read existing Python registrations without creating new ones.""" + + def get_logical_type(self, python_type: type) -> LogicalTypeProtocol | None: ... + + NARROW_FLOAT_KEYS_NOT_SUPPORTED = ( "float32 and float16 are not supported as a dict key type or a set element type" ) @@ -71,23 +89,61 @@ class NarrowFloatKeyError(InputValidationError, ValueError): ) -def require_supported_python_float_key(annotation: object, *, is_set: bool) -> None: - """Report an unsupported NumPy half float in a key or set element declaration.""" +_converting_existing_types: ContextVar[bool] = ContextVar( + "converting_existing_types", default=False +) + + +@contextmanager +def converting_existing_types() -> Iterator[None]: + """Convert inferred or already-validated types without treating them as declarations.""" + token = _converting_existing_types.set(True) + try: + yield + finally: + _converting_existing_types.reset(token) + + +def checking_python_declarations() -> bool: + """Return whether Python type conversion is checking a new declaration.""" + return not _converting_existing_types.get() + + +def _python_float_key(annotation: object, *, is_set: bool) -> str | None: + """Describe a narrow Python key or element, including optional and literal types.""" import numpy as np + import pyarrow as pa origin = get_origin(annotation) args = get_args(annotation) if origin in (Union, UnionType): non_none = [arg for arg in args if arg is not type(None)] - if len(non_none) == 1: - require_supported_python_float_key(non_none[0], is_set=is_set) - if annotation is np.float16 or ( - origin is Literal - and {type(value) for value in args if value is not None} == {np.float16} + if len(non_none) != 1: + return None + return _python_float_key(non_none[0], is_set=is_set) + if origin is Literal: + value_types = {type(value) for value in args if value is not None} + if len(value_types) != 1: + return None + annotation = next(iter(value_types)) + if annotation is np.float16: + arrow_type = pa.float16() + elif annotation is np.float32 or ( + isinstance(annotation, str) and annotation == "float32" + ): + arrow_type = pa.float32() + else: + return None + return f"{'set element' if is_set else 'dict key'} type {arrow_type}" + + +def require_supported_python_float_key(annotation: object, *, is_set: bool) -> None: + """Refuse a narrow key or element as its Python container is declared.""" + if checking_python_declarations() and ( + description := _python_float_key(annotation, is_set=is_set) ): - part = "set element" if is_set else "dict key" raise NarrowFloatKeyError( - f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {part} type {annotation}. {_REMEDY}" + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {description}. {_REMEDY}" ) @@ -115,64 +171,25 @@ def _dict_key(arrow_type: pa.DataType) -> str | None: return None -def _declared_fields(arrow_type: pa.DataType, record: dict[str, object]) -> set[str]: - """Check user-class fields using the declared tokens alongside their Arrow types.""" - import pyarrow as pa - - if not pa.types.is_struct(arrow_type): - return set() - found: set[str] = set() - for name, token in cast("list[tuple[str, object]]", record["fields"]): - if arrow_type.get_field_index(name) != -1: - found.update(_declared_field(arrow_type.field(name).type, token)) - return found - +def _python_class_fields( + cls: type, converter: _LogicalTypeLookup +) -> Iterator[tuple[str, object]]: + """Read the fields of a native user class, leaving custom logical classes opaque.""" + from orcapod.logical_types import user_class_identity as uci + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType -def _non_null_token(token: object) -> object: - """Return the value type of an optional field or element.""" - if isinstance(token, dict) and "union" in token: - members = cast("list[object]", token["union"]) - non_null = [member for member in members if member != "None"] - if len(non_null) == 1: - return non_null[0] - return token + if uci.class_kind(cls) is not None: + registered = converter.get_logical_type(cls) + if registered is None or isinstance(registered, UserClassLogicalType): + hints = uci.type_hints(cls) + for name in uci.stored_field_names(cls): + yield name, hints.get(name, Any) -def _declared_field(arrow_type: pa.DataType, token: object) -> set[str]: - """Follow a field declaration whose extension wrappers were stripped for storage.""" - import pyarrow as pa - - unwrapped = _non_null_token(token) - if not isinstance(unwrapped, dict): - return set() - declaration = cast("dict[str, object]", unwrapped) - if "class" in declaration: - return _declared_fields( - arrow_type, cast("dict[str, object]", declaration["class"]) - ) - generic = declaration.get("generic") - if generic == "dict": - return set(narrow_float_keys(arrow_type)) - if generic in ("list", "set") and ( - pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type) - ): - item = cast("pa.DataType", arrow_type.value_type) - element = _non_null_token(cast("list[object]", declaration["args"])[0]) - if ( - generic == "set" - and _is_narrow_float(item) - and ( - isinstance(element, str) - or (isinstance(element, dict) and "literal" in element) - ) - ): - return {f"set element type {item}"} - return _declared_field(item, element) - return set() - - -def _logical_keys(arrow_type: pa.DataType, name: bytes, raw: bytes) -> set[str]: - """Check Orcapod containers and user classes, using their extension declarations.""" +def _logical_children( + storage: pa.DataType, name: bytes, raw: bytes, converter: _LogicalTypeLookup +) -> tuple[str | None, list[object]]: + """Resolve the declarations of a native extension from its Arrow identifier.""" import pyarrow as pa from orcapod.logical_types import user_class_identity as uci @@ -180,137 +197,174 @@ def _logical_keys(arrow_type: pa.DataType, name: bytes, raw: bytes) -> set[str]: LIST_CATEGORY, SET_CATEGORY, ) + from orcapod.logical_types.protocols import ( + TypeConverterProtocol as LogicalTypeConverter, + ) + from orcapod.logical_types.structural_class import annotation_from_token if not raw: - return set() + return None, [] try: decoded: object = json.loads(raw) except ValueError: - return set() + return None, [] if not isinstance(decoded, dict): - return set() + return None, [] metadata = cast("dict[str, object]", decoded) category = metadata.get("category") if category in (LIST_CATEGORY, SET_CATEGORY) and ( name.startswith(f"{category}[".encode()) and name.endswith(b"]") - and (pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type)) + and (pa.types.is_list(storage) or pa.types.is_large_list(storage)) ): - item = cast("pa.Field[pa.DataType]", arrow_type.value_field) + item = cast("pa.Field[pa.DataType]", storage.value_field) element_name = metadata.get("element_ext_name") if isinstance(element_name, str): if name != f"{category}[{element_name}]".encode(): - return set() + return None, [] element_raw = metadata.get("element_ext_metadata") - return _logical_keys( - item.type, - element_name.encode(), - element_raw.encode() if isinstance(element_raw, str) else b"", + item = item.with_metadata( + { + _EXTENSION_NAME_KEY: element_name.encode(), + _EXTENSION_METADATA_KEY: ( + element_raw.encode() if isinstance(element_raw, str) else b"" + ), + } ) if ( category == SET_CATEGORY and _EXTENSION_NAME_KEY not in (item.metadata or {}) and _is_narrow_float(item.type) ): - return {f"set element type {item.type}"} - return set(narrow_float_keys(item.type, item.metadata)) + return f"set element type {item.type}", [] + return None, [item] identity = metadata.get("identity") if not isinstance(identity, dict): - return set() - record = cast("dict[str, object]", identity) + return None, [] + record = cast("dict[str, Any]", identity) + kind, class_name = record.get("kind"), record.get("name") if ( - record.get("kind") - in (uci.KIND_DATACLASS, uci.KIND_PYDANTIC, uci.KIND_STRUCTURAL) - and category == f"orcapod.{record['kind']}" - and isinstance(record.get("name"), str) - and isinstance(record.get("fields"), list) - and name == uci.identity_string(record).encode() + kind not in (uci.KIND_DATACLASS, uci.KIND_PYDANTIC, uci.KIND_STRUCTURAL) + or category != f"orcapod.{kind}" + or not isinstance(class_name, str) + or not isinstance(record.get("fields"), list) + or name != uci.identity_string(record).encode() ): - return _declared_fields(arrow_type, record) - return set() - - -def narrow_float_keys( - arrow_type: pa.DataType, field_metadata: Mapping[bytes, bytes] | None = None -) -> list[str]: - """Return what the rule refuses in ``arrow_type``, at any depth. - - A bare list (plain, large or fixed-size) of structs with exactly ``key`` and - ``value`` fields counts as a dict regardless of intent, as does an Arrow map - (D38). A logical type, including a field annotated only in metadata, owns its - storage. Follow Orcapod's native list and set element declarations and its - user-class field declarations. + return None, [] - Args: - arrow_type: A declared Arrow type, or the Arrow type a declared Python type - maps to. - field_metadata: The metadata of the field that holds the type, which can - identify a logical type in its storage form. - - Returns: - A description of each refused part (``"dict key type float"``, - ``"set element type halffloat"``), sorted, each once; empty when the type is - accepted. - """ + if kind == uci.KIND_STRUCTURAL: + for cls in uci.structural_classes(class_name): + if uci.known_record(cls) == record: + return None, [cls] + else: + exact_class: object = uci.find_exact_class(class_name) + if isinstance(exact_class, type) and uci.class_kind(exact_class) == kind: + return None, [exact_class] + + # A portable class can have no definition in the current process. Its + # identity records each declared Python field type. + if not isinstance(converter, LogicalTypeConverter): + return None, [] + annotations: list[object] = [] + for _, token in record["fields"]: + try: + annotation: object = annotation_from_token(token, converter) + annotations.append(annotation) + except (ImportError, TypeError, ValueError): + # The reader reports unresolved identities independently of this rule. + continue + return None, annotations + + +def _walk( + declaration: object, + converter: _LogicalTypeLookup, + ancestors: tuple[type, ...] = (), + *, + field_metadata: Mapping[bytes, bytes] | None = None, +) -> Iterator[str]: + """Walk bare Arrow types, native containers and declared user-class fields.""" import pyarrow as pa - if isinstance(arrow_type, pa.ExtensionType): - return sorted( - _logical_keys( - arrow_type.storage_type, - arrow_type.extension_name.encode(), - arrow_type.__arrow_ext_serialize__(), - ) - ) - if isinstance(arrow_type, pa.BaseExtensionType): - return [] metadata = field_metadata or {} - if name := metadata.get(_EXTENSION_NAME_KEY): - return sorted( - _logical_keys(arrow_type, name, metadata.get(_EXTENSION_METADATA_KEY, b"")) + if isinstance(declaration, pa.Field): + metadata = declaration.metadata or {} + declaration = declaration.type + if isinstance(declaration, pa.DataType): + part = None + children: list[object] = [] + if isinstance(declaration, pa.ExtensionType): + part, children = _logical_children( + declaration.storage_type, + declaration.extension_name.encode(), + declaration.__arrow_ext_serialize__(), + converter, + ) + elif isinstance(declaration, pa.BaseExtensionType): + return + elif name := metadata.get(_EXTENSION_NAME_KEY): + part, children = _logical_children( + declaration, name, metadata.get(_EXTENSION_METADATA_KEY, b""), converter + ) + else: + part = _dict_key(declaration) + if pa.types.is_dictionary(declaration): + children = [declaration.value_type] + else: + children = [ + declaration.field(index) for index in range(declaration.num_fields) + ] + if part: + yield part + for child in children: + yield from _walk(child, converter, ancestors) + return + + origin = get_origin(declaration) + args = get_args(declaration) + if origin in (dict, set) and args: + if part := _python_float_key(args[0], is_set=origin is set): + yield part + if origin in (list, set, dict, tuple, Union, UnionType): + for arg in args: + yield from _walk(arg, converter, ancestors) + elif isinstance(declaration, type) and declaration not in ancestors: + for name, annotation in _python_class_fields(declaration, converter): + for part in _walk(annotation, converter, (*ancestors, declaration)): + yield f"{declaration.__qualname__}.{name}: {part}" + + +def require_python_declaration_without_narrow_float_keys( + annotation: object, converter: _LogicalTypeLookup +) -> None: + """Refuse a Python declaration without requiring its Arrow storage to exist.""" + if found := sorted(set(_walk(annotation, converter))): + raise NarrowFloatKeyError( + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {', '.join(found)}. {_REMEDY}" ) - if pa.types.is_dictionary(arrow_type): - return narrow_float_keys(arrow_type.value_type) - - found: set[str] = set() - if (description := _dict_key(arrow_type)) is not None: - found.add(description) - for index in range(arrow_type.num_fields): - child = arrow_type.field(index) - found.update(narrow_float_keys(child.type, child.metadata)) - return sorted(found) - - -def require_no_narrow_float_keys( - arrow_type: pa.DataType, *, is_set_element: bool = False -) -> None: - """Refuse a declared type with a ``float32`` or ``float16`` dict key or set element. - Args: - arrow_type: A declared Arrow type, or the Arrow type a declared Python type - maps to. - is_set_element: Whether the type is itself declared as a set element. +def narrow_float_keys( + arrow_type: pa.DataType, + field_metadata: Mapping[bytes, bytes] | None = None, + *, + converter: _LogicalTypeLookup | None = None, +) -> list[str]: + """Return the refused keys and elements of a declared Arrow type.""" + if converter is None: + from orcapod.contexts import resolve_context - Raises: - NarrowFloatKeyError: If ``arrow_type`` is, or contains at any depth, a dict - keyed by, or a set of, ``float32`` or ``float16``. The message names the - type and each such part, and the remedy. - """ - found = narrow_float_keys(arrow_type) - if is_set_element and _is_narrow_float(arrow_type): - found.insert(0, f"set element type {arrow_type}") - if found: - raise NarrowFloatKeyError( - f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: Arrow type {arrow_type} has " - f"{', '.join(found)}. {_REMEDY}" - ) + converter = resolve_context(None).type_converter + return sorted(set(_walk(arrow_type, converter, field_metadata=field_metadata))) def require_schema_without_narrow_float_keys( - arrow_schema: pa.Schema, *, source_input: bool = False + arrow_schema: pa.Schema, + *, + source_input: bool = False, + converter: _LogicalTypeLookup | None = None, ) -> None: """Refuse an Arrow schema with a ``float32`` or ``float16`` dict key or set element. @@ -323,6 +377,7 @@ def require_schema_without_narrow_float_keys( Args: arrow_schema: The Arrow schema of the table. + converter: The data context that owns the declared logical types. source_input: The schema came from the source's input data. During saved source reconstruction its diagnostic can wait for the identity check. @@ -332,10 +387,14 @@ def require_schema_without_narrow_float_keys( such column, in name order, with its type and each such part, and the remedy. """ + if converter is None: + from orcapod.contexts import resolve_context + + converter = resolve_context(None).type_converter lines = [ f" - column {field.name!r} has type {field.type} ({', '.join(found)})" for field in sorted(arrow_schema, key=lambda field: field.name) - if (found := narrow_float_keys(field.type, field.metadata)) + if (found := sorted(set(_walk(field, converter)))) ] if lines: error = NarrowFloatKeyError( diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 3c01a1afe..6ff76b570 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 contextlib import nullcontext from datetime import date, datetime, timezone # Handle generic types @@ -46,7 +47,9 @@ ) from orcapod.semantic_types.narrow_float_keys import ( NarrowFloatKeyError, - require_no_narrow_float_keys, + checking_python_declarations, + converting_existing_types, + require_python_declaration_without_narrow_float_keys, require_schema_without_narrow_float_keys, require_supported_python_float_key, ) @@ -307,7 +310,7 @@ def get_native_python_types(cls) -> frozenset[type]: ) | {type(None)} return _ARROW_NATIVE_TYPE_KEYS - def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: + def ensure_types_registered_for_schemas(self, *schemas: SchemaLike) -> None: """Ensure a LogicalType is registered for every annotation in schemas. Calls ``register_python_class`` for each annotation, which recursively @@ -524,13 +527,9 @@ def _register_python_class_impl( 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) - dict_arrow = pa.large_list( + return pa.large_list( pa.struct([pa.field("key", key_arrow), pa.field("value", val_arrow)]) ) - # A dict keyed by float32 or float16 is refused where it is declared - # (ITL-1591). - require_no_narrow_float_keys(dict_arrow) - return dict_arrow # Concrete class — registry or factory dispatch if isinstance(annotation, type): @@ -544,6 +543,10 @@ def _register_python_class_impl( # Registry hit (already synthesised) lt = self._logical_type_registry.get_by_python_type(annotation) if lt is not None: + if checking_python_declarations(): + require_python_declaration_without_narrow_float_keys( + annotation, self + ) return lt.get_arrow_extension_type() # Cycle detection (via the shared ContextVar-backed in_progress set) @@ -632,8 +635,6 @@ def _make_or_get_arrow_element_set_type( ListLogicalType, ) - # Check the declaration even when the set will be stored as a plain list. - require_no_narrow_float_keys(element_arrow_type, is_set_element=True) if self._logical_type_registry is None or isinstance( element_arrow_type, pa.BaseExtensionType ): @@ -970,9 +971,10 @@ def register_logical_type_from_arrow_metadata( ) # Reconstruct and register - logical_type = factory.reconstruct_from_arrow( - arrow_extension_name, storage_type, metadata_dict, converter=self - ) + with converting_existing_types(): + logical_type = factory.reconstruct_from_arrow( + arrow_extension_name, storage_type, metadata_dict, converter=self + ) require_readable(logical_type, extension_metadata) self._logical_type_registry.register_logical_type(logical_type) return logical_type.get_arrow_extension_type() @@ -1010,7 +1012,8 @@ def storage_to_python(self, storage_value: Any, annotation: Any) -> Any: decodes nested positions (list elements, class fields); a column's own null never reaches it. """ - arrow_type = self.python_type_to_arrow_type(annotation) + with converting_existing_types(): + arrow_type = self.python_type_to_arrow_type(annotation) if storage_value is None and not none_is_restorable( arrow_type, self._is_user_class_extension ): @@ -1083,7 +1086,8 @@ def python_type_to_arrow_type(self, python_type: DataType) -> pa.DataType: # Convert and cache result arrow_type = self._convert_python_to_arrow(python_type) - self._python_to_arrow_types[python_type] = arrow_type + if checking_python_declarations(): + self._python_to_arrow_types[python_type] = arrow_type return arrow_type @@ -1396,26 +1400,24 @@ def python_dicts_to_arrow_table( a dict key or set element. """ if arrow_schema is not None: - require_schema_without_narrow_float_keys(arrow_schema) + require_schema_without_narrow_float_keys(arrow_schema, converter=self) if python_schema is not None: require_python_schema_without_narrow_float_keys(python_schema, self) logger.warning( "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." ) - if python_schema is None and arrow_schema is None: - # Infer schema from data if not provided - python_schema = infer_python_schema_from_pylist_data(python_dicts) - if arrow_schema is None: - # Convert to Arrow schema — auto-register any types that have a registered - # 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 - # 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) + scope = ( + nullcontext() + if python_schema is not None + else converting_existing_types() + ) + with scope: + if python_schema is None: + python_schema = infer_python_schema_from_pylist_data(python_dicts) + # Auto-register types covered by a semantic-type factory. + 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, ( @@ -1423,9 +1425,10 @@ 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 - ) + with converting_existing_types(): + struct_dicts = self.python_dicts_to_struct_dicts( + python_dicts, python_schema=python_schema + ) # TODO: add more helpful message here return pa.Table.from_pylist(struct_dicts, schema=arrow_schema) @@ -1523,6 +1526,10 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: if self._logical_type_registry is not None: lt = self._logical_type_registry.get_by_python_type(python_type) if lt is not None: + if checking_python_declarations(): + require_python_declaration_without_narrow_float_keys( + python_type, self + ) return lt.get_arrow_extension_type() # Handle typeddict look up @@ -1593,11 +1600,7 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: require_storable_in_struct_field(value_type) require_restorable_none(args[1], value_type, self._is_user_class_extension) key_value_struct = pa.struct([("key", key_type), ("value", value_type)]) - dict_arrow = pa.large_list(key_value_struct) - # A dict keyed by float32 or float16 is refused where it is declared - # (ITL-1591). - require_no_narrow_float_keys(dict_arrow) - return dict_arrow + return pa.large_list(key_value_struct) # Handle Union/Optional types elif origin is typing.Union or origin is types.UnionType: @@ -1902,7 +1905,8 @@ def convert_logical(value: Any) -> Any: # Get the Arrow type for this Python type # TODO: check if this step is necessary - _ = self.python_type_to_arrow_type(python_type) + with converting_existing_types(): + _ = self.python_type_to_arrow_type(python_type) # Create conversion function based on type diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index cc94ad952..8a35212f3 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -10,7 +10,11 @@ import pyarrow as pa from orcapod.errors import InputValidationError -from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError +from orcapod.semantic_types.narrow_float_keys import ( + NarrowFloatKeyError, + require_python_declaration_without_narrow_float_keys, +) +from orcapod.semantic_types.nested_none import with_context from orcapod.types import ContentHash, Schema, SchemaLike from orcapod.utils.output_containers import EXCLUDED_OUTPUT_CONTAINERS @@ -654,6 +658,12 @@ def require_python_schema_without_narrow_float_keys( belong to the path that requires the converter to produce an Arrow type. """ for name, python_type in schema.items(): + try: + require_python_declaration_without_narrow_float_keys(python_type, converter) + except NarrowFloatKeyError as exc: + raise with_context(f"Column {name!r} ({python_type})", exc) from exc + except (NameError, TypeError, ValueError): + pass try: declared_arrow_schema({name: python_type}, converter) except NarrowFloatKeyError: diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 3c38020a1..1e19d5997 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -54,7 +54,6 @@ NARROW_FLOAT_KEYS_NOT_SUPPORTED, NarrowFloatKeyError, narrow_float_keys, - require_no_narrow_float_keys, require_schema_without_narrow_float_keys, ) from orcapod.semantic_types.nested_storage import dict_entry_fields @@ -344,15 +343,13 @@ def test_explicit_arrow_checks_declared_fields_of_user_classes( with pytest.raises(NarrowFloatKeyError, match=description): converter.register_python_class(annotation) - def allow_legacy_keys( - arrow_type: pa.DataType, *, is_set_element: bool = False - ) -> None: + def allow_legacy_keys(annotation: object, *, is_set: bool) -> None: pass with monkeypatch.context() as legacy: legacy.setattr( universal_converter, - "require_no_narrow_float_keys", + "require_supported_python_float_key", allow_legacy_keys, ) arrow_type = converter.register_python_class(annotation) @@ -633,7 +630,6 @@ def test_accepts_every_other_key_and_element_type( ) -> None: column_type = build(part) assert narrow_float_keys(column_type) == [] - require_no_narrow_float_keys(column_type) require_schema_without_narrow_float_keys( pa.schema([("id", pa.int64()), ("k", column_type)]) ) @@ -1908,3 +1904,147 @@ def test_datagram_checks_new_arrow_declaration_before_materializing_existing_dat row = Data({"m": "invalid integer"}, python_schema={"m": int}) with pytest.raises(NarrowFloatKeyError, match="column 'k'"): row.with_columns({"k": _dict_of(pa.float32())}, k={}) + + +@dataclasses.dataclass(frozen=True) +class _CustomStringContainers: + pairs: _StringDict + items: _StringSet + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["dict", "arrow", "metadata"]) +async def test_nested_custom_string_containers_own_storage(route: str) -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + + context = contexts.create_registry().get_context("v1") + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type( + _make_logical_type( + "test.narrow_keys.nested_string_dict", + _StringDict, + pa.struct([("values", _dict_of(pa.float32()))]), + lambda value: { + "values": [ + {"key": float(key), "value": item} + for key, item in value.values.items() + ] + }, + lambda stored: _StringDict( + {str(row["key"]): row["value"] for row in stored["values"]} + ), + ) + ) + converter.register_logical_type( + _make_logical_type( + "test.narrow_keys.nested_string_set", + _StringSet, + pa.struct([("values", pa.large_list(pa.float32()))]), + lambda value: {"values": [float(item) for item in value.values]}, + lambda stored: _StringSet({str(item) for item in stored["values"]}), + ) + ) + item = _CustomStringContainers(_StringDict({"0.5": 1}), _StringSet({"0.5"})) + rows: list[dict[str, Any]] = [{"id": 1, "k": item}] + schema = {"id": int, "k": _CustomStringContainers} + if route == "dict": + source = DictSource(rows, "id", data_schema=schema, data_context=context) + else: + table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + if route == "metadata": + table = table.cast(storage_form_schema(table.schema)) + source = ArrowTableSource(table, "id", data_context=context) + stored = [ + { + "pairs": {"values": [{"key": 0.5, "value": 1}]}, + "items": {"values": [0.5]}, + } + ] + assert source.as_table()["k"].to_pylist() == stored + assert [ + data.as_table()["k"].to_pylist() async for _, data in source.async_iter_data() + ] == [stored] + assert [data.as_table()["k"].to_pylist() for _, data in source.iter_data()] == [ + stored + ] + + # The same boundary applies under bare Arrow containers and both native + # logical containers, no matter which form carries the identifiers. + nested = pa.schema( + [ + ( + "bare_list", + pa.list_(converter.register_python_class(_CustomStringContainers)), + ), + ( + "bare_struct", + pa.struct( + [("v", converter.register_python_class(_CustomStringContainers))] + ), + ), + ( + "native_list", + converter.register_python_class(list[_CustomStringContainers]), + ), + ( + "native_set", + converter.register_python_class(set[_CustomStringContainers]), + ), + ] + ) + for arrow_schema in (nested, storage_form_schema(nested)): + require_schema_without_narrow_float_keys(arrow_schema, converter=converter) + + +@dataclasses.dataclass +class _HalfDictField: + values: list[dict[np.float16, int]] + + +@dataclasses.dataclass +class _HalfSetField: + values: set[np.float16] + + +@pytest.mark.parametrize( + "instance", + [_HalfDictField([{np.float16(0.5): 1}]), _HalfSetField({np.float16(0.5)})], +) +def test_datagram_refuses_declared_half_float_field(instance: Any) -> None: + with pytest.raises(NarrowFloatKeyError, match=r"Column 'k'.*values"): + Data({"k": instance}, python_schema={"k": type(instance)}) + + +@pytest.mark.parametrize( + ("value", "annotation"), + [ + ({np.float32(0.5): 1}, dict[np.float32, int]), + ({np.float32(0.5)}, set[np.float32]), + ], +) +@pytest.mark.parametrize("route", ["data", "converter"]) +def test_undeclared_float32_dict_and_set_are_accepted( + value: Any, annotation: Any, route: str +) -> None: + context = contexts.create_registry().get_context("v1") + converter = context.type_converter + rows = [{"k": value}] + if route == "data": + row = Data(rows[0], data_context=context) + table = row.as_table() + else: + table = converter.python_dicts_to_arrow_table(rows) + assert converter.arrow_table_to_python_dicts(table) == rows + with pytest.raises(NarrowFloatKeyError): + converter.python_dicts_to_arrow_table(rows, python_schema={"k": annotation}) + + +def test_polars_source_accepts_undeclared_python_object_dict() -> None: + columns = { + "id": [1], + "k": pl.Series("k", [{np.float32(0.5): 1}], dtype=pl.Object), + } + table = DataFrameSource(columns, "id").as_table() + assert table["k"].type == _dict_of(pa.float32()) + assert table["k"].to_pylist() == [[{"key": 0.5, "value": 1}]] From e710fb6c1b4395aeb384cbb5545f55c25c9ae938 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:55:51 -0800 Subject: [PATCH 22/32] fix(semantic-types): validate Arrow class identity declarations --- docs/dev/design_issues/ITL-1591-NFK1.md | 9 +- .../semantic_types/narrow_float_keys.py | 149 +++++++------- .../test_narrow_float_keys_refused.py | 190 +++++++++++++++++- 3 files changed, 275 insertions(+), 73 deletions(-) diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index f5f21fe7a..760a7572b 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -39,10 +39,11 @@ structs with exactly `key` and `value` fields is a dict regardless of intent. `nested_storage.dict_entry_fields` defines the shape. An Arrow map is also a dict. Custom logical types own their storage, including when the extension identifier is in field metadata. This includes a class that exposes `set[str]` or `dict[str, int]` -over float32-backed storage. The check follows native list and set element types and -declared user-class fields, as Python annotations. A class registered as a custom -logical type remains opaque inside another class. Plain narrow-float columns, list elements, struct fields -and dict values remain accepted. +over float32-backed storage. The check follows native list and set element types. +For Arrow inputs, it follows user-class field type tokens in the extension's identity +record, including nested records. For Python declarations, it follows the class's +field annotations. Plain narrow-float columns, list elements, struct fields and dict +values remain accepted. Open points: an undeclared dict or set built from Python values can still infer a float32 key or element (ITL-1668, ITL-1667). An Arrow-held datagram can still narrow two keys to one when updated with diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 38c506f11..43203c549 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -19,8 +19,9 @@ ``ARROW:extension:*`` field metadata. Custom logical types own their storage, in both live and field-metadata forms. Native -containers declare an element type, and user-class types declare fields in their identity -record. Only declared entry points use this rule (D28). +containers declare an element type. An Arrow user-class type declares its fields in +its identity record, while a Python class declares fields in its annotations. Only +declared entry points use this rule (D28). A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is accepted, and so is a ``float64`` key or element. @@ -186,10 +187,57 @@ def _python_class_fields( yield name, hints.get(name, Any) -def _logical_children( - storage: pa.DataType, name: bytes, raw: bytes, converter: _LogicalTypeLookup -) -> tuple[str | None, list[object]]: - """Resolve the declarations of a native extension from its Arrow identifier.""" +def _token_float_width(token: object) -> str | None: + """Read a narrow float's Arrow type name from its canonical type token.""" + if isinstance(token, dict) and isinstance(members := token.get("union"), list): + non_none = [member for member in members if member != "None"] + if len(non_none) == 1: + return _token_float_width(non_none[0]) + if token == "numpy.float32": + return "float" + if token == "numpy.float16": + return "halffloat" + return None + + +def _walk_type_token(token: object) -> Iterator[str]: + """Walk the declaration in an identity token without resolving Python types.""" + if not isinstance(token, dict): + return + if isinstance(record := token.get("class"), dict): + yield from _walk_identity_record(record) + elif isinstance(members := token.get("union"), list): + for member in members: + yield from _walk_type_token(member) + elif (origin := token.get("generic")) in ("list", "set", "dict", "tuple"): + args = token.get("args") + if not isinstance(args, list): + return + if ( + origin in ("dict", "set") + and args + and (width := _token_float_width(args[0])) + ): + label = "dict key" if origin == "dict" else "set element" + yield f"{label} type {width}" + for arg in args: + yield from _walk_type_token(arg) + + +def _walk_identity_record(record: dict[str, Any]) -> Iterator[str]: + """Walk the stored field declarations of a user class.""" + class_name, fields = record.get("name"), record.get("fields") + if not isinstance(class_name, str) or not isinstance(fields, list): + return + for field in fields: + if isinstance(field, list) and len(field) == 2: + name, token = field + for part in _walk_type_token(token): + yield f"{class_name}.{name}: {part}" + + +def _walk_logical(storage: pa.DataType, name: bytes, raw: bytes) -> Iterator[str]: + """Walk the declarations carried by a native Arrow extension identifier.""" import pyarrow as pa from orcapod.logical_types import user_class_identity as uci @@ -197,19 +245,15 @@ def _logical_children( LIST_CATEGORY, SET_CATEGORY, ) - from orcapod.logical_types.protocols import ( - TypeConverterProtocol as LogicalTypeConverter, - ) - from orcapod.logical_types.structural_class import annotation_from_token if not raw: - return None, [] + return try: decoded: object = json.loads(raw) except ValueError: - return None, [] + return if not isinstance(decoded, dict): - return None, [] + return metadata = cast("dict[str, object]", decoded) category = metadata.get("category") @@ -222,7 +266,7 @@ def _logical_children( element_name = metadata.get("element_ext_name") if isinstance(element_name, str): if name != f"{category}[{element_name}]".encode(): - return None, [] + return element_raw = metadata.get("element_ext_metadata") item = item.with_metadata( { @@ -237,50 +281,29 @@ def _logical_children( and _EXTENSION_NAME_KEY not in (item.metadata or {}) and _is_narrow_float(item.type) ): - return f"set element type {item.type}", [] - return None, [item] + yield f"set element type {item.type}" + else: + yield from _walk(item) + return identity = metadata.get("identity") if not isinstance(identity, dict): - return None, [] + return record = cast("dict[str, Any]", identity) kind, class_name = record.get("kind"), record.get("name") if ( kind not in (uci.KIND_DATACLASS, uci.KIND_PYDANTIC, uci.KIND_STRUCTURAL) or category != f"orcapod.{kind}" or not isinstance(class_name, str) - or not isinstance(record.get("fields"), list) or name != uci.identity_string(record).encode() ): - return None, [] - - if kind == uci.KIND_STRUCTURAL: - for cls in uci.structural_classes(class_name): - if uci.known_record(cls) == record: - return None, [cls] - else: - exact_class: object = uci.find_exact_class(class_name) - if isinstance(exact_class, type) and uci.class_kind(exact_class) == kind: - return None, [exact_class] - - # A portable class can have no definition in the current process. Its - # identity records each declared Python field type. - if not isinstance(converter, LogicalTypeConverter): - return None, [] - annotations: list[object] = [] - for _, token in record["fields"]: - try: - annotation: object = annotation_from_token(token, converter) - annotations.append(annotation) - except (ImportError, TypeError, ValueError): - # The reader reports unresolved identities independently of this rule. - continue - return None, annotations + return + yield from _walk_identity_record(record) def _walk( declaration: object, - converter: _LogicalTypeLookup, + converter: _LogicalTypeLookup | None = None, ancestors: tuple[type, ...] = (), *, field_metadata: Mapping[bytes, bytes] | None = None, @@ -293,33 +316,26 @@ def _walk( metadata = declaration.metadata or {} declaration = declaration.type if isinstance(declaration, pa.DataType): - part = None - children: list[object] = [] if isinstance(declaration, pa.ExtensionType): - part, children = _logical_children( + yield from _walk_logical( declaration.storage_type, declaration.extension_name.encode(), declaration.__arrow_ext_serialize__(), - converter, ) elif isinstance(declaration, pa.BaseExtensionType): return elif name := metadata.get(_EXTENSION_NAME_KEY): - part, children = _logical_children( - declaration, name, metadata.get(_EXTENSION_METADATA_KEY, b""), converter + yield from _walk_logical( + declaration, name, metadata.get(_EXTENSION_METADATA_KEY, b"") ) else: - part = _dict_key(declaration) + if part := _dict_key(declaration): + yield part if pa.types.is_dictionary(declaration): - children = [declaration.value_type] + yield from _walk(declaration.value_type) else: - children = [ - declaration.field(index) for index in range(declaration.num_fields) - ] - if part: - yield part - for child in children: - yield from _walk(child, converter, ancestors) + for index in range(declaration.num_fields): + yield from _walk(declaration.field(index)) return origin = get_origin(declaration) @@ -330,7 +346,11 @@ def _walk( if origin in (list, set, dict, tuple, Union, UnionType): for arg in args: yield from _walk(arg, converter, ancestors) - elif isinstance(declaration, type) and declaration not in ancestors: + elif ( + converter is not None + and isinstance(declaration, type) + and declaration not in ancestors + ): for name, annotation in _python_class_fields(declaration, converter): for part in _walk(annotation, converter, (*ancestors, declaration)): yield f"{declaration.__qualname__}.{name}: {part}" @@ -353,10 +373,6 @@ def narrow_float_keys( converter: _LogicalTypeLookup | None = None, ) -> list[str]: """Return the refused keys and elements of a declared Arrow type.""" - if converter is None: - from orcapod.contexts import resolve_context - - converter = resolve_context(None).type_converter return sorted(set(_walk(arrow_type, converter, field_metadata=field_metadata))) @@ -377,7 +393,8 @@ def require_schema_without_narrow_float_keys( Args: arrow_schema: The Arrow schema of the table. - converter: The data context that owns the declared logical types. + converter: The data context of the caller. Arrow validation reads the + declarations carried by the schema itself. source_input: The schema came from the source's input data. During saved source reconstruction its diagnostic can wait for the identity check. @@ -387,10 +404,6 @@ def require_schema_without_narrow_float_keys( such column, in name order, with its type and each such part, and the remedy. """ - if converter is None: - from orcapod.contexts import resolve_context - - converter = resolve_context(None).type_converter lines = [ f" - column {field.name!r} has type {field.type} ({', '.join(found)})" for field in sorted(arrow_schema, key=lambda field: field.name) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 1e19d5997..3863002aa 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -479,7 +479,7 @@ def test_index_preserves_empty_logical_set_column(storage_type: pa.DataType) -> ) stream = ArrowTableStream(table, tag_columns=["id"], data_context=context) - result = Index("x", 1).static_process(stream).as_table() + result = Index("x", 1, fail_on_miss=False).static_process(stream).as_table() assert result.num_rows == 0 result_type = result.schema.field("x").type assert isinstance(result_type, pa.ExtensionType) @@ -2048,3 +2048,191 @@ def test_polars_source_accepts_undeclared_python_object_dict() -> None: table = DataFrameSource(columns, "id").as_table() assert table["k"].type == _dict_of(pa.float32()) assert table["k"].to_pylist() == [[{"key": 0.5, "value": 1}]] + + +_USER_CLASS_IPC_WRITER = """ +import sys +from dataclasses import make_dataclass +from pathlib import Path + +import numpy as np +import pyarrow as pa +from pydantic import ConfigDict, create_model + +from orcapod import contexts, dataclass +from orcapod.semantic_types.narrow_float_keys import converting_existing_types + + +def make_class(kind, name, field, annotation): + if kind == "pydantic": + cls = create_model( + name, + __config__=ConfigDict(arbitrary_types_allowed=True), + __module__=__name__, + **{field: (annotation, ...)}, + ) + elif kind == "structural": + cls = dataclass(name=f"test.ipc.{name}")( + type(name, (), {"__module__": __name__, "__annotations__": {field: annotation}}) + ) + else: + cls = make_dataclass( + name, [(field, annotation)], namespace={"__module__": __name__} + ) + globals()[name] = cls + return cls + + +def write(name, item): + with converting_existing_types(): + table = converter.python_dicts_to_arrow_table( + [{"id": 1, "k": item}], python_schema={"id": int, "k": type(item)} + ) + with pa.ipc.new_file(Path(sys.argv[1]) / f"{name}.arrow", table.schema) as writer: + writer.write_table(table) + + +converter = contexts.resolve_context(None).type_converter +wide = make_class("dataclass", "Wide", "entries", dict[str, int]) +write("wide", wide(entries={"string": 4})) +for inner_kind, outer_kind in [ + ("dataclass", "dataclass"), + ("dataclass", "pydantic"), + ("pydantic", "dataclass"), + ("pydantic", "pydantic"), + ("structural", "dataclass"), + ("structural", "pydantic"), + ("structural", "structural"), +]: + for container, annotation, value in [ + ("dict", dict[np.float32, int], {np.float32(0.5): 4}), + ("set", set[np.float32], {np.float32(0.5)}), + ]: + inner = make_class(inner_kind, f"{inner_kind.title()}{container}Inner", + "entries", annotation) + outer = make_class(outer_kind, f"{outer_kind.title()}{container}Outer", + "nested", inner) + write(f"{inner_kind}-{outer_kind}-{container}", outer(nested=inner(entries=value))) +""" + +_USER_CLASS_IPC_READER = """ +import asyncio +import sys +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import pyarrow as pa + +from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError +from orcapod.sources import ArrowTableSource, DataFrameSource, PollingSource +from orcapod.types import Cursor, PollingConfig + + +@dataclass +class Wide: + entries: dict[np.float32, int] + + +class Poll: + def schema(self): + return None + + async def fetch(self, cursor=None): + return Cursor(value=1), table + + async def poll(self, cursor=None): + return cursor is None + + async def close(self): + pass + + def identity(self): + return ("user-class-ipc",) + + +async def read_async(source): + rows = source.async_iter_data() + try: + _, data = await asyncio.wait_for(anext(rows), timeout=5) + return data.as_table()["k"].to_pylist() + finally: + await rows.aclose() + + +def read(route): + if route in ("arrow", "dataframe"): + cls = ArrowTableSource if route == "arrow" else DataFrameSource + return cls(table, "id", source_id=route).as_table()["k"].to_pylist() + source = PollingSource( + Poll(), "id", source_id=route, record_id_columns="id", + polling_config=PollingConfig(interval=0.01, duration=0.5), + ) + if route == "polling-async": + return asyncio.run(read_async(source)) + source.check_for_new_data() + return source.as_table()["k"].to_pylist() + + +route, directory, container = sys.argv[1:] +directory = Path(directory) +paths = [directory / "wide.arrow"] if container == "wide" else sorted( + directory.glob(f"*-{container}.arrow") +) +assert len(paths) == (1 if container == "wide" else 7) +for path in paths: + table = pa.ipc.open_file(path).read_all() + if container == "wide": + assert read(route) == [{"entries": [{"key": "string", "value": 4}]}] + else: + try: + read(route) + except NarrowFloatKeyError as exc: + expected = "dict key type float" if container == "dict" else "set element type float" + assert expected in str(exc), str(exc) + assert ".nested:" in str(exc) and ".entries:" in str(exc), str(exc) + else: + raise AssertionError(f"{route} accepted {path.name}") +""" + + +@pytest.fixture(scope="module") +def user_class_ipc(tmp_path_factory: pytest.TempPathFactory) -> Path: + path = tmp_path_factory.mktemp("user-class-ipc") + subprocess.run( + [sys.executable, "-c", _USER_CLASS_IPC_WRITER, str(path)], check=True + ) + return path + + +@pytest.mark.parametrize("route", ["arrow", "dataframe", "polling", "polling-async"]) +def test_arrow_user_class_uses_stored_fields(user_class_ipc: Path, route: str) -> None: + subprocess.run( + [ + sys.executable, + "-c", + _USER_CLASS_IPC_READER, + route, + str(user_class_ipc), + "wide", + ], + check=True, + ) + + +@pytest.mark.parametrize("route", ["arrow", "dataframe", "polling", "polling-async"]) +@pytest.mark.parametrize("container", ["dict", "set"]) +def test_arrow_nested_user_class_uses_stored_fields( + user_class_ipc: Path, route: str, container: str +) -> None: + subprocess.run( + [ + sys.executable, + "-c", + _USER_CLASS_IPC_READER, + route, + str(user_class_ipc), + container, + ], + check=True, + ) From bf6304a2977304655f0f0940a6ba8357abdf977d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:17:20 -0800 Subject: [PATCH 23/32] fix(semantic-types): retain narrow literal key validation --- .../semantic_types/narrow_float_keys.py | 21 +++++++++++--- .../test_narrow_float_keys_refused.py | 29 ++++++++++++++++++- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 43203c549..79e3ecd82 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -189,10 +189,23 @@ def _python_class_fields( def _token_float_width(token: object) -> str | None: """Read a narrow float's Arrow type name from its canonical type token.""" - if isinstance(token, dict) and isinstance(members := token.get("union"), list): - non_none = [member for member in members if member != "None"] - if len(non_none) == 1: - return _token_float_width(non_none[0]) + if isinstance(token, dict): + if isinstance(members := token.get("union"), list): + non_none = [member for member in members if member != "None"] + if len(non_none) == 1: + return _token_float_width(non_none[0]) + if isinstance(members := token.get("literal"), list): + # Identity records store literal reprs. NumPy 2 spells out the scalar + # type, while older NumPy reprs cannot distinguish its float widths. + non_none = [member for member in members if member != "None"] + for scalar, arrow_type in (("float32", "float"), ("float16", "halffloat")): + if non_none and all( + isinstance(member, str) + and member.startswith(f"np.{scalar}(") + and member.endswith(")") + for member in non_none + ): + return arrow_type if token == "numpy.float32": return "float" if token == "numpy.float16": diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 3863002aa..44c4fd06f 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -22,7 +22,7 @@ import sys from collections.abc import Callable from pathlib import Path -from typing import Any, cast, final +from typing import Any, Literal, cast, final import numpy as np import pandas as pd @@ -53,6 +53,7 @@ from orcapod.semantic_types.narrow_float_keys import ( NARROW_FLOAT_KEYS_NOT_SUPPORTED, NarrowFloatKeyError, + converting_existing_types, narrow_float_keys, require_schema_without_narrow_float_keys, ) @@ -359,6 +360,32 @@ def allow_legacy_keys(annotation: object, *, is_set: bool) -> None: require_schema_without_narrow_float_keys(declaration) +@pytest.mark.parametrize("value", [np.float32(0.5), 0.5]) +def test_arrow_user_class_retains_literal_key_width(value: np.float32 | float) -> None: + from orcapod.logical_types.canonical_form import storage_form_schema + + if isinstance(value, np.float32) and not repr(value).startswith("np.float32("): + pytest.skip("NumPy's legacy repr omits the scalar type from the identity token") + + annotation = Literal[value, None] # pyright: ignore[reportInvalidTypeForm] + cls = dataclasses.make_dataclass( + "LegacyLiteralKey", + [("entries", dict[annotation, int])], + namespace={"__module__": __name__}, + ) + converter = contexts.create_registry().get_context("v1").type_converter + with converting_existing_types(): + table = converter.python_dicts_to_arrow_table( + [{"k": cls({value: 4})}], python_schema={"k": cls} + ) + for schema in (table.schema, storage_form_schema(table.schema)): + if isinstance(value, np.float32): + with pytest.raises(NarrowFloatKeyError, match="dict key type float"): + require_schema_without_narrow_float_keys(schema) + else: + require_schema_without_narrow_float_keys(schema) + + _FRAMES = _Frames(((0.5, 1), (0.5, 2))) _PAIR_ROWS = [{"key": 0.5, "value": 1}, {"key": 0.5, "value": 2}] From fcabcb18e826613d46d1ebd16ef37a3d446f6dac Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:19:51 -0800 Subject: [PATCH 24/32] test(semantic-types): identify literal key cases explicitly --- .../test_narrow_float_keys_refused.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 44c4fd06f..d09568022 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -360,11 +360,19 @@ def allow_legacy_keys(annotation: object, *, is_set: bool) -> None: require_schema_without_narrow_float_keys(declaration) -@pytest.mark.parametrize("value", [np.float32(0.5), 0.5]) -def test_arrow_user_class_retains_literal_key_width(value: np.float32 | float) -> None: +@pytest.mark.parametrize( + ("value", "is_narrow"), + [ + pytest.param(np.float32(0.5), True, id="float32"), + pytest.param(0.5, False, id="float64"), + ], +) +def test_arrow_user_class_retains_literal_key_width( + value: np.float32 | float, is_narrow: bool +) -> None: from orcapod.logical_types.canonical_form import storage_form_schema - if isinstance(value, np.float32) and not repr(value).startswith("np.float32("): + if is_narrow and not repr(value).startswith("np.float32("): pytest.skip("NumPy's legacy repr omits the scalar type from the identity token") annotation = Literal[value, None] # pyright: ignore[reportInvalidTypeForm] @@ -379,7 +387,7 @@ def test_arrow_user_class_retains_literal_key_width(value: np.float32 | float) - [{"k": cls({value: 4})}], python_schema={"k": cls} ) for schema in (table.schema, storage_form_schema(table.schema)): - if isinstance(value, np.float32): + if is_narrow: with pytest.raises(NarrowFloatKeyError, match="dict key type float"): require_schema_without_narrow_float_keys(schema) else: From 003b2b8e161c1fda79114248c2b42e03a3bb9c9b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:57:19 -0800 Subject: [PATCH 25/32] fix(semantic-types): limit narrow-float key checks to Python declarations --- .zed/rules | 26 +- CLAUDE.md | 26 +- changelog.d/ITL-1591.md | 56 +- docs/concepts/function-pods.md | 32 +- docs/concepts/logical-type-identifiers.md | 10 +- docs/dev/design_issues/ITL-1591-NFK1.md | 63 +- src/orcapod/core/datagrams/datagram.py | 74 +- src/orcapod/core/datagrams/tag_data.py | 25 +- src/orcapod/core/function_pod.py | 10 + src/orcapod/core/nodes/source_node.py | 34 +- src/orcapod/core/sources/csv_source.py | 7 - src/orcapod/core/sources/data_frame_source.py | 27 +- .../core/sources/delta_table_source.py | 7 +- src/orcapod/core/sources/derived_source.py | 1 - src/orcapod/core/sources/dict_source.py | 7 - src/orcapod/core/sources/list_source.py | 1 - src/orcapod/core/sources/polars_input.py | 240 -- src/orcapod/core/sources/polling_source.py | 47 +- .../core/sources/spiraldb_table_source.py | 5 - src/orcapod/core/sources/stream_builder.py | 17 - .../logical_types/user_class_logical_type.py | 7 +- src/orcapod/pipeline/job.py | 4 - src/orcapod/pipeline/serialization.py | 34 +- .../semantic_types/narrow_float_keys.py | 432 +--- src/orcapod/semantic_types/nested_storage.py | 38 +- .../semantic_types/universal_converter.py | 157 +- src/orcapod/utils/schema_utils.py | 32 - .../narrow_float_arrow_main.json | 87 + .../test_narrow_float_arrow_compatibility.py | 255 ++ .../test_narrow_float_keys_refused.py | 2192 +---------------- 30 files changed, 725 insertions(+), 3228 deletions(-) delete mode 100644 src/orcapod/core/sources/polars_input.py create mode 100644 tests/test_semantic_types/narrow_float_arrow_main.json create mode 100644 tests/test_semantic_types/test_narrow_float_arrow_compatibility.py diff --git a/.zed/rules b/.zed/rules index b657504ac..6cb0ff1ba 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1572,25 +1572,13 @@ data. The rules: Batch with a size has its own form, grouping rows by arrival. A new operator whose output rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch code. -- A dict key and a set element are never `float32` or `float16` (developer, November 28, 2026, - D16 and D25, ITL-1591): a float stored under such a type is narrowed, two distinct floats - can become one stored value, and the container loses an entry. A declared type with such a - key or element is refused (`NarrowFloatKeyError`, an `InputValidationError`) where it is - declared, Python-declared and Arrow-declared alike, at any depth, by a check of types that - never reads a value. One rule, `semantic_types/narrow_float_keys.py`: the type converter - applies it to every dict and set type it builds (sources' Python schemas, datagrams, - user-class fields, a function pod's inputs and outputs when the pod is defined). - `SourceStreamBuilder.build` checks schemas at source ingestion, and explicit Arrow - declarations are checked before conversion. Saved schema text is read with its original - types by the serialization helpers. A raw `ArrowTableStream` and - Arrow-held datagrams carry already-built schemas, including operator and cached results. - A list of structs produced by aggregation can have the same Arrow shape as a dict. - A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an - Arrow map; a set is the native set container, live or in its storage form. The check - follows native container elements and user-class field declarations. Custom logical - types interpret their own storage. `float32` and - `float16` stay valid as a plain column, a list element, a struct field and a dict value; - the silent narrowing of such plain values from an Arrow declaration is ITL-1613. +- A Python declaration with a `float32` or `float16` dict key or set element raises + `NarrowFloatKeyError` (ITL-1591, D16, D25 and D41). Narrowing can turn two distinct + keys or elements into one stored value and lose an entry. The check in + `semantic_types/narrow_float_keys.py` reads Python annotations at declaration + boundaries, including native user-class fields at any depth. A registered custom + logical type owns its storage. Inferred types and Arrow inputs use their existing + conversion paths. Plain narrow floats, list elements and dict values are supported. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 3301767b3..3277855d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1620,25 +1620,13 @@ data. The rules: input (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no other per-operator batch code. -- A dict key and a set element are never `float32` or `float16` (developer, November 28, 2026, - D16 and D25, ITL-1591): a float stored under such a type is narrowed, two distinct floats - can become one stored value, and the container loses an entry. A declared type with such a - key or element is refused (`NarrowFloatKeyError`, an `InputValidationError`) where it is - declared, Python-declared and Arrow-declared alike, at any depth, by a check of types that - never reads a value. One rule, `semantic_types/narrow_float_keys.py`: the type converter - applies it to every dict and set type it builds (sources' Python schemas, datagrams, - user-class fields, a function pod's inputs and outputs when the pod is defined). - `SourceStreamBuilder.build` checks schemas at source ingestion, and explicit Arrow - declarations are checked before conversion. Saved schema text is read with its original - types by the serialization helpers. A raw `ArrowTableStream` and - Arrow-held datagrams carry already-built schemas, including operator and cached results. - A list of structs produced by aggregation can have the same Arrow shape as a dict. - A dict declaration uses the converter's one dict shape (`nested_storage.dict_entry_fields`; never write a second shape test) or an - Arrow map; a set is the native set container, live or in its storage form. The check - follows native container elements and user-class field declarations. Custom logical - types interpret their own storage. `float32` and - `float16` stay valid as a plain column, a list element, a struct field and a dict value; - the silent narrowing of such plain values from an Arrow declaration is ITL-1613. +- A Python declaration with a `float32` or `float16` dict key or set element raises + `NarrowFloatKeyError` (ITL-1591, D16, D25 and D41). Narrowing can turn two distinct + keys or elements into one stored value and lose an entry. The check in + `semantic_types/narrow_float_keys.py` reads Python annotations at declaration + boundaries, including native user-class fields at any depth. A registered custom + logical type owns its storage. Inferred types and Arrow inputs use their existing + conversion paths. Plain narrow floats, list elements and dict values are supported. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 8c6b1d020..0a8eb3b06 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -1,52 +1,12 @@ -### Breaking changes and migration +### Fixed -- **`float32` and `float16` are refused as a dict key type and as a set element type** - (ITL-1591). A float stored under such a type is narrowed, and two distinct floats can - narrow to one stored value (`1e-50` and `2e-50` both become `0.0`), so a dict or a set - lost an entry without notice. A declared type with such a key or element, at any nesting - depth (a dict in a list, a dict as a dict value, a dict in a tuple or a user-class field, - an Arrow `map`), now raises `NarrowFloatKeyError` (an `InputValidationError`) naming the - column and the key or element type, where the type is declared: a source's Python or - Arrow schema, a pipeline's declared input slot, a datagram's Python schema or - explicitly typed new column, and a function pod's parameters and outputs when the pod is defined - (`-> dict[np.float32, int]`, `set[np.float32]`). This also covers Arrow readers and - nested and top-level column mappings with Arrow arrays or Arrow-backed pandas Series - given to Polars-backed sources, Arrow-backed pandas frames and sequences of Series, - and explicit Arrow schemas - given to the Python-to-Arrow converter. The check reads types only, never a - value. Declare the key or element as `float64` (`float` in Python, `pa.float64()` in - Arrow), or use another type. Arrow `float32` and `float16` are still accepted as a plain - column, a list element, a struct field and a dict value. At a declaration boundary, - a bare Arrow list (plain, large or fixed-size) of structs with exactly `key` and - `value` fields counts as a dict regardless of intent, as does an Arrow map. Custom - logical types own their storage, including when their identifiers are stored in - field metadata. The check follows native list and set element types and declared - user-class fields. Already-built operator results and their caches bypass the - declaration check, including `Batch` results with the same list-of-structs shape. -- Loading saved jobs and blueprints preserves legacy schema types, including float32 - or float16 keys and set elements. Saved jobs also preserve bindings whose rebuilt - inputs match the saved pipeline identity, including Delta and SpiralDB tables. A narrow - key in a changed live input schema raises `NarrowFloatKeyError` during load. +- Python declarations of `float32` or `float16` dictionary keys or set elements raise + `NarrowFloatKeyError` in function pods, Python schemas for sources and stream input + slots, and `Data` (ITL-1591). The check follows nested Python types and stored fields + of user classes. Two distinct values can narrow to one stored value and lose an entry. + Declare the key or element as `float` to retain double precision. ### Known limitations -- Inference still accepts undeclared float32 keys and set elements in Python data. - For example, `Data({"k": {np.float32(0.5): 1}}).as_table()` succeeds - (ITL-1668, ITL-1667). -- A plain value (not a dict key or set element) stored into a column that an Arrow schema - declares `float32` or `float16` is still narrowed without a warning: `0.1` under - `pa.float16()` is stored as `0.0999755859375` (ITL-1613). -- A raw `ArrowTableStream` still accepts an already-built Arrow table with the dict - shape. Updating an Arrow-held datagram can still narrow two keys to one. For example, - - ```python - import pyarrow as pa - from orcapod.core.datagrams import Data - from orcapod.core.streams import ArrowTableStream - - key_type = pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())])) - table = pa.table({"id": [1], "k": pa.array([[]], type=key_type)}) - ArrowTableStream(table, tag_columns=["id"]) - row = Data(table).update(k={1e-50: 1, 2e-50: 2}) - assert row.as_dict()["k"] == {0.0: 2} - ``` +- Arrow input with a narrow-float dictionary key or set element is accepted as on main. + For example, `Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` returns `{0.0: 2}`. This is a follow-up issue to be filed by the coordinator. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 4a9866cf1..5dfe8b782 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -285,28 +285,16 @@ 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 dictionary key and a set element cannot be `np.float32` or `np.float16` -(`dict[np.float32, int]`, `set[np.float32]`, at any depth): a float stored under such a type -is narrowed, two distinct floats can become one stored value, and the dictionary or set would -lose an entry. Such a parameter or output raises `NarrowFloatKeyError` when the pod is -defined (ITL-1591). Declare the key or element as `float`. `np.float32` remains valid as a -plain value, a list element and a dictionary value. - -#### What counts as a dict here - -At a declared Arrow input, an Arrow map or a bare list of structs with exactly the -fields `key` and `value` counts as a dict regardless of intent. This includes plain, -large and fixed-size lists. Custom logical types own their storage, whether Arrow -carries the extension type directly or records it in field metadata. A registered -class that exposes `set[str]` or `dict[str, int]` can therefore use float32-backed -storage. The check follows the element type of Orcapod's native lists and sets and -the declared fields of its user classes. - -The check runs when a type is declared and enters the pipeline. For example, a source -that supplies a bare `large_list>` is refused. -`Batch` can produce that same type by collecting a source's plain `key`/`value` struct -column. The already-built result and its cached rows remain usable. Reading a saved -schema also preserves the types it records. +A Python declaration of a dictionary key or set element as `np.float32` or +`np.float16` raises `NarrowFloatKeyError` when the pod is defined (ITL-1591). +The check follows nested Python types, including the stored fields of user classes. +Two distinct values can narrow to the same stored value and lose an entry. Declare +the key or element as `float` to retain double precision. Narrow floats are supported +as plain values, list elements and dictionary values. + +The same check applies when a source, stream input slot or `Data` declares a Python +schema. Arrow tables and Arrow schemas use the existing Arrow conversion path. +A narrow-float key or set element arriving as Arrow data can still lose an entry. 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 d9208b217..a6de37b62 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -182,11 +182,11 @@ print(labels_type.storage_type) `NestedTypeNotStorableError` that names the column or `Class.field` (ITL-1150). Hold the set in a dataclass field, where it keeps its type, or declare the plain type (`dict[str, list[int]]`). -- A set of `float32` or `float16` elements is refused where it is declared, in Python - (`set[np.float32]`) and in Arrow (`set[float]`, `set[halffloat]`), with a - `NarrowFloatKeyError`: a float stored under such a type is narrowed, two distinct floats can - become one stored element, and the set would lose one (ITL-1591). Declare `set[float]` - (`set[double]`). The same holds for the key of a dict. +- A Python declaration like `set[np.float32]` or `set[np.float16]` raises + `NarrowFloatKeyError` (ITL-1591). Two distinct floats can narrow to one stored + element and lose an entry. Declare `set[float]` to retain double precision. + The same rule applies to Python dictionary keys. Arrow inputs use the existing + Arrow conversion path. - `frozenset[T]` is not supported: declare `set[T]`. Support is to be evaluated in ITL-1140. A container type you implement yourself is not a native container. It is an ordinary logical diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 760a7572b..6316c9fd0 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -1,55 +1,24 @@ ## `src/orcapod/semantic_types/universal_converter.py` -### NFK1 — A float32 or float16 dict key or set element loses an entry when a float is narrowed +### NFK1 — Declared narrow-float dictionary keys and set elements can lose entries **Status:** resolved **Severity:** high **Issue:** ITL-1591 (related: ITL-924, ITL-1613) -A Python float stored under a `float32` or `float16` type is narrowed without notice, and two -distinct floats can narrow to one stored value (`1e-50` and `2e-50` both become `0.0`). For -the keys of a dict and the elements of a set that lost an entry: a `DictSource` with an Arrow -`data_schema` whose column `k` is `large_list>` stored -`{1e-50: 1, 2e-50: 2}` with two `0.0` keys, a set column `{1e-50, 2e-50}` was stored as -`[0.0, 0.0]` and read back `{0.0}`, and updating a datagram held as an Arrow table did the -same. No warning, no error. +Two distinct Python floats can narrow to the same `float32` or `float16` value. +For example, `1e-50` and `2e-50` both become `0.0`. A dict or set read back from +that representation can have fewer entries than the original. -**Fix:** developer decisions D16 and D25 (November 28, 2026): a declared type whose dict key -or set element is `float32` or `float16` is refused where it is declared, in a Python schema -or annotation and in an Arrow schema or table alike, at any nesting depth, by a check of -types that reads no value. One rule, `semantic_types/narrow_float_keys.py` -(`NarrowFloatKeyError`, an `InputValidationError`): the type converter applies it to every -dict and set type it builds (so a source's Python schema, a datagram's, a user-class field -and a function pod's declared inputs and outputs, when the pod is defined). The source -builder checks schemas at source ingestion. Explicit Arrow schemas are also checked before -source value conversion and when a datagram adds a column with a declared type. The -converter checks explicit Arrow declarations before converting Python rows and checks -plain Python set element types, including when no logical type registry is configured. -The Polars-backed sources keep the incoming Arrow declarations for the schema check -when importing arrays or streams, including Arrow-backed pandas columns passed in -column mappings at any depth, sequences and iterators. The check uses those declarations before building the stream. The input data follows its usual -conversion path. -The saved-source resolver keeps input types when the rebuilt source matches its saved -pipeline hash. A narrow key in a changed input schema raises a declaration error during -job load. Schema readers preserve the types recorded in saved jobs, proxies and -blueprints, including legacy narrow float keys and elements. Public slot declarations -check any Arrow override and each explicitly declared Python role, including when the -other Python role comes from a bound stream. -Under D38 (November 29, 2026), a bare Arrow list (plain, large or fixed-size) of -structs with exactly `key` and `value` fields is a dict regardless of intent. -`nested_storage.dict_entry_fields` defines the shape. An Arrow map is also a dict. -Custom logical types own their storage, including when the extension identifier is -in field metadata. This includes a class that exposes `set[str]` or `dict[str, int]` -over float32-backed storage. The check follows native list and set element types. -For Arrow inputs, it follows user-class field type tokens in the extension's identity -record, including nested records. For Python declarations, it follows the class's -field annotations. Plain narrow-float columns, list elements, struct fields and dict -values remain accepted. +**Fix:** D41 selects fallback (b) for D16 and D25. At a Python declaration boundary, +`semantic_types/narrow_float_keys.py` raises `NarrowFloatKeyError` for a narrow-float +dict key or set element. It checks function pod inputs and outputs, source and +stream slot Python schemas, and datagrams. It follows native container annotations +and stored fields of native user classes, including nested classes. A registered +custom logical type owns its storage. Plain narrow-float values, list elements and +dict values remain supported. -Open points: an undeclared dict or set built from Python values can still infer a -float32 key or element (ITL-1668, ITL-1667). An Arrow-held datagram can still narrow two keys to one when updated with -Python floats. A raw `ArrowTableStream` still accepts the same Arrow type. Both APIs also -carry already-built operator results. Under D28, a `Batch` result that collects a plain -`key`/`value` struct column bypasses the declaration check, as do stored results and -saved schemas. Supplying the same bare list shape with a narrow-float key as a source's -Arrow input triggers the check. An Arrow-declared plain value can still narrow silently -(ITL-1613). +**Known limitations:** Schema-free Python inference and Arrow input retain main's +behavior. Arrow tables, declared Arrow schemas, raw streams, saved schemas and +stored results can still carry these types. For example, +`Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` +returns `{0.0: 2}`. Arrow input is a follow-up issue to be filed by the coordinator. diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index e805d2fa6..91c4cdedc 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -38,13 +38,12 @@ 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.narrow_float_keys import ( - converting_existing_types, - require_schema_without_narrow_float_keys, + materializing_inferred_schema, + require_python_schema_without_narrow_float_keys, ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import require_python_schema_without_narrow_float_keys logger = logging.getLogger(__name__) @@ -193,7 +192,7 @@ def _init_from_dict( if python_schema else inferred ) - if python_schema: + if python_schema is not None: require_python_schema_without_narrow_float_keys( python_schema, self.converter ) @@ -246,6 +245,7 @@ def _init_from_table( ) table = arrow_utils.normalize_table_to_large_types(table) + # Extract context from table if not provided externally if constants.CONTEXT_KEY in table.column_names and data_context is None: data_context = table[constants.CONTEXT_KEY].to_pylist()[0] @@ -420,8 +420,7 @@ def _ensure_data_table(self) -> pa.Table: """ if self._data_table is None: assert self._data_dict is not None - # Explicit Python types were checked when the datagram was built. - with converting_existing_types(): + with materializing_inferred_schema(): self._data_table = self.converter.python_dicts_to_arrow_table( [self._data_dict], self._data_python_schema, @@ -451,12 +450,9 @@ def _ensure_arrow_schema(self) -> pa.Schema: if self._data_table is not None: self._data_arrow_schema = self._data_table.schema else: - with converting_existing_types(): - self._data_arrow_schema = ( - self.converter.python_schema_to_arrow_schema( - self._ensure_python_schema() - ) - ) + self._data_arrow_schema = self.converter.python_schema_to_arrow_schema( + self._ensure_python_schema() + ) return self._data_arrow_schema def _ensure_context_table(self) -> pa.Table: @@ -478,7 +474,7 @@ def _ensure_meta_table(self) -> pa.Table | None: if not self._meta: return None if self._meta_table is None: - with converting_existing_types(): + with materializing_inferred_schema(): self._meta_table = self.converter.python_dicts_to_arrow_table( [self._meta], python_schema=self._meta_python_schema ) @@ -775,11 +771,11 @@ def with_meta_columns(self, **meta_updates: DataValue) -> Self: ) ) if prefixed: - with converting_existing_types(): + with materializing_inferred_schema(): tables.append( self.converter.python_dicts_to_arrow_table( [prefixed], - python_schema=new_inferred, + python_schema=Schema({k: merged[k] for k in prefixed}), ) ) meta_names = list(new_d.meta_columns) @@ -1025,14 +1021,9 @@ def update(self, **updates: DataValue) -> Self: sub_schema = arrow_utils.schema_select( self._data_table.schema, list(updates.keys()) ) - # This schema came from the held table. Only convert values for its - # existing fields, which can also represent operator-built types. - converter = self.converter - storage_rows = converter.python_dicts_to_struct_dicts( - [updates], - python_schema=converter.arrow_schema_to_python_schema(sub_schema), + update_table = self.converter.python_dicts_to_arrow_table( + [updates], arrow_schema=sub_schema ) - update_table = pa.Table.from_pylist(storage_rows, schema=sub_schema) new_d = self.copy(include_cache=False) new_d._data_table = arrow_utils.hstack_tables( self._data_table.drop_columns(list(updates.keys())), update_table @@ -1087,6 +1078,11 @@ def _new_columns_table( if name not in updates: continue if isinstance(declared, pa.Field): + if updates[name] is None and not declared.nullable: + raise ValueError( + f"Column {name!r} is declared non-nullable" + + f" ({declared}) but its value is None" + ) arrow_fields[name] = declared.with_name(name) elif isinstance(declared, pa.DataType): arrow_fields[name] = pa.field( @@ -1094,30 +1090,28 @@ def _new_columns_table( ) else: python_schema[name] = declared - arrow_schema = pa.schema(list(arrow_fields.values())) - require_schema_without_narrow_float_keys(arrow_schema, converter=self.converter) - for name, field in arrow_fields.items(): - if updates[name] is None and not field.nullable: - raise ValueError( - f"Column {name!r} is declared non-nullable" - f" ({column_types[name]}) but its value is None" + inferred_names = [n for n in updates if n not in column_types] + if inferred_names: + python_schema.update( + infer_python_schema_from_pylist_data( + [{n: updates[n] for n in inferred_names}] ) - inferred = {n: value for n, value in updates.items() if n not in column_types} + ) + tables: list[pa.Table] = [] - if inferred: - tables.append(self.converter.python_dicts_to_arrow_table([inferred])) if python_schema: - tables.append( - self.converter.python_dicts_to_arrow_table( - [{n: updates[n] for n in python_schema}], - python_schema=python_schema, + with materializing_inferred_schema(): + tables.append( + self.converter.python_dicts_to_arrow_table( + [{n: updates[n] for n in python_schema}], + python_schema=python_schema, + ) ) - ) if arrow_fields: tables.append( self.converter.python_dicts_to_arrow_table( [{n: updates[n] for n in arrow_fields}], - arrow_schema=arrow_schema, + arrow_schema=pa.schema(list(arrow_fields.values())), ) ) return arrow_utils.hstack_tables(*tables).select(list(updates)) @@ -1189,10 +1183,10 @@ def with_columns( # Arrow type. Existing columns keep their Arrow fields (converted # from the Python schema if the table was not loaded); only the new # columns are typed (declared) or inferred (undeclared). - new_columns = self._new_columns_table(updates, column_types or {}) new_d = self.copy(include_cache=False) new_d._data_table = arrow_utils.hstack_tables( - self._ensure_data_table(), new_columns + self._ensure_data_table(), + self._new_columns_table(updates, column_types or {}), ) new_d._data_dict = None new_d._data_python_schema = None diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index 15a2a086f..c5fc7d180 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -26,6 +26,7 @@ from orcapod import contexts from orcapod.core.datagrams.datagram import Datagram, context_key_field from orcapod.semantic_types import infer_python_schema_from_pylist_data +from orcapod.semantic_types.narrow_float_keys import materializing_inferred_schema from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, @@ -165,12 +166,13 @@ def _merge_system_tag_table( table.drop_columns(list(replacements)), updated ).select(table.column_names) if additions: - added = self.converter.python_dicts_to_arrow_table( - [additions], - python_schema=infer_python_schema_from_pylist_data( - [additions], default_type=str - ), - ) + with materializing_inferred_schema(): + added = self.converter.python_dicts_to_arrow_table( + [additions], + python_schema=infer_python_schema_from_pylist_data( + [additions], default_type=str + ), + ) table = arrow_utils.hstack_tables(table, added) return table @@ -251,12 +253,13 @@ def rows_of( def _ensure_system_tags_table(self) -> "pa.Table": if self._system_tags_table is None: - self._system_tags_table = ( - self._data_context.type_converter.python_dicts_to_arrow_table( - [self._system_tags], - python_schema=self._system_tags_python_schema, + with materializing_inferred_schema(): + self._system_tags_table = ( + self._data_context.type_converter.python_dicts_to_arrow_table( + [self._system_tags], + python_schema=self._system_tags_python_schema, + ) ) - ) return self._system_tags_table # ------------------------------------------------------------------ diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index fd8910acb..08c4c748a 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -19,6 +19,9 @@ import pyarrow as pa from orcapod import contexts +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) from orcapod.channels import ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig import orcapod.core.row_ids as row_ids @@ -146,6 +149,13 @@ def __init__( f"(schema keys: {list(data_function.input_data_schema.keys())})" ) self._ctx_arg_name: str | None = ctx_arg_name + converter = self.data_context.type_converter + require_python_schema_without_narrow_float_keys( + self.input_data_schema, converter + ) + require_python_schema_without_narrow_float_keys( + data_function.output_data_schema, converter + ) # 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, diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 2fd2f8cea..3def21807 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -23,8 +23,7 @@ from orcapod import contexts from orcapod.semantic_types.narrow_float_keys import ( - NarrowFloatKeyError, - require_schema_without_narrow_float_keys, + require_python_schema_without_narrow_float_keys, ) from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig @@ -72,7 +71,6 @@ arrow_schema_identity, compute_schema_hash, declared_arrow_schema, - require_python_schema_without_narrow_float_keys, ) if TYPE_CHECKING: @@ -418,8 +416,6 @@ def _columns_without_arrow_type( seen.add(name) try: declared_arrow_schema({name: python_type}, converter) - except NarrowFloatKeyError: - raise except (ValueError, TypeError): missing.append((name, python_type)) return missing @@ -579,8 +575,6 @@ def __init__( "arrow_schemas is given by tag_schema and data_schema already" ) converter = self.data_context.type_converter - require_schema_without_narrow_float_keys(tag_schema, converter=converter) - require_schema_without_narrow_float_keys(data_schema, converter=converter) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). tag_schema = declaration_form_schema(tag_schema, converter) @@ -588,12 +582,8 @@ 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 arrow_schemas is not None and not _inherited_types: + elif not _inherited_types: converter = self.data_context.type_converter - for schema in arrow_schemas: - require_schema_without_narrow_float_keys(schema, converter=converter) - # A supplied Arrow mapping may cover Python types the converter does - # not know. Still check both roles for prohibited Python declarations. require_python_schema_without_narrow_float_keys(tag_schema, converter) require_python_schema_without_narrow_float_keys(data_schema, converter) self._name = name @@ -1692,6 +1682,13 @@ def __init__( "SourceJobNode requires either explicit tag_schema/data_schema " "or a bound_source to derive schemas from." ) + if not _inherited_types: + converter = contexts.resolve_context(data_context).type_converter + for schema in (tag_schema, data_schema): + if schema is not None: + require_python_schema_without_narrow_float_keys( + schema, converter + ) derived_tag, derived_data = bound_source.output_schema() if arrow_schemas is None: # Each role's Arrow schema from where that role comes from: an omitted @@ -1708,19 +1705,6 @@ def __init__( if data_schema is None else declared_arrow_schema(data_schema, converter), ) - elif not _inherited_types: - # Both Arrow schemas were supplied by the caller. Only the Python - # roles that were supplied are declarations. - converter = contexts.resolve_context(data_context).type_converter - for schema in arrow_schemas: - require_schema_without_narrow_float_keys( - schema, converter=converter - ) - for python_schema in (tag_schema, data_schema): - if python_schema is not None: - require_python_schema_without_narrow_float_keys( - python_schema, converter - ) if tag_schema is None: tag_schema = derived_tag if data_schema is None: diff --git a/src/orcapod/core/sources/csv_source.py b/src/orcapod/core/sources/csv_source.py index 9d7f2bc6f..e44f9c189 100644 --- a/src/orcapod/core/sources/csv_source.py +++ b/src/orcapod/core/sources/csv_source.py @@ -10,9 +10,6 @@ import pyarrow as pa from typing_extensions import override -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.core.sources.base import RootSource, saved_tag_only_columns from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.source_ids import location_source_name @@ -312,10 +309,6 @@ def __init__( # Every later read (a check, ITL-1102) opens the file found now, whatever the # working directory is then. self._access_path = os.path.abspath(file_path) - if schema is not None: - require_schema_without_narrow_float_keys( - schema, converter=self.data_context.type_converter - ) self._schema = schema self._tag_columns: Collection[str] = _normalize_column_list(tag_columns) self._system_tag_columns: Collection[str] = system_tag_columns diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index 941900d79..a435b32fb 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -8,13 +8,6 @@ import polars as pl import pyarrow as pa -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) -from orcapod.core.sources.polars_input import ( - dataframe_with_input_schema, - require_polars_input_types, -) from orcapod.core.sources.base import RootSource from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.stream_builder import SourceStreamBuilder @@ -80,13 +73,7 @@ def __init__( ) -> None: super().__init__(source_id=source_id, **kwargs) - if schema is not None: - require_schema_without_narrow_float_keys( - schema, converter=self.data_context.type_converter - ) - arrow_input_schema = None - input_schema = None # Keep pandas and Polars on their native paths even if they export Arrow. # For Arrow inputs, materialize once before Polars drops field metadata. if not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)) and ( @@ -106,20 +93,13 @@ def __init__( arrow_input, system_tag_columns, schema=schema ) arrow_input_schema = arrow_input.schema - require_schema_without_narrow_float_keys( - arrow_input_schema, - source_input=True, - converter=self.data_context.type_converter, - ) # Polars rechunks native tables but preserves chunks on exporter inputs. df = cast( pl.DataFrame, pl.from_arrow(arrow_input, rechunk=isinstance(data, pa.Table)), ) else: - df, input_schema = dataframe_with_input_schema( - data, self.data_context.type_converter - ) + df = pl.DataFrame(data) # Convert any Object-dtype columns to Arrow-compatible types. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] @@ -151,10 +131,6 @@ def __init__( raise ValueError(f"TagProtocol column(s) not found in data: {missing}") arrow_table = df.to_arrow() - if arrow_input_schema is None: - require_polars_input_types( - arrow_table.schema, input_schema, self.data_context.type_converter - ) if schema is not None: require_supported_nullable_types(schema) if arrow_input_schema is None: @@ -182,7 +158,6 @@ def __init__( builder = SourceStreamBuilder(self.data_context) result = builder.build( arrow_table, - input_types_checked=True, tag_columns=tag_columns, data_tags=source_data_tags(tag_columns, tag_only_columns), source_name=self._source_name, diff --git a/src/orcapod/core/sources/delta_table_source.py b/src/orcapod/core/sources/delta_table_source.py index a7d60582b..8a9b272f1 100644 --- a/src/orcapod/core/sources/delta_table_source.py +++ b/src/orcapod/core/sources/delta_table_source.py @@ -97,7 +97,7 @@ def __init__( self._tag_only_columns: tuple[str, ...] = tuple( c for c in self._tag_columns if c not in data_tags ) - result = self._build(table, inherited_types=False) + result = self._build(table) self._stream = result.stream self._tag_columns = result.tag_columns self._system_tag_columns = result.system_tag_columns @@ -112,7 +112,7 @@ def _read_table(self) -> "pa.Table": self._delta_table, as_large_types=True ).to_table() - def _build(self, table: "pa.Table", *, inherited_types: bool) -> SourceStreamResult: + def _build(self, table: "pa.Table") -> SourceStreamResult: """Enrich ``table`` as this source's stream (source info, system tags).""" builder = SourceStreamBuilder(self.data_context) return builder.build( @@ -123,7 +123,6 @@ def _build(self, table: "pa.Table", *, inherited_types: bool) -> SourceStreamRes kind_part=self.kind_part(), record_id_columns=self._record_id_columns or (), system_tag_columns=self._system_tag_columns, - inherited_types=inherited_types, ) @override @@ -159,7 +158,7 @@ def check_for_new_data(self) -> bool: if same_rows(self._table, table, ordered=not self._record_id_columns): self._version = version return False - stream = self._build(table, inherited_types=True).stream + stream = self._build(table).stream self._version = version self._stream = stream self._table = table diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 716b281ee..b92d03ffe 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -674,7 +674,6 @@ def _derive_from( data_tags=self._data_tags(), source_name=self.source_name, kind_part=self.kind_part(), - inherited_types=True, record_id_columns=self._record_id_columns or (), ) return result.stream diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 27a76abb6..26eefb169 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -17,9 +17,6 @@ declare_native_custom_system_tags, require_supported_nullable_types, ) -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.types import DataValue, SchemaLike from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -89,9 +86,6 @@ def __init__( # Accept either a Python SchemaLike (Mapping[str, type]) or a # pa.Schema directly via data_schema; route to the converter accordingly. if isinstance(data_schema, pa.Schema): - require_schema_without_narrow_float_keys( - data_schema, converter=self.data_context.type_converter - ) require_supported_nullable_types(data_schema) arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( rows, @@ -123,7 +117,6 @@ def __init__( kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, - input_types_checked=data_schema is None, system_tag_columns=system_tag_columns, ) diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index b9fadd4ce..1433cbc71 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -157,7 +157,6 @@ def __init__( kind_part=self.kind_part(), record_id_columns=self._key_columns, hash_in_key_order=hash_in_key_order, - input_types_checked=data_schema is None, ) self._stream = result.stream diff --git a/src/orcapod/core/sources/polars_input.py b/src/orcapod/core/sources/polars_input.py deleted file mode 100644 index 0abbf907b..000000000 --- a/src/orcapod/core/sources/polars_input.py +++ /dev/null @@ -1,240 +0,0 @@ -"""Keep declared Arrow types available across Polars' source input conversion.""" - -from __future__ import annotations - -import ctypes -from collections.abc import Iterable, Iterator, Mapping, Sequence, Sized -from itertools import chain -from typing import TYPE_CHECKING, cast, final - -import pandas as pd -import polars as pl -import pyarrow as pa - -from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) - -if TYPE_CHECKING: - from polars._typing import ( - ArrowArrayExportable, - ArrowStreamExportable, - FrameInitTypes, - ) - - -# The C Data and Stream interfaces allow an opaque provider to supply its schema -# without importing any arrays into PyArrow. Polars gets the original capsules. -@final -class _ArrowSchema(ctypes.Structure): - """The stable Arrow C Data Interface schema ABI.""" - - _fields_ = [ - ("format", ctypes.c_void_p), - ("name", ctypes.c_void_p), - ("metadata", ctypes.c_void_p), - ("flags", ctypes.c_int64), - ("n_children", ctypes.c_int64), - ("children", ctypes.c_void_p), - ("dictionary", ctypes.c_void_p), - ("release", ctypes.c_void_p), - ("private_data", ctypes.c_void_p), - ] - if TYPE_CHECKING: - release: int | None = None - - -_get_capsule_pointer = ctypes.pythonapi.PyCapsule_GetPointer -_get_capsule_pointer.argtypes = [ctypes.py_object, ctypes.c_char_p] -_get_capsule_pointer.restype = ctypes.c_void_p -_GetStreamSchema = ctypes.PYFUNCTYPE( - ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(_ArrowSchema) -) - - -@ctypes.CFUNCTYPE(None, ctypes.POINTER(_ArrowSchema)) -def _release_borrowed_schema(schema: ctypes._Pointer[_ArrowSchema]) -> None: # noqa: SLF001 - """Mark the copied schema released while the original owns all pointers.""" - schema.contents.release = None - - -@final -class _InspectArrowArray: - """Read the schema on export and hand Polars the same array and schema.""" - - def __init__(self, provider: ArrowArrayExportable) -> None: - self._provider = provider - self.schema: pa.Schema | None = None - - def __arrow_c_array__( - self, requested_schema: object | None = None - ) -> tuple[object, object]: - export = self._provider.__arrow_c_array__ - schema, array = ( - export() if requested_schema is None else export(requested_schema) - ) - pointer = cast("int", _get_capsule_pointer(schema, b"arrow_schema")) - borrowed = _ArrowSchema.from_buffer_copy(_ArrowSchema.from_address(pointer)) - borrowed.release = ctypes.cast(_release_borrowed_schema, ctypes.c_void_p).value - field = pa.Field._import_from_c(ctypes.addressof(borrowed)) - if isinstance(field.type, pa.StructType): - self.schema = pa.schema(list(field.type)) - return schema, array - - -@final -class _InspectArrowStream: - """Read the schema from the same stream capsule that Polars will consume.""" - - def __init__(self, provider: ArrowStreamExportable) -> None: - self._provider = provider - self.schema: pa.Schema | None = None - - def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: - export = self._provider.__arrow_c_stream__ - stream = export() if requested_schema is None else export(requested_schema) - pointer = cast("int", _get_capsule_pointer(stream, b"arrow_array_stream")) - # get_schema is the first member. Each call returns a separately owned - # schema and does not advance the stream. - get_schema = ctypes.cast( - ctypes.c_void_p.from_address(pointer), _GetStreamSchema - ) - schema = _ArrowSchema() - if status := get_schema(pointer, ctypes.byref(schema)): - raise pa.ArrowInvalid( - f"Arrow stream get_schema failed with status {status}" - ) - self.schema = pa.Schema._import_from_c(ctypes.addressof(schema)) - return stream - - -def _pandas_arrow_fields(columns: Iterable[object]) -> Iterator[pa.Field[pa.DataType]]: - """Read Arrow-backed pandas column declarations straight from their dtypes.""" - for column in columns: - if isinstance(column, (pd.Series, pd.Index)) and isinstance( - column.dtype, pd.ArrowDtype - ): - yield pa.field(str(column.name), column.dtype.pyarrow_dtype) - - -PolarsInputSchema = pa.Schema | pl.Schema | Mapping[str, object] | None - - -def _mapping_arrow_fields( - columns: Mapping[str, object], -) -> Iterator[pa.Field[pa.DataType]]: - """Read Arrow declarations carried by a column mapping, including nested columns.""" - for name, column in columns.items(): - name = str(name) - if isinstance(column, (pa.Array, pa.ChunkedArray)): - yield pa.field(name, column.type) - elif isinstance(column, (pd.Series, pd.Index)) and isinstance( - column.dtype, pd.ArrowDtype - ): - yield pa.field(name, column.dtype.pyarrow_dtype) - elif isinstance(column, dict): - children = list(_mapping_arrow_fields(column)) - if children: - yield pa.field(name, pa.struct(children)) - - -def dataframe_with_input_schema( - data: FrameInitTypes, - converter: TypeConverterProtocol, -) -> tuple[pl.DataFrame, PolarsInputSchema]: - """Run the usual Polars constructor and retain any original Arrow declarations. - - Polars may discard a native list or set identifier while importing, so the - source uses the incoming Arrow fields to check the declaration. For a - typed Polars input, retain the column types supplied by the caller. - """ - schema: PolarsInputSchema = None - observed = None - fields: list[pa.Field[pa.DataType]] = [] - if isinstance(data, (pa.Table, pa.RecordBatch, pa.RecordBatchReader)): - schema = data.schema - elif isinstance(data, pa.StructArray): - schema = pa.schema(list(data.type)) - elif isinstance(data, pd.DataFrame): - fields.extend( - pa.field(str(name), dtype.pyarrow_dtype) - for name, dtype in data.dtypes.items() - if isinstance(dtype, pd.ArrowDtype) - ) - elif isinstance(data, pl.DataFrame): - schema = data.schema - elif isinstance(data, pl.Series): - schema = pl.Schema({data.name: data.dtype}) - elif isinstance(data, Mapping): - schema = data - elif isinstance(data, Sequence): - if len(data) and isinstance(data[0], (pd.Series, pd.Index)): - fields.extend(_pandas_arrow_fields(data)) - elif not isinstance(data, (pl.DataFrame, pl.Series)): - if ( - not hasattr(data, "__arrow_c_stream__") - and isinstance(data, Iterable) - and not isinstance(data, Sized) - ): - data = _observe_pandas_iterator(data, fields) - elif callable(getattr(data, "__arrow_c_array__", None)): - observed = data = _InspectArrowArray(cast("ArrowArrayExportable", data)) - elif callable(getattr(data, "__arrow_c_stream__", None)): - observed = data = _InspectArrowStream(cast("ArrowStreamExportable", data)) - - def original_schema() -> PolarsInputSchema: - if observed is not None: - return observed.schema - return pa.schema(fields) if fields else schema - - try: - frame = pl.DataFrame(data) - except (pa.ArrowException, pl.exceptions.PolarsError, pl.exceptions.PanicException): - # Polars can fail to import some types entirely (for example a union). - # Prefer the known declaration error if a field has a prohibited key. - if (declaration := original_schema()) is not None: - require_polars_input_types(pa.schema([]), declaration, converter) - raise - return frame, original_schema() - - -def _observe_pandas_iterator( - data: Iterable[object], fields: list[pa.Field[pa.DataType]] -) -> Iterator[object]: - """Observe schemas of streamed columns, leaving ordinary row data untouched.""" - iterator = iter(data) - end = object() - head = next(iterator, end) - if head is end: - return - items = chain((head,), iterator) - if isinstance(head, (pd.Series, pd.Index)): - for column in items: - fields.extend(_pandas_arrow_fields((column,))) - yield column - else: - yield from items - - -def require_polars_input_types( - converted: pa.Schema, original: PolarsInputSchema, converter: TypeConverterProtocol -) -> None: - """Validate the declared fields of the input to Polars.""" - if original is None: - return - if isinstance(original, pa.Schema): - declaration = original - elif isinstance(original, pl.Schema): - declaration = pa.schema( - [ - field - for field in converted - if field.name in original and original[field.name] != pl.Object - ] - ) - else: - declaration = pa.schema(_mapping_arrow_fields(original)) - require_schema_without_narrow_float_keys( - declaration, source_input=True, converter=converter - ) diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index ef071db6a..9759ab212 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -16,7 +16,7 @@ import threading from collections.abc import Collection from math import floor -from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast +from typing import Any, ClassVar, Generic, TYPE_CHECKING, TypeVar, cast import polars as pl import pyarrow as pa @@ -24,39 +24,35 @@ from orcapod.core.identity_chains import refuse_identity_io from orcapod.core.sources.base import RootSource -from orcapod.core.sources.polars_input import ( - dataframe_with_input_schema, - require_polars_input_types, -) from orcapod.core.sources.source_ids import hash_source_name +from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.core.sources.stream_builder import ( SourceStreamBuilder, normalize_record_id_columns, require_supported_nullable_types, validate_source_table, ) +from orcapod.core.streams.view import ( + ViewStatus, + StreamView, +) from orcapod.core.streams.base import ( check_head_size, typed_zero_row_table, ) -from orcapod.core.streams.view import ( - StreamView, - ViewStatus, -) from orcapod.errors import ( CursorInvalidatedError, InputValidationError, RowIdentifierError, SchemaInconsistencyError, ) -from orcapod.logical_types.canonical_form import declaration_form_schema -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, ContentHash, Cursor, PollingConfig, Schema +from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) from orcapod.utils.schema_utils import ( _normalize_column_list, compute_schema_hash, @@ -64,12 +60,11 @@ ) if TYPE_CHECKING: + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from polars._typing import FrameInitTypes - from orcapod.core.sources.polars_input import PolarsInputSchema from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types import Schema T = TypeVar("T") @@ -341,9 +336,6 @@ def __init__( self._declared_arrow: pa.Schema | None = None unified_schema = self._impl.schema() if isinstance(unified_schema, pa.Schema): - require_schema_without_narrow_float_keys( - unified_schema, converter=self.data_context.type_converter - ) require_supported_nullable_types(unified_schema) # Logical types in one form first: a field declared with its identifier # in ARROW:extension:* metadata is that logical type (ITL-640). @@ -379,6 +371,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_python_schema_without_narrow_float_keys( + unified_schema, self.data_context.type_converter + ) self._declared_arrow = declared_arrow_schema( unified_schema, self.data_context.type_converter ) @@ -914,20 +909,16 @@ def _try_build_stream(self, data: FrameInitTypes) -> ArrowTableStream | None: Returns: ``ArrowTableStream`` if data has rows and columns, ``None`` otherwise. """ - df, input_schema = dataframe_with_input_schema( - data, self.data_context.type_converter - ) + df = pl.DataFrame(data) if len(df.columns) == 0: logger.debug( "PollingSource %r: fetch returned data with no columns — skipping stream build", self.source_id, ) return None - return self._build_stream_from_df(df, input_schema) + return self._build_stream_from_df(df) - def _build_stream_from_df( - self, df: pl.DataFrame, input_schema: PolarsInputSchema - ) -> ArrowTableStream | None: + def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: """Build an ``ArrowTableStream`` from a Polars DataFrame. Returns ``None`` on the infer-once path when the batch has zero rows and @@ -944,9 +935,6 @@ def _build_stream_from_df( df = df.with_columns([pl.from_arrow(c) for c in sub_table]) raw = df.to_arrow() - require_polars_input_types( - raw.schema, input_schema, self.data_context.type_converter - ) require_supported_nullable_types(raw.schema) arrow_table = arrow_utils.drop_system_columns(raw) @@ -993,7 +981,6 @@ def _build_stream_from_df( builder = SourceStreamBuilder(self.data_context) result = builder.build( arrow_table, - input_types_checked=True, tag_columns=self._tag_columns, source_name=self._source_name, kind_part=self.kind_part(), diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index c4a9d85a4..dcdd309c5 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -78,7 +78,6 @@ require_same_process, ) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError -from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError from orcapod.types import ColumnConfig, Condition from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils @@ -437,10 +436,6 @@ def __init__( ), data_tags=self._data_tags, ) - except NarrowFloatKeyError as exc: - raise NarrowFloatKeyError( - f"{location}, table {table_name!r}: {exc}" - ) from exc except ValueError as exc: raise ValueError(f"{location}, table {table_name!r}: {exc}") from exc self._table_schema: pa.Schema = arrow_utils.drop_system_columns( diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 50beb254d..743de64aa 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -25,9 +25,6 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import InputValidationError, RowIdentifierError from orcapod.logical_types.identifier import LogicalTypeIdentifierError -from orcapod.semantic_types.narrow_float_keys import ( - require_schema_without_narrow_float_keys, -) from orcapod.system_constants import constants from orcapod.types import ContentHash from orcapod.utils import arrow_utils, schema_utils @@ -573,8 +570,6 @@ def build( data_tags: Collection[str] = (), *, hash_in_key_order: bool = False, - inherited_types: bool = False, - input_types_checked: bool = False, ) -> SourceStreamResult: """Run the full enrichment pipeline. @@ -594,10 +589,6 @@ def build( which changes when rows are reordered unless ``hash_in_key_order`` is given; pass an explicit value when the source id must survive reordering. - inherited_types: The table retains already-built upstream types, as - when a derived source copies a tag into data. - input_types_checked: The source handled validation of any declarations - before passing the table to the builder. record_id_columns: The key columns whose values identify a row, in key order: the row identifier is their canonical JSON (``key_row_identifier``), which follows the row regardless of its @@ -671,14 +662,6 @@ def build( raise schema_utils.schema_hash_rejected_columns_error( found, tag_columns_tuple, data_tags_tuple, system_tag_columns_tuple ) - # Nor is a dict keyed by, or a set of, float32 or float16 (ITL-1591): refused - # here first, as the stream refuses it, before any key column or hash. - if not inherited_types and not input_types_checked: - require_schema_without_narrow_float_keys( - table.schema, - source_input=True, - converter=self._data_context.type_converter, - ) # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 87de34fdd..7f9578b3b 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -34,7 +34,6 @@ require_restorable_none, with_context, ) -from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError from orcapod.semantic_types.nested_storage import NestedTypeNotStorableError from orcapod.logical_types.registry import ( make_arrow_extension_type, @@ -331,11 +330,7 @@ def _storage( UserClassLogicalType, ), ) - except ( - NestedNoneNotRestorableError, - NestedTypeNotStorableError, - NarrowFloatKeyError, - ) as exc: + except (NestedNoneNotRestorableError, NestedTypeNotStorableError) as exc: raise with_context( f"{python_type.__qualname__}.{field_name} ({annotation})", exc ) from exc diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index aef61323f..63c332a4e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2043,7 +2043,6 @@ def load( saved_database_kind, saved_source_kind, ) - from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError path = _Path(path) with open(path) as f: @@ -2167,9 +2166,6 @@ def load( spec_name, spec_name, ) - elif isinstance(failure, NarrowFloatKeyError): - failure.add_note(f"{path}: source {spec_name!r}") - raise failure elif isinstance(failure, Warning): # A warning turned into an error (a ProvisionalHashWarning under an # error filter) is the caller's request: it propagates, never read as a diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 4df2a23ab..3ea71f25c 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -11,6 +11,7 @@ from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias, cast +from orcapod.types import Schema from orcapod.logical_types.canonical_form import ( declaration_form_field, declaration_form_schema, @@ -22,11 +23,6 @@ arrow_type_identifier, require_readable, ) -from orcapod.semantic_types.narrow_float_keys import ( - NarrowFloatKeyError, - saved_source_schema_errors, -) -from orcapod.types import Schema if TYPE_CHECKING: import pyarrow as pa @@ -691,22 +687,12 @@ def resolve_source_from_config( ) cls = SOURCE_REGISTRY[source_type] try: - # Let the input schema reach the identity check even if it contains a - # legacy narrow key. This checks live input, independently of saved schemas. - schema_errors: list[NarrowFloatKeyError] = [] - token = saved_source_schema_errors.set(schema_errors) - try: - source = cls.from_config(config, db_registry=db_registry) - finally: - saved_source_schema_errors.reset(token) - if schema_errors: - saved_hash = config.get("pipeline_hash") - if saved_hash is None or source.pipeline_hash().to_string() != saved_hash: - raise schema_errors[0] - return source - except (NarrowFloatKeyError, Warning): - # A changed input schema and a warning turned into an error propagate - # instead of becoming a proxy for a source that could not be rebuilt. + # All sources accept db_registry — always forward it. + # Sources that don't embed database references simply ignore it. + return cls.from_config(config, db_registry=db_registry) + except Warning: + # A warning turned into an error (a ProvisionalHashWarning under an error + # filter) propagates; it is not a source that could not be rebuilt (ITL-1331). raise except Exception: if fallback_to_proxy: @@ -1569,11 +1555,7 @@ def deserialize_arrow_schema( def parse_arrow_type_string(type_str: str, type_converter: Any | None = None) -> Any: - """Restore a saved Arrow type string as a ``pa.DataType``. - - Saved types describe schemas that already existed. Declaration checks belong - at the points where callers introduce a type, so reading the text preserves - legacy types, including narrow float dict keys and set elements. + """Parse an Arrow type string into a ``pa.DataType``. Handles both primitive types (``"int64"``, ``"large_string"``) and nested types (``"list"``, ``"struct"``, diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 79e3ecd82..562767a2a 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -1,432 +1,132 @@ -"""No dict key and no set element is declared ``float32`` or ``float16`` (ITL-1591). - -Developer decisions D16 and D25, November 28, 2026. A Python float stored under a -``float32`` or ``float16`` type is narrowed, and two distinct values can narrow to one -stored value (``1e-50`` and ``2e-50`` both become ``0.0``). For a plain value that is a -loss of precision; for the keys of a dict or the elements of a set it loses an entry, -because the container read back holds one of them. So a declared type whose dict key or -set element is ``float32`` or ``float16`` is refused where it is declared, in a Python -schema or annotation and in an Arrow schema or table alike. The refusal reads types -only, never a value. - -What counts, at the top of a type and inside its declared containers and fields: - -- the key of a dict: an Arrow ``map`` or a bare Arrow list (plain, large or fixed-size) - of structs with exactly ``key`` and ``value`` fields, regardless of intent (D38). - ``nested_storage.dict_entry_fields`` defines the shape; -- the element of a set: the native ``set[T]`` container (a ``ListLogicalType`` of the - set category), as a live extension type or as its storage with the identifier in - ``ARROW:extension:*`` field metadata. - -Custom logical types own their storage, in both live and field-metadata forms. Native -containers declare an element type. An Arrow user-class type declares its fields in -its identity record, while a Python class declares fields in its annotations. Only -declared entry points use this rule (D28). - -A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is -accepted, and so is a ``float64`` key or element. - -The rule applies to Python declarations and explicit Arrow inputs. Inference and -conversion of values under types that already entered bypass declaration validation. -""" +"""Reject narrow float keys and elements in declared Python types (ITL-1591).""" from __future__ import annotations -import json -from collections.abc import Iterator, Mapping +from collections.abc import Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar from types import UnionType from typing import ( TYPE_CHECKING, - Any, + Annotated, Literal, Protocol, Union, - cast, get_args, get_origin, ) +import numpy as np + from orcapod.errors import InputValidationError -from orcapod.semantic_types.nested_storage import dict_entry_fields +from orcapod.semantic_types.nested_none import with_context +from orcapod.types import SchemaLike if TYPE_CHECKING: - import pyarrow as pa - from orcapod.logical_types.protocols import LogicalTypeProtocol - -class _LogicalTypeLookup(Protocol): - """Read existing Python registrations without creating new ones.""" - - def get_logical_type(self, python_type: type) -> LogicalTypeProtocol | None: ... - - NARROW_FLOAT_KEYS_NOT_SUPPORTED = ( "float32 and float16 are not supported as a dict key type or a set element type" ) -"""The start of every refusal of this rule.""" - _REMEDY = ( - "A float stored under such a type is narrowed, so two distinct keys or elements can " - "become one stored value and an entry is lost. Declare the key or element as float64 " - "(float in Python, pa.float64() in Arrow), or use another type (an integer or a " - "string)." + "Two distinct values can narrow to the same stored value and lose an entry. " + "Declare the key or element as float, an integer, or a string." +) +_materializing_inferred_schema = ContextVar( + "materializing_inferred_schema", default=False ) - -_EXTENSION_NAME_KEY = b"ARROW:extension:name" -_EXTENSION_METADATA_KEY = b"ARROW:extension:metadata" class NarrowFloatKeyError(InputValidationError, ValueError): - """A declared type has a ``float32`` or ``float16`` dict key or set element.""" + """A Python declaration has a float32 or float16 dict key or set element.""" -# The saved-source resolver owns this scope, including a separate scope for each -# nested source. Explicit schema declarations never opt into deferral. -saved_source_schema_errors: ContextVar[list[NarrowFloatKeyError] | None] = ContextVar( - "saved_source_schema_errors", default=None -) - +class _LogicalTypeLookup(Protocol): + """Read Python registrations without creating new ones.""" -_converting_existing_types: ContextVar[bool] = ContextVar( - "converting_existing_types", default=False -) + def get_logical_type(self, python_type: type) -> LogicalTypeProtocol | None: ... @contextmanager -def converting_existing_types() -> Iterator[None]: - """Convert inferred or already-validated types without treating them as declarations.""" - token = _converting_existing_types.set(True) +def materializing_inferred_schema() -> Iterator[None]: + """Keep internal row conversion from treating inferred types as declarations.""" + token = _materializing_inferred_schema.set(True) try: yield finally: - _converting_existing_types.reset(token) - - -def checking_python_declarations() -> bool: - """Return whether Python type conversion is checking a new declaration.""" - return not _converting_existing_types.get() + _materializing_inferred_schema.reset(token) -def _python_float_key(annotation: object, *, is_set: bool) -> str | None: - """Describe a narrow Python key or element, including optional and literal types.""" - import numpy as np - import pyarrow as pa - +def _float_width(annotation: object) -> str | None: origin = get_origin(annotation) args = get_args(annotation) + if origin is Annotated: + return _float_width(args[0]) if origin in (Union, UnionType): non_none = [arg for arg in args if arg is not type(None)] - if len(non_none) != 1: - return None - return _python_float_key(non_none[0], is_set=is_set) + return _float_width(non_none[0]) if len(non_none) == 1 else None if origin is Literal: value_types = {type(value) for value in args if value is not None} - if len(value_types) != 1: - return None - annotation = next(iter(value_types)) + return _float_width(next(iter(value_types))) if len(value_types) == 1 else None if annotation is np.float16: - arrow_type = pa.float16() - elif annotation is np.float32 or ( + return "float16" + if annotation is np.float32 or ( isinstance(annotation, str) and annotation == "float32" ): - arrow_type = pa.float32() - else: - return None - return f"{'set element' if is_set else 'dict key'} type {arrow_type}" - - -def require_supported_python_float_key(annotation: object, *, is_set: bool) -> None: - """Refuse a narrow key or element as its Python container is declared.""" - if checking_python_declarations() and ( - description := _python_float_key(annotation, is_set=is_set) - ): - raise NarrowFloatKeyError( - f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {description}. {_REMEDY}" - ) - - -def _is_narrow_float(arrow_type: pa.DataType) -> bool: - import pyarrow as pa - - return pa.types.is_float32(arrow_type) or pa.types.is_float16(arrow_type) - - -def _dict_key(arrow_type: pa.DataType) -> str | None: - """Describe a narrow float key in a plain dict's storage type.""" - import pyarrow as pa - - if pa.types.is_map(arrow_type): - key = arrow_type.key_field - elif (entry_fields := dict_entry_fields(arrow_type)) is not None: - # The item struct may be the storage form of a logical type. - if _EXTENSION_NAME_KEY in (arrow_type.field(0).metadata or {}): - return None - key = entry_fields[0] - else: - return None - if _EXTENSION_NAME_KEY not in (key.metadata or {}) and _is_narrow_float(key.type): - return f"dict key type {key.type}" + return "float32" return None -def _python_class_fields( +def _class_fields( cls: type, converter: _LogicalTypeLookup -) -> Iterator[tuple[str, object]]: - """Read the fields of a native user class, leaving custom logical classes opaque.""" - from orcapod.logical_types import user_class_identity as uci +) -> Iterable[tuple[str, object]]: + """Read stored annotations of native user classes. Custom codecs own their types.""" + from orcapod.logical_types import user_class_identity from orcapod.logical_types.user_class_logical_type import UserClassLogicalType - if uci.class_kind(cls) is not None: - registered = converter.get_logical_type(cls) - if registered is None or isinstance(registered, UserClassLogicalType): - hints = uci.type_hints(cls) - for name in uci.stored_field_names(cls): - yield name, hints.get(name, Any) - - -def _token_float_width(token: object) -> str | None: - """Read a narrow float's Arrow type name from its canonical type token.""" - if isinstance(token, dict): - if isinstance(members := token.get("union"), list): - non_none = [member for member in members if member != "None"] - if len(non_none) == 1: - return _token_float_width(non_none[0]) - if isinstance(members := token.get("literal"), list): - # Identity records store literal reprs. NumPy 2 spells out the scalar - # type, while older NumPy reprs cannot distinguish its float widths. - non_none = [member for member in members if member != "None"] - for scalar, arrow_type in (("float32", "float"), ("float16", "halffloat")): - if non_none and all( - isinstance(member, str) - and member.startswith(f"np.{scalar}(") - and member.endswith(")") - for member in non_none - ): - return arrow_type - if token == "numpy.float32": - return "float" - if token == "numpy.float16": - return "halffloat" - return None - - -def _walk_type_token(token: object) -> Iterator[str]: - """Walk the declaration in an identity token without resolving Python types.""" - if not isinstance(token, dict): - return - if isinstance(record := token.get("class"), dict): - yield from _walk_identity_record(record) - elif isinstance(members := token.get("union"), list): - for member in members: - yield from _walk_type_token(member) - elif (origin := token.get("generic")) in ("list", "set", "dict", "tuple"): - args = token.get("args") - if not isinstance(args, list): - return - if ( - origin in ("dict", "set") - and args - and (width := _token_float_width(args[0])) - ): - label = "dict key" if origin == "dict" else "set element" - yield f"{label} type {width}" - for arg in args: - yield from _walk_type_token(arg) - - -def _walk_identity_record(record: dict[str, Any]) -> Iterator[str]: - """Walk the stored field declarations of a user class.""" - class_name, fields = record.get("name"), record.get("fields") - if not isinstance(class_name, str) or not isinstance(fields, list): + if user_class_identity.class_kind(cls) is None: return - for field in fields: - if isinstance(field, list) and len(field) == 2: - name, token = field - for part in _walk_type_token(token): - yield f"{class_name}.{name}: {part}" - - -def _walk_logical(storage: pa.DataType, name: bytes, raw: bytes) -> Iterator[str]: - """Walk the declarations carried by a native Arrow extension identifier.""" - import pyarrow as pa - - from orcapod.logical_types import user_class_identity as uci - from orcapod.logical_types.list_logical_type_factory import ( - LIST_CATEGORY, - SET_CATEGORY, - ) - - if not raw: + registered = converter.get_logical_type(cls) + if registered is not None and not isinstance(registered, UserClassLogicalType): return try: - decoded: object = json.loads(raw) + hints = user_class_identity.type_hints(cls) except ValueError: + # Leave resolution errors to the converter at the point that needs the type. return - if not isinstance(decoded, dict): - return - - metadata = cast("dict[str, object]", decoded) - category = metadata.get("category") - if category in (LIST_CATEGORY, SET_CATEGORY) and ( - name.startswith(f"{category}[".encode()) - and name.endswith(b"]") - and (pa.types.is_list(storage) or pa.types.is_large_list(storage)) - ): - item = cast("pa.Field[pa.DataType]", storage.value_field) - element_name = metadata.get("element_ext_name") - if isinstance(element_name, str): - if name != f"{category}[{element_name}]".encode(): - return - element_raw = metadata.get("element_ext_metadata") - item = item.with_metadata( - { - _EXTENSION_NAME_KEY: element_name.encode(), - _EXTENSION_METADATA_KEY: ( - element_raw.encode() if isinstance(element_raw, str) else b"" - ), - } - ) - if ( - category == SET_CATEGORY - and _EXTENSION_NAME_KEY not in (item.metadata or {}) - and _is_narrow_float(item.type) - ): - yield f"set element type {item.type}" - else: - yield from _walk(item) - return - - identity = metadata.get("identity") - if not isinstance(identity, dict): - return - record = cast("dict[str, Any]", identity) - kind, class_name = record.get("kind"), record.get("name") - if ( - kind not in (uci.KIND_DATACLASS, uci.KIND_PYDANTIC, uci.KIND_STRUCTURAL) - or category != f"orcapod.{kind}" - or not isinstance(class_name, str) - or name != uci.identity_string(record).encode() - ): - return - yield from _walk_identity_record(record) + for name in user_class_identity.stored_field_names(cls): + if name in hints: + yield name, hints[name] -def _walk( - declaration: object, - converter: _LogicalTypeLookup | None = None, - ancestors: tuple[type, ...] = (), - *, - field_metadata: Mapping[bytes, bytes] | None = None, +def _violations( + annotation: object, converter: _LogicalTypeLookup, ancestors: tuple[type, ...] = () ) -> Iterator[str]: - """Walk bare Arrow types, native containers and declared user-class fields.""" - import pyarrow as pa - - metadata = field_metadata or {} - if isinstance(declaration, pa.Field): - metadata = declaration.metadata or {} - declaration = declaration.type - if isinstance(declaration, pa.DataType): - if isinstance(declaration, pa.ExtensionType): - yield from _walk_logical( - declaration.storage_type, - declaration.extension_name.encode(), - declaration.__arrow_ext_serialize__(), - ) - elif isinstance(declaration, pa.BaseExtensionType): - return - elif name := metadata.get(_EXTENSION_NAME_KEY): - yield from _walk_logical( - declaration, name, metadata.get(_EXTENSION_METADATA_KEY, b"") - ) - else: - if part := _dict_key(declaration): - yield part - if pa.types.is_dictionary(declaration): - yield from _walk(declaration.value_type) - else: - for index in range(declaration.num_fields): - yield from _walk(declaration.field(index)) - return - - origin = get_origin(declaration) - args = get_args(declaration) - if origin in (dict, set) and args: - if part := _python_float_key(args[0], is_set=origin is set): - yield part - if origin in (list, set, dict, tuple, Union, UnionType): + origin = get_origin(annotation) + args = get_args(annotation) + if origin in (dict, set) and args and (width := _float_width(args[0])): + part = "set element" if origin is set else "dict key" + yield f"{part} type {width}" + if origin is Annotated: + yield from _violations(args[0], converter, ancestors) + elif origin in (dict, set, list, tuple, Union, UnionType): for arg in args: - yield from _walk(arg, converter, ancestors) - elif ( - converter is not None - and isinstance(declaration, type) - and declaration not in ancestors - ): - for name, annotation in _python_class_fields(declaration, converter): - for part in _walk(annotation, converter, (*ancestors, declaration)): - yield f"{declaration.__qualname__}.{name}: {part}" - + yield from _violations(arg, converter, ancestors) + elif isinstance(annotation, type) and annotation not in ancestors: + for name, field in _class_fields(annotation, converter): + for violation in _violations(field, converter, (*ancestors, annotation)): + yield f"{annotation.__qualname__}.{name}: {violation}" -def require_python_declaration_without_narrow_float_keys( - annotation: object, converter: _LogicalTypeLookup -) -> None: - """Refuse a Python declaration without requiring its Arrow storage to exist.""" - if found := sorted(set(_walk(annotation, converter))): - raise NarrowFloatKeyError( - f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {', '.join(found)}. {_REMEDY}" - ) - - -def narrow_float_keys( - arrow_type: pa.DataType, - field_metadata: Mapping[bytes, bytes] | None = None, - *, - converter: _LogicalTypeLookup | None = None, -) -> list[str]: - """Return the refused keys and elements of a declared Arrow type.""" - return sorted(set(_walk(arrow_type, converter, field_metadata=field_metadata))) - -def require_schema_without_narrow_float_keys( - arrow_schema: pa.Schema, - *, - source_input: bool = False, - converter: _LogicalTypeLookup | None = None, +def require_python_schema_without_narrow_float_keys( + schema: SchemaLike, converter: _LogicalTypeLookup ) -> None: - """Refuse an Arrow schema with a ``float32`` or ``float16`` dict key or set element. - - Applied at declared entry points (D28), including source Arrow inputs and - explicitly declared mutations. A bare list of structs with exactly ``key`` - and ``value`` fields is a dict at these boundaries (D38). For example, Batch - can build that shape from a struct column and carry it through the pipeline. - Supplying the same shape as a source's Arrow input triggers the check. Operator - results, caches and saved schemas bypass declaration validation. No value is read. - - Args: - arrow_schema: The Arrow schema of the table. - converter: The data context of the caller. Arrow validation reads the - declarations carried by the schema itself. - source_input: The schema came from the source's input data. During saved - source reconstruction its diagnostic can wait for the identity check. - - Raises: - NarrowFloatKeyError: If a column's type is, or contains at any depth, a dict - keyed by, or a set of, ``float32`` or ``float16``. The message names each - such column, in name order, with its type and each such part, and the - remedy. - """ - lines = [ - f" - column {field.name!r} has type {field.type} ({', '.join(found)})" - for field in sorted(arrow_schema, key=lambda field: field.name) - if (found := sorted(set(_walk(field, converter)))) - ] - if lines: - error = NarrowFloatKeyError( - f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}:\n" + "\n".join(lines) + f"\n{_REMEDY}" - ) - if source_input and (errors := saved_source_schema_errors.get()) is not None: - errors.append(error) - else: - raise error + """Check declared Python columns without converting values or Arrow types.""" + if _materializing_inferred_schema.get(): + return + for name, annotation in schema.items(): + if found := sorted(set(_violations(annotation, converter))): + error = NarrowFloatKeyError( + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {', '.join(found)}. {_REMEDY}" + ) + raise with_context(f"Column {name!r} ({annotation})", error) diff --git a/src/orcapod/semantic_types/nested_storage.py b/src/orcapod/semantic_types/nested_storage.py index 43e73cde9..37ee98ba6 100644 --- a/src/orcapod/semantic_types/nested_storage.py +++ b/src/orcapod/semantic_types/nested_storage.py @@ -12,7 +12,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING if TYPE_CHECKING: import pyarrow as pa @@ -45,39 +45,3 @@ def require_storable_in_struct_field(arrow_type: pa.DataType) -> None: f"or declare the plain type (e.g. dict[str, list[int]] for " f"dict[str, set[int]]). Follow-up: {_FOLLOW_UP}." ) - - -def dict_entry_fields( - arrow_type: pa.DataType, -) -> tuple[pa.Field[Any], pa.Field[Any]] | None: - """Return the key and value fields of ``arrow_type`` when it stores a dict. - - The one definition of the dict shape: a ``dict[K, V]`` is stored as a list (large, - plain or fixed-size) of structs with exactly the two fields ``key`` and ``value``. - The converter reads such a type as a dict (``arrow_type_to_python_type``, - ``get_arrow_to_python_converter``), and the refusal of a narrow float key in a - declared type (``narrow_float_keys``, ITL-1591) asks here too. An Arrow ``map`` is - read as a dict as well and is not this shape: its key and item types are the - type's own. - - Args: - arrow_type: Any Arrow type. - - Returns: - ``(key field, value field)``, or ``None`` when ``arrow_type`` is not a list of - ``{key, value}`` structs. - """ - import pyarrow as pa - - if not ( - pa.types.is_list(arrow_type) - or pa.types.is_large_list(arrow_type) - or pa.types.is_fixed_size_list(arrow_type) - ): - return None - element_type = arrow_type.value_type - if not pa.types.is_struct(element_type) or element_type.num_fields != 2: - return None - if {field.name for field in element_type} != {"key", "value"}: - return None - return element_type.field("key"), element_type.field("value") diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 6ff76b570..9bf0a0465 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -17,7 +17,6 @@ import types import typing from collections.abc import Callable, Iterable, Mapping -from contextlib import nullcontext from datetime import date, datetime, timezone # Handle generic types @@ -46,22 +45,15 @@ with_context, ) from orcapod.semantic_types.narrow_float_keys import ( - NarrowFloatKeyError, - checking_python_declarations, - converting_existing_types, - require_python_declaration_without_narrow_float_keys, - require_schema_without_narrow_float_keys, - require_supported_python_float_key, + require_python_schema_without_narrow_float_keys, ) from orcapod.semantic_types.nested_storage import ( - dict_entry_fields, NestedTypeNotStorableError, require_storable_in_struct_field, ) from orcapod.semantic_types.type_inference import infer_python_schema_from_pylist_data from orcapod.types import DataType, Schema, SchemaLike from orcapod.utils import arrow_utils -from orcapod.utils.schema_utils import require_python_schema_without_narrow_float_keys if TYPE_CHECKING: from orcapod.logical_types.registry import LogicalTypeRegistry @@ -310,7 +302,7 @@ def get_native_python_types(cls) -> frozenset[type]: ) | {type(None)} return _ARROW_NATIVE_TYPE_KEYS - def ensure_types_registered_for_schemas(self, *schemas: SchemaLike) -> None: + 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 @@ -349,7 +341,6 @@ def ensure_types_registered_for_schemas(self, *schemas: SchemaLike) -> None: except ( NestedNoneNotRestorableError, NestedTypeNotStorableError, - NarrowFloatKeyError, ) as exc: raise with_context(f"Column {name!r} ({annotation})", exc) from exc @@ -495,7 +486,6 @@ def _register_python_class_impl( "Unparameterized 'set' is not supported. Use 'set[T]' with a concrete " "element type (e.g. set[int], set[str])." ) - require_supported_python_float_key(args[0], is_set=True) 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( @@ -521,7 +511,6 @@ 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])." ) - require_supported_python_float_key(args[0], is_set=False) key_arrow = self.register_python_class(args[0]) val_arrow = self.register_python_class(args[1]) require_storable_in_struct_field(key_arrow) @@ -543,10 +532,6 @@ def _register_python_class_impl( # Registry hit (already synthesised) lt = self._logical_type_registry.get_by_python_type(annotation) if lt is not None: - if checking_python_declarations(): - require_python_declaration_without_narrow_float_keys( - annotation, self - ) return lt.get_arrow_extension_type() # Cycle detection (via the shared ContextVar-backed in_progress set) @@ -971,10 +956,9 @@ def register_logical_type_from_arrow_metadata( ) # Reconstruct and register - with converting_existing_types(): - logical_type = factory.reconstruct_from_arrow( - arrow_extension_name, storage_type, metadata_dict, converter=self - ) + logical_type = factory.reconstruct_from_arrow( + arrow_extension_name, storage_type, metadata_dict, converter=self + ) require_readable(logical_type, extension_metadata) self._logical_type_registry.register_logical_type(logical_type) return logical_type.get_arrow_extension_type() @@ -1012,8 +996,7 @@ def storage_to_python(self, storage_value: Any, annotation: Any) -> Any: decodes nested positions (list elements, class fields); a column's own null never reaches it. """ - with converting_existing_types(): - arrow_type = self.python_type_to_arrow_type(annotation) + arrow_type = self.python_type_to_arrow_type(annotation) if storage_value is None and not none_is_restorable( arrow_type, self._is_user_class_extension ): @@ -1086,8 +1069,7 @@ def python_type_to_arrow_type(self, python_type: DataType) -> pa.DataType: # Convert and cache result arrow_type = self._convert_python_to_arrow(python_type) - if checking_python_declarations(): - self._python_to_arrow_types[python_type] = arrow_type + self._python_to_arrow_types[python_type] = arrow_type return arrow_type @@ -1103,11 +1085,7 @@ def python_schema_to_arrow_schema(self, python_schema: SchemaLike) -> pa.Schema: for field_name, python_type in python_schema.items(): try: arrow_type = self.python_type_to_arrow_type(python_type) - except ( - NestedNoneNotRestorableError, - NestedTypeNotStorableError, - NarrowFloatKeyError, - ) as exc: + except (NestedNoneNotRestorableError, NestedTypeNotStorableError) as exc: raise with_context( f"Column {field_name!r} ({python_type})", exc ) from exc @@ -1388,36 +1366,33 @@ def python_dicts_to_arrow_table( * ``python_schema`` omitted — the Python schema is derived from ``arrow_schema`` for value-conversion purposes; no type registration is performed. - * ``python_schema`` supplied — it controls value conversion, and - the Arrow schema controls the table layout. The converter logs - a warning about possible incompatibility. + * ``python_schema`` supplied — both schemas are used as-is and a + warning is logged if they are incompatible; no type + registration is performed in either case. Returns: A PyArrow ``Table`` containing the converted data. - - Raises: - NarrowFloatKeyError: If either declaration uses a narrow float as - a dict key or set element. """ - if arrow_schema is not None: - require_schema_without_narrow_float_keys(arrow_schema, converter=self) - if python_schema is not None: - require_python_schema_without_narrow_float_keys(python_schema, self) - logger.warning( - "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." - ) - if arrow_schema is None: - scope = ( - nullcontext() - if python_schema is not None - else converting_existing_types() + if python_schema is not None: + require_python_schema_without_narrow_float_keys(python_schema, self) + if python_schema is not None and arrow_schema is not None: + logger.warning( + "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." ) - with scope: - if python_schema is None: - python_schema = infer_python_schema_from_pylist_data(python_dicts) - # Auto-register types covered by a semantic-type factory. - self.ensure_types_registered_for_schemas(python_schema) - arrow_schema = self.python_schema_to_arrow_schema(python_schema) + if python_schema is None and arrow_schema is None: + # Infer schema from data if not provided + python_schema = infer_python_schema_from_pylist_data(python_dicts) + + if arrow_schema is None: + # Convert to Arrow schema — auto-register any types that have a registered + # 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 + # a no-op for primitives and already-registered types. + assert python_schema is not None, "Python schema should not be None here" + self.ensure_types_registered_for_schemas(python_schema) + arrow_schema = self.python_schema_to_arrow_schema(python_schema) if python_schema is None: assert arrow_schema is not None, ( @@ -1425,10 +1400,9 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) - with converting_existing_types(): - struct_dicts = self.python_dicts_to_struct_dicts( - python_dicts, python_schema=python_schema - ) + struct_dicts = self.python_dicts_to_struct_dicts( + python_dicts, python_schema=python_schema + ) # TODO: add more helpful message here return pa.Table.from_pylist(struct_dicts, schema=arrow_schema) @@ -1526,10 +1500,6 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: if self._logical_type_registry is not None: lt = self._logical_type_registry.get_by_python_type(python_type) if lt is not None: - if checking_python_declarations(): - require_python_declaration_without_narrow_float_keys( - python_type, self - ) return lt.get_arrow_extension_type() # Handle typeddict look up @@ -1593,7 +1563,6 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: raise ValueError( f"dict type must have exactly two type arguments, got: {args}" ) - require_supported_python_float_key(args[0], is_set=False) key_type = self.python_type_to_arrow_type(args[0]) value_type = self.python_type_to_arrow_type(args[1]) require_storable_in_struct_field(key_type) @@ -1640,7 +1609,6 @@ def _convert_python_to_arrow(self, python_type: DataType) -> pa.DataType: raise ValueError( f"set type must have exactly one type argument, got: {args}" ) - require_supported_python_float_key(args[0], is_set=True) element_type = self.python_type_to_arrow_type(args[0]) require_restorable_none( args[0], element_type, self._is_user_class_extension @@ -1739,12 +1707,17 @@ def _convert_arrow_to_python(self, arrow_type: pa.DataType) -> type | Any: element_type = arrow_type.value_type # Check if this is a dict representation: list> - if (entry_fields := dict_entry_fields(arrow_type)) is not None: - key_field, value_field = entry_fields - key_python_type = self.arrow_type_to_python_type(key_field.type) - value_python_type = self.arrow_type_to_python_type(value_field.type) + if pa.types.is_struct(element_type): + field_names = [field.name for field in element_type] + if set(field_names) == {"key", "value"}: + # This is a dict + key_field = next(f for f in element_type if f.name == "key") + value_field = next(f for f in element_type if f.name == "value") + + key_python_type = self.arrow_type_to_python_type(key_field.type) + value_python_type = self.arrow_type_to_python_type(value_field.type) - return dict[key_python_type, value_python_type] + return dict[key_python_type, value_python_type] # Regular list element_python_type = self.arrow_type_to_python_type(element_type) @@ -1905,8 +1878,7 @@ def convert_logical(value: Any) -> Any: # Get the Arrow type for this Python type # TODO: check if this step is necessary - with converting_existing_types(): - _ = self.python_type_to_arrow_type(python_type) + _ = self.python_type_to_arrow_type(python_type) # Create conversion function based on type @@ -2062,25 +2034,30 @@ def _create_arrow_to_python_converter( element_type = arrow_type.value_type # Check if this is a dict representation - if (entry_fields := dict_entry_fields(arrow_type)) is not None: - key_field, value_field = entry_fields - key_converter = self.get_arrow_to_python_converter(key_field.type) - value_converter = self._nested_value_converter(value_field.type) - - def convert_entries(value: Any) -> dict[Any, Any]: - if not value: - return {} - converted = {} - for item in value: - # A null entry is not a key/value pair: never drop it. - if item is None: - raise unrestorable_none_error(element_type) - converted[key_converter(item["key"])] = value_converter( - item["value"] - ) - return converted + if pa.types.is_struct(element_type): + field_names = [field.name for field in element_type] + if set(field_names) == {"key", "value"}: + # Dict representation + key_field = next(f for f in element_type if f.name == "key") + value_field = next(f for f in element_type if f.name == "value") + + key_converter = self.get_arrow_to_python_converter(key_field.type) + value_converter = self._nested_value_converter(value_field.type) + + def convert_entries(value: Any) -> dict[Any, Any]: + if not value: + return {} + converted = {} + for item in value: + # A null entry is not a key/value pair: never drop it. + if item is None: + raise unrestorable_none_error(element_type) + converted[key_converter(item["key"])] = value_converter( + item["value"] + ) + return converted - return convert_entries + return convert_entries # Regular list element_converter = self._nested_value_converter(element_type) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 8a35212f3..d9d70fba5 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -10,11 +10,6 @@ import pyarrow as pa from orcapod.errors import InputValidationError -from orcapod.semantic_types.narrow_float_keys import ( - NarrowFloatKeyError, - require_python_declaration_without_narrow_float_keys, -) -from orcapod.semantic_types.nested_none import with_context from orcapod.types import ContentHash, Schema, SchemaLike from orcapod.utils.output_containers import EXCLUDED_OUTPUT_CONTAINERS @@ -628,8 +623,6 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register """ try: return converter.python_schema_to_arrow_schema(schema) - except NarrowFloatKeyError: - raise except (TypeError, ValueError): pass optional = getattr(schema, "optional_fields", frozenset()) @@ -640,8 +633,6 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register ) try: converted = converter.python_schema_to_arrow_schema(single) - except NarrowFloatKeyError: - raise except (TypeError, ValueError): converter.ensure_types_registered_for_schemas(single) converted = converter.python_schema_to_arrow_schema(single) @@ -649,29 +640,6 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register return pa.schema(fields) -def require_python_schema_without_narrow_float_keys( - schema: SchemaLike, converter: Any -) -> None: - """Check a Python declaration when its Arrow conversion is deferred or optional. - - Use the converter's narrow key and element check. Other conversion errors - belong to the path that requires the converter to produce an Arrow type. - """ - for name, python_type in schema.items(): - try: - require_python_declaration_without_narrow_float_keys(python_type, converter) - except NarrowFloatKeyError as exc: - raise with_context(f"Column {name!r} ({python_type})", exc) from exc - except (NameError, TypeError, ValueError): - pass - try: - declared_arrow_schema({name: python_type}, converter) - except NarrowFloatKeyError: - raise - except Exception: # noqa: BLE001 - conversion is optional here - continue - - def compute_schema_hash( tag_schema: "pa.Schema", data_schema: "pa.Schema", diff --git a/tests/test_semantic_types/narrow_float_arrow_main.json b/tests/test_semantic_types/narrow_float_arrow_main.json new file mode 100644 index 000000000..c5357ff76 --- /dev/null +++ b/tests/test_semantic_types/narrow_float_arrow_main.json @@ -0,0 +1,87 @@ +{ + "list-float16": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:d1d2887930ba19ea2d903af3bfb2c1a78d3753d96ebfaaa16046f6be8c248d83", "content_hash": "semantic_v1:eaa0a6c9bcc1afcc4795c1c8993aa74381ec7ac57de7eb66e47627426bbcd17d", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002b92d311db2753b3576be437944a1f560a0b7dddd3bada966e9447cf38b634fc7"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:d1d2887930ba19ea2d903af3bfb2c1a78d3753d96ebfaaa16046f6be8c248d83", "content_hash": "semantic_v1:6884e1228145a196cf4129bd25e9e81d27b72a6ce31d8cc4b6fcc640428e390e", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002b92d311db2753b3576be437944a1f560a0b7dddd3bada966e9447cf38b634fc7"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:5e582de984411388038178390762a09f6e378814ea2d0978c4f0951026c9bf4c", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000228bd997bf015ac7d1b2f8dc3fec5b80b953db7f95bea605c561d8a7aa9f6c39a"} + }, + "list-float32": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:c3fdc73315e188c657a9ea0fc599b753aa0fc7931ebdd819c1cb7c9b87a2366a", "content_hash": "semantic_v1:20ac8db0c18b677cbe10a168a8124c634324f7d27149f637a3ab20a16ab0b179", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002634af7c35a6af3bd2f3df2a27a94c9d4aaba5e72aedb4d800bb3e21529989eda"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:c3fdc73315e188c657a9ea0fc599b753aa0fc7931ebdd819c1cb7c9b87a2366a", "content_hash": "semantic_v1:1534803708953f851fddf96e765b9e954c807b4f772d0db3f77beda88ca4b221", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002634af7c35a6af3bd2f3df2a27a94c9d4aaba5e72aedb4d800bb3e21529989eda"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:a4086da737a44f894bc17db599031385201811e41512e924332483db080e9376", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002434eec37311844f0ebb23c04ecf059d90892b5ab7b418fa813d3a29817fb75d9"} + }, + "large-float16": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:d1d2887930ba19ea2d903af3bfb2c1a78d3753d96ebfaaa16046f6be8c248d83", "content_hash": "semantic_v1:eaa0a6c9bcc1afcc4795c1c8993aa74381ec7ac57de7eb66e47627426bbcd17d", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002b92d311db2753b3576be437944a1f560a0b7dddd3bada966e9447cf38b634fc7"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:d1d2887930ba19ea2d903af3bfb2c1a78d3753d96ebfaaa16046f6be8c248d83", "content_hash": "semantic_v1:6884e1228145a196cf4129bd25e9e81d27b72a6ce31d8cc4b6fcc640428e390e", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002b92d311db2753b3576be437944a1f560a0b7dddd3bada966e9447cf38b634fc7"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:5e582de984411388038178390762a09f6e378814ea2d0978c4f0951026c9bf4c", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000228bd997bf015ac7d1b2f8dc3fec5b80b953db7f95bea605c561d8a7aa9f6c39a"} + }, + "large-float32": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:c3fdc73315e188c657a9ea0fc599b753aa0fc7931ebdd819c1cb7c9b87a2366a", "content_hash": "semantic_v1:20ac8db0c18b677cbe10a168a8124c634324f7d27149f637a3ab20a16ab0b179", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002634af7c35a6af3bd2f3df2a27a94c9d4aaba5e72aedb4d800bb3e21529989eda"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:c3fdc73315e188c657a9ea0fc599b753aa0fc7931ebdd819c1cb7c9b87a2366a", "content_hash": "semantic_v1:1534803708953f851fddf96e765b9e954c807b4f772d0db3f77beda88ca4b221", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002634af7c35a6af3bd2f3df2a27a94c9d4aaba5e72aedb4d800bb3e21529989eda"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:a4086da737a44f894bc17db599031385201811e41512e924332483db080e9376", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002434eec37311844f0ebb23c04ecf059d90892b5ab7b418fa813d3a29817fb75d9"} + }, + "fixed-float16": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:f9164011bf02cd052c494c95f65f2207efc25e227b4b8a972c33714f9f7c7d4f", "content_hash": "semantic_v1:399efbb5603ebc88803512c29eb6befb4e2593dd70da7fb0161face185df14ad", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002ddc9622ff4d55ab69dc4746d9c8e0d0e5582c8437cf3144b3b0babcf52222348"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:f9164011bf02cd052c494c95f65f2207efc25e227b4b8a972c33714f9f7c7d4f", "content_hash": "semantic_v1:1cc74f70985115e7c0b41a97c82a02391fcc995f26afac2684e739dd88381974", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002ddc9622ff4d55ab69dc4746d9c8e0d0e5582c8437cf3144b3b0babcf52222348"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:aebb7a8eeee32e3b5fc765ef572bd7baf9e8cba9d261bd31c6ecb0f27c210041", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002733f31ab2be3f90b0e80acbccb4e9a0910c08b4b7a1015c73ca89896674bc460"} + }, + "fixed-float32": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:89313f2f3037e8fa277f99993b65a60909b79c80c7dff6228550507292169a2b", "content_hash": "semantic_v1:d1e62c629a308795ee5e2c619ece45ed7f45338073b4aed5ff36bd73fb472de6", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:00000219e04245f853faf157036d615b5e001af178edd1ecadb4dc7dff2c5e93897fa1"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:89313f2f3037e8fa277f99993b65a60909b79c80c7dff6228550507292169a2b", "content_hash": "semantic_v1:0d7fb8ef5c701c1fb456c5466023d068638d1a860ac5b20cc7f0aec0301c25f0", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:00000219e04245f853faf157036d615b5e001af178edd1ecadb4dc7dff2c5e93897fa1"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:773a057a9f9343cd3dee8004b2b22233190888a500b003a877fb784ab62ea85d", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000027f19a43d87db88454b796f5cf01f3c197ef76a21db2b29b0f9dd4ec4b9561dbd"} + }, + "map-float16": { + "arrow": {"error": "ValueError", "message": "cannot hash column 'k' of type map: the Arrow hasher refused (Hashing data of type map (node 'k') is not supported). Drop or convert before building the source."}, + "frame": {"error": "ArrowNotImplementedError", "message": "Unsupported cast from large_list> to map using function cast_map"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:5e582de984411388038178390762a09f6e378814ea2d0978c4f0951026c9bf4c", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000228bd997bf015ac7d1b2f8dc3fec5b80b953db7f95bea605c561d8a7aa9f6c39a"} + }, + "map-float32": { + "arrow": {"error": "ValueError", "message": "cannot hash column 'k' of type map: the Arrow hasher refused (Hashing data of type map (node 'k') is not supported). Drop or convert before building the source."}, + "frame": {"error": "ArrowNotImplementedError", "message": "Unsupported cast from large_list> to map using function cast_map"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:a4086da737a44f894bc17db599031385201811e41512e924332483db080e9376", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002434eec37311844f0ebb23c04ecf059d90892b5ab7b418fa813d3a29817fb75d9"} + }, + "declared-map-float16": { + "arrow": {"error": "ValueError", "message": "cannot hash column 'k' of type map: the Arrow hasher refused (Hashing data of type map (node 'k') is not supported). Drop or convert before building the source."}, + "frame": {"error": "ArrowNotImplementedError", "message": "Unsupported cast from large_list> to map using function cast_map"}, + "polling": {"error": "SchemaInconsistencyError", "message": "PollingSource 'polling_source_v1:polling': the fetched column 'k' has the Arrow type large_list>, but the source declares map (its identity was fixed by the declared schema; a Python type means one Arrow type, so declare impl.schema() with a pa.Schema of the fetched types, or fetch the declared types)."} + }, + "declared-map-float32": { + "arrow": {"error": "ValueError", "message": "cannot hash column 'k' of type map: the Arrow hasher refused (Hashing data of type map (node 'k') is not supported). Drop or convert before building the source."}, + "frame": {"error": "ArrowNotImplementedError", "message": "Unsupported cast from large_list> to map using function cast_map"}, + "polling": {"error": "SchemaInconsistencyError", "message": "PollingSource 'polling_source_v1:polling': the fetched column 'k' has the Arrow type large_list>, but the source declares map (its identity was fixed by the declared schema; a Python type means one Arrow type, so declare impl.schema() with a pa.Schema of the fetched types, or fetch the declared types)."} + }, + "declared-list-float16": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:d1d2887930ba19ea2d903af3bfb2c1a78d3753d96ebfaaa16046f6be8c248d83", "content_hash": "semantic_v1:eaa0a6c9bcc1afcc4795c1c8993aa74381ec7ac57de7eb66e47627426bbcd17d", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002b92d311db2753b3576be437944a1f560a0b7dddd3bada966e9447cf38b634fc7"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:d1d2887930ba19ea2d903af3bfb2c1a78d3753d96ebfaaa16046f6be8c248d83", "content_hash": "semantic_v1:6884e1228145a196cf4129bd25e9e81d27b72a6ce31d8cc4b6fcc640428e390e", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002b92d311db2753b3576be437944a1f560a0b7dddd3bada966e9447cf38b634fc7"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:0f514abba5f8b18640c0d3519293b6e013f87277dd33c598c055ff587f14fd98", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002fe5873c4ac2265a2d89a084e274f26eca6f3551934469486499506c934ffef5a"} + }, + "declared-list-float32": { + "arrow": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:c3fdc73315e188c657a9ea0fc599b753aa0fc7931ebdd819c1cb7c9b87a2366a", "content_hash": "semantic_v1:20ac8db0c18b677cbe10a168a8124c634324f7d27149f637a3ab20a16ab0b179", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002634af7c35a6af3bd2f3df2a27a94c9d4aaba5e72aedb4d800bb3e21529989eda"}, + "frame": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:c3fdc73315e188c657a9ea0fc599b753aa0fc7931ebdd819c1cb7c9b87a2366a", "content_hash": "semantic_v1:1534803708953f851fddf96e765b9e954c807b4f772d0db3f77beda88ca4b221", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002634af7c35a6af3bd2f3df2a27a94c9d4aaba5e72aedb4d800bb3e21529989eda"}, + "polling": {"rows": [{"id": 1, "k": [{"key": 0.5, "value": 4}]}], "data": [[{"key": 0.5, "value": 4}]], "pipeline_hash": "semantic_v1:9c6deb31992f3bb839313935f00cf19659a6c89c0eb1a6541c579178276dfa18", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:0000025e6cdc72cf36195b739feb1c0443f2fed91581c9469d54f1563ea451b3f74701", "data_hash": "arrow_v1:000002fa7b8d5b57de61acf5a57a7b2e3e94e8e45bbf9ab8929d9545427f7fa67bcb1b"} + }, + "custom-live": { + "arrow": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:0fb5fa54469c0ca01d4f4d3d4b512ff16cb288652d91403d97b2de5eda242ca5", "content_hash": "semantic_v1:1921398d6e5da426fe69ab6c6b10ea669a51196826286b17519c7c8266a55c05", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002810f45ed1e1d9f1dc7a67be8e90502f326bcfaa4cb431ed16fc567fff1c0e80c"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:0fb5fa54469c0ca01d4f4d3d4b512ff16cb288652d91403d97b2de5eda242ca5", "content_hash": "semantic_v1:6eed2da9d3db7833be3f894adab42dd316604c310cebdae51cd569315f60d65d", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002810f45ed1e1d9f1dc7a67be8e90502f326bcfaa4cb431ed16fc567fff1c0e80c"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:70286d098b2c338782b4a064783f57b351cfd56ea9b811d0435ad4ab0ec50cab", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000021a3f6a67f5e411d93054f024da8201613ed83f841e520ea8929f1cc7cd61b2fe"} + }, + "custom-metadata": { + "arrow": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:0fb5fa54469c0ca01d4f4d3d4b512ff16cb288652d91403d97b2de5eda242ca5", "content_hash": "semantic_v1:1921398d6e5da426fe69ab6c6b10ea669a51196826286b17519c7c8266a55c05", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002810f45ed1e1d9f1dc7a67be8e90502f326bcfaa4cb431ed16fc567fff1c0e80c"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:0fb5fa54469c0ca01d4f4d3d4b512ff16cb288652d91403d97b2de5eda242ca5", "content_hash": "semantic_v1:6eed2da9d3db7833be3f894adab42dd316604c310cebdae51cd569315f60d65d", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002810f45ed1e1d9f1dc7a67be8e90502f326bcfaa4cb431ed16fc567fff1c0e80c"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:70286d098b2c338782b4a064783f57b351cfd56ea9b811d0435ad4ab0ec50cab", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000021a3f6a67f5e411d93054f024da8201613ed83f841e520ea8929f1cc7cd61b2fe"} + }, + "newer-class": { + "arrow": {"rows": [{"id": 1, "k": {"entries": [{"key": "string", "value": 4}]}}], "data": [{"entries": [{"key": "string", "value": 4}]}], "pipeline_hash": "semantic_v1:1573b477b49b4639e7cea9b1f48260fdb7dc79cf09187f89202137ec7feb6295", "content_hash": "semantic_v1:a9b39a00c029690bf5f38008af2a3ca3a76d81dbec297ab337f37f680342216b", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002b71173ec38d5b5edb6a89b752745bcf4a5d80287525ad4a6381b613563395b4d"}, + "frame": {"rows": [{"id": 1, "k": {"entries": [{"key": "string", "value": 4}]}}], "data": [{"entries": [{"key": "string", "value": 4}]}], "pipeline_hash": "semantic_v1:1573b477b49b4639e7cea9b1f48260fdb7dc79cf09187f89202137ec7feb6295", "content_hash": "semantic_v1:e8b680597e9f80a4093a0905f430ad32bfec7ddd33184111d8b2172c88546f0a", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002b71173ec38d5b5edb6a89b752745bcf4a5d80287525ad4a6381b613563395b4d"}, + "polling": {"rows": [{"id": 1, "k": {"entries": [{"key": "string", "value": 4}]}}], "data": [{"entries": [{"key": "string", "value": 4}]}], "pipeline_hash": "semantic_v1:848f0fd838702f2370bc207c33b77592d1d2073debedb1473100515155906962", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002588e72763687a67883014950e47a867d3512862146f169cff443062fde807ae5"} + }, + "missing-dict": { + "arrow": {"rows": [{"id": 1, "k": {"nested": {"entries": [{"key": 0.5, "value": 4}]}}}], "data": [{"nested": {"entries": [{"key": 0.5, "value": 4}]}}], "pipeline_hash": "semantic_v1:7421ed72792297f15ba299f1e12b365f9b981d95cddcbe4532a6df20bb26be64", "content_hash": "semantic_v1:3f5581ee7d0cc99cb8916e620935bdd39a1e358f6c110ee7ef8fde0fb2c1f968", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002f9f865b89163b542cd4a96f4bd0adcf5d0fba8eaa3ecf02c987ac6a52112bad6"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"entries": [{"key": 0.5, "value": 4}]}}}], "data": [{"nested": {"entries": [{"key": 0.5, "value": 4}]}}], "pipeline_hash": "semantic_v1:7421ed72792297f15ba299f1e12b365f9b981d95cddcbe4532a6df20bb26be64", "content_hash": "semantic_v1:0d32a8980cd135e6aa90bce5964c7f4c0a47b4c077f4df584c29e6070fba3882", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002f9f865b89163b542cd4a96f4bd0adcf5d0fba8eaa3ecf02c987ac6a52112bad6"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"entries": [{"key": 0.5, "value": 4}]}}}], "data": [{"nested": {"entries": [{"key": 0.5, "value": 4}]}}], "pipeline_hash": "semantic_v1:e82dc08d34f3b42cb92dcb371a37ce045fa783c64788747a285d73797141d1e6", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000225f04d36e5d6737ce6dbf8ea517afc3db155863aac0130adcdb5ad80ce5fc471"} + }, + "missing-set": { + "arrow": {"rows": [{"id": 1, "k": {"nested": {"entries": [0.5]}}}], "data": [{"nested": {"entries": [0.5]}}], "pipeline_hash": "semantic_v1:67473f22f162c198b6008f9531c2e941f41db41802077f974647e1d282aee32e", "content_hash": "semantic_v1:886b60f5962273f09d08c7bd0b4d4c9c631d39901a192394f38e4baccde97a42", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000020e4276ed94690fb8d3fe8fa068d93ed977b011583321d83be4d1d33691cdc3a5"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"entries": [0.5]}}}], "data": [{"nested": {"entries": [0.5]}}], "pipeline_hash": "semantic_v1:67473f22f162c198b6008f9531c2e941f41db41802077f974647e1d282aee32e", "content_hash": "semantic_v1:d13f805c434357166ff68953e644db532f9eb869d7b9cc06f675e8b83cfc8df8", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000020e4276ed94690fb8d3fe8fa068d93ed977b011583321d83be4d1d33691cdc3a5"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"entries": [0.5]}}}], "data": [{"nested": {"entries": [0.5]}}], "pipeline_hash": "semantic_v1:945fdae24c7ea40231bc295c7f943e9670b0298e7bea17e6d5dd9e1a47d2f23e", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002321424041f12466d3de3812700c439534138a9a5b96760b2b6d198514b5bbda1"} + } +} diff --git a/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py new file mode 100644 index 000000000..1eee7c1f6 --- /dev/null +++ b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py @@ -0,0 +1,255 @@ +"""Arrow inputs preserve source behavior captured on main before ITL-1591.""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import dataclass, make_dataclass +from pathlib import Path +from typing import Any, cast, final + +import numpy as np +import pyarrow as pa +import pytest +from typing_extensions import override + +from orcapod import contexts +from orcapod.core.sources import ArrowTableSource, DataFrameSource, PollingSource +from orcapod.errors import SchemaInconsistencyError +from orcapod.logical_types import make_arrow_extension_type, make_polars_extension_type +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.canonical_form import storage_form_schema +from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.types import Cursor, PollingConfig + +SOURCES = ("arrow", "frame", "polling") +CASES = [ + f"{shape}-{width}" + for shape in ("list", "large", "fixed", "map", "declared-map") + for width in ("float16", "float32") +] + [ + "declared-list-float16", + "declared-list-float32", + "custom-live", + "custom-metadata", + "newer-class", + "missing-dict", + "missing-set", +] + + +@dataclass(frozen=True) +class _CustomInteger: + entries: dict[np.float32, int] + + +@dataclass +class _NativeWrapper: + nested: _CustomInteger + + +_INT_STORAGE = pa.struct([("value", pa.int64())]) +_CUSTOM_NAME = "test.itl1591.custom-integer" + + +@final +class _CustomIntegerCodec(BaseLogicalType): + logical_type_name = _CUSTOM_NAME + python_type = _CustomInteger + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + return make_arrow_extension_type(_CUSTOM_NAME, _INT_STORAGE)() + + @override + def get_polars_extension_type(self) -> Any: + return make_polars_extension_type(_CUSTOM_NAME, _INT_STORAGE)() + + @override + def python_to_storage( + self, value: _CustomInteger, converter: TypeConverterProtocol | None + ) -> dict[str, int]: + return {"value": value.entries[np.float32(0.5)]} + + @override + def storage_to_python( + self, storage_value: dict[str, int], converter: TypeConverterProtocol | None + ) -> _CustomInteger: + return _CustomInteger({np.float32(0.5): storage_value["value"]}) + + +def _context() -> contexts.DataContext: + return contexts.create_registry().get_context("v1") + + +def _ipc_storage_round_trip(table: pa.Table) -> pa.Table: + """Use the field-metadata representation carried by IPC without registration.""" + plain = table.cast(storage_form_schema(table.schema)) + buffer = pa.BufferOutputStream() + with pa.ipc.new_file(buffer, plain.schema) as writer: + writer.write_table(plain) + return pa.ipc.open_file(buffer.getvalue()).read_all() + + +def _arrow_input(case: str) -> tuple[pa.Table, contexts.DataContext]: + context = _context() + if case.startswith("custom"): + converter = context.type_converter + converter.register_logical_type(_CustomIntegerCodec()) + # The custom class's Python implementation contains a narrow key. Its + # registered codec presents an integer field in the Arrow declaration. + table = converter.python_dicts_to_arrow_table( + [ + { + "id": 1, + "k": cast( + Any, _NativeWrapper(_CustomInteger({np.float32(0.5): 4})) + ), + } + ], + python_schema={"id": int, "k": _NativeWrapper}, + ) + return ( + _ipc_storage_round_trip(table) if case.endswith("metadata") else table + ), context + + if case == "newer-class" or case.startswith("missing"): + # The writer owns the original class registrations. The reader either + # registers an incompatible class of the same name or has neither class. + writer = _context().type_converter + namespace = {"__module__": "itl1591_arrow_compatibility"} + if case == "newer-class": + original = make_dataclass( + "Entries", [("entries", dict[str, int])], namespace=namespace + ) + item = original(entries={"string": 4}) + replacement = make_dataclass( + "Entries", [("entries", dict[np.float32, int])], namespace=namespace + ) + context.type_converter.register_python_class(replacement) + else: + annotation = ( + set[np.float32] if case.endswith("set") else dict[np.float32, int] + ) + value = {np.float32(0.5)} if case.endswith("set") else {np.float32(0.5): 4} + inner = make_dataclass( + "Inner", [("entries", annotation)], namespace=namespace + ) + outer = make_dataclass("Outer", [("nested", inner)], namespace=namespace) + item = outer(nested=inner(entries=value)) + table = writer.python_dicts_to_arrow_table([{"id": 1, "k": item}]) + return _ipc_storage_round_trip(table), context + + shape, width = case.rsplit("-", 1) + if width == "float16": + key, scalar = pa.float16(), np.float16(0.5) + else: + key, scalar = pa.float32(), np.float32(0.5) + if shape.endswith("map"): + values = pa.array([[(scalar, 4)]], type=pa.map_(key, pa.int64())) + else: + pair = pa.struct([("key", key), ("value", pa.int64())]) + column = { + "list": pa.list_(pair), + "large": pa.large_list(pair), + "fixed": pa.list_(pair, 1), + }[shape.removeprefix("declared-")] + values = pa.array([[{"key": scalar, "value": 4}]], type=column) + return pa.table({"id": [1], "k": values}), context + + +@dataclass +class _PollOnce: + table: pa.Table + declared: pa.Schema | None + + def schema(self) -> pa.Schema | None: + return self.declared + + def identity(self) -> tuple[str]: + return ("itl1591-arrow-compatibility",) + + async def poll(self, cursor: Cursor | None = None) -> bool: + return cursor is None + + async def fetch(self, cursor: Cursor | None = None) -> tuple[Cursor, pa.Table]: + assert cursor is None + return Cursor(value=1), self.table + + async def close(self) -> None: + pass + + +async def _read_async( + source: ArrowTableSource | DataFrameSource | PollingSource[pa.Table], +) -> tuple[Any, Any]: + rows = source.async_iter_data() + try: + return await asyncio.wait_for(anext(rows), timeout=5) + finally: + await rows.aclose() + + +def _source_result(case: str, kind: str, asynchronous: bool) -> dict[str, Any]: + table, context = _arrow_input(case) + declared = table.schema if case.startswith("declared-") else None + source: ArrowTableSource | DataFrameSource | PollingSource[pa.Table] + try: + if kind == "arrow": + source = ArrowTableSource(table, "id", source_id=kind, data_context=context) + elif kind == "frame": + source = DataFrameSource( + table, "id", source_id=kind, data_context=context, schema=declared + ) + else: + source = PollingSource( + _PollOnce(table, declared), + "id", + source_id=kind, + data_context=context, + record_id_columns="id", + polling_config=PollingConfig(interval=0.01, duration=0.5), + ) + if not asynchronous: + source.check_for_new_data() + tag, data = ( + asyncio.run(_read_async(source)) + if asynchronous + else next(source.iter_data()) + ) + return { + "rows": source.as_table().select(["id", "k"]).to_pylist(), + "data": data.as_table()["k"].to_pylist(), + "pipeline_hash": str(source.pipeline_hash()), + "content_hash": str(source.content_hash()), + "tag_hash": str(tag.content_hash()), + "data_hash": str(data.content_hash()), + } + except ( + ValueError, + pa.ArrowNotImplementedError, + SchemaInconsistencyError, + StopAsyncIteration, + ) as exc: + # Main already rejects retained Arrow maps during hashing or schema casts. + # Record the baseline diagnostic as well as the successful reads. + return {"error": type(exc).__name__, "message": str(exc)} + + +@pytest.fixture(scope="module") +def main_results() -> dict[str, Any]: + """Rows, hashes and pre-existing map errors recorded on main at 1fb2a7f7.""" + return json.loads( + Path(__file__).with_name("narrow_float_arrow_main.json").read_text() + ) + + +@pytest.mark.parametrize("case", CASES) +@pytest.mark.parametrize("kind", SOURCES) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_arrow_input_matches_main( + case: str, kind: str, asynchronous: bool, main_results: dict[str, Any] +) -> None: + observed = _source_result(case, kind, asynchronous) + # Convert Arrow map tuples to JSON arrays before comparison. + assert json.loads(json.dumps(observed)) == main_results[case][kind] diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index d09568022..9b18ec74f 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -1,734 +1,25 @@ -"""No dict key and no set element is declared ``float32`` or ``float16`` (ITL-1591). - -Developer decisions D16 and D25, November 28, 2026. A Python float stored under a -``float32`` or ``float16`` type is narrowed, and two distinct values can narrow to one -(``1e-50`` and ``2e-50`` both become ``0.0``): a dict stored two ``0.0`` keys and a set two -``0.0`` elements, so the container read back had lost an entry. A declared type whose -dict key or set element is ``float32`` or ``float16`` is therefore refused where it is -declared, in a Python schema or annotation and in an Arrow schema or table alike, at any -nesting depth, by a check of types that reads no value. The rule is -``semantic_types/narrow_float_keys.py``; the dict shape is the type converter's one -definition (``nested_storage.dict_entry_fields``), and an Arrow ``map`` is a dict too. - -A ``float32`` or ``float16`` plain column, list element, struct field or dict VALUE is -accepted, and so is a ``float64`` key or element. -""" +"""The narrow-float key and element rule applies at Python declaration boundaries.""" from __future__ import annotations import dataclasses -import json -import subprocess -import sys -from collections.abc import Callable -from pathlib import Path -from typing import Any, Literal, cast, final +from typing import Any, cast +from unittest.mock import Mock import numpy as np -import pandas as pd -import polars as pl import pyarrow as pa import pytest -from typing_extensions import override -from orcapod import contexts, dataclass as structural_dataclass, function_pod +from orcapod import contexts, function_pod from orcapod.core.datagrams import Data, Datagram, Tag -from orcapod.core.operators import Index -from orcapod.core.sources import ( - ArrowTableSource, - DataFrameSource, - DeltaTableSource, - DictSource, - ListSource, -) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream -from orcapod.errors import InputValidationError -from orcapod.logical_types.base_logical_type import BaseLogicalType -from orcapod.logical_types.list_logical_type_factory import ListLogicalType -from orcapod.logical_types.protocols import LogicalTypeProtocol, TypeConverterProtocol -from orcapod.logical_types.registry import ( - make_arrow_extension_type, - make_polars_extension_type, -) +from orcapod.core.nodes import SourceJobNode, SourceNode +from orcapod.core.sources import DictSource, ListSource, PollingSource +from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.semantic_types.narrow_float_keys import ( - NARROW_FLOAT_KEYS_NOT_SUPPORTED, + NARROW_FLOAT_KEYS_NOT_SUPPORTED as NOT_SUPPORTED, NarrowFloatKeyError, - converting_existing_types, - narrow_float_keys, - require_schema_without_narrow_float_keys, -) -from orcapod.semantic_types.nested_storage import dict_entry_fields -from orcapod.semantic_types.universal_converter import UniversalTypeConverter - -NOT_SUPPORTED = NARROW_FLOAT_KEYS_NOT_SUPPORTED - - -def _converter() -> Any: - return contexts.resolve_context(None).type_converter - - -def _dict_of(key: pa.DataType, value: pa.DataType = pa.int64()) -> pa.DataType: - """The converter's stored form of ``dict[key, value]``.""" - return pa.large_list(pa.struct([("key", key), ("value", value)])) - - -def _make_logical_type( - name: str, - element_class: type, - storage_type: pa.DataType, - encode: Callable[[Any], Any], - decode: Callable[[Any], Any], -) -> LogicalTypeProtocol: - """Build a custom logical type using the given storage conversions.""" - arrow_extension = cast( - "Callable[[], pa.ExtensionType]", make_arrow_extension_type(name, storage_type) - )() - polars_extension = cast( - "Callable[[], pl.BaseExtension]", make_polars_extension_type(name, storage_type) - )() - - @final - class LogicalElement(BaseLogicalType): - logical_type_name = name - python_type = element_class - - @override - def get_arrow_extension_type(self) -> pa.ExtensionType: - return arrow_extension - - def get_polars_extension_type(self) -> pl.BaseExtension: - return polars_extension - - def python_to_storage( - self, value: Any, converter: TypeConverterProtocol | None - ) -> Any: - return encode(value) - - def storage_to_python( - self, storage_value: Any, converter: TypeConverterProtocol | None - ) -> Any: - return decode(storage_value) - - return LogicalElement() - - -@pytest.mark.parametrize("width", [pa.float32(), pa.float16()], ids=str) -def test_d38_bare_key_value_struct_lists_are_dicts(width: pa.DataType) -> None: - from orcapod.core.operators import Batch - - pair_type = pa.struct([("key", width), ("value", pa.int64())]) - pair = {"key": 0.5, "value": 1} - source = ArrowTableSource( - pa.table({"id": [1], "pairs": pa.array([pair], type=pair_type)}), - tag_columns="id", - tag_only_columns=True, - ) - result = Batch()(source).as_table() - assert result["pairs"].type == pa.large_list(pair_type) - assert result["pairs"].to_pylist() == [[pair]] - - for pairs in ( - pa.array([[pair]], type=pa.list_(pair_type)), - result["pairs"], - pa.array([[pair]], type=pa.list_(pair_type, 1)), - ): - table = pa.Table.from_arrays([pa.array([1]), pairs], names=["id", "pairs"]) - with pytest.raises(NarrowFloatKeyError, match="column 'pairs'.*dict key type"): - ArrowTableSource(table, tag_columns="id", tag_only_columns=True) - - -def test_d38_logical_storage_is_opaque_in_both_arrow_forms() -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - - @dataclasses.dataclass(frozen=True) - class Opaque: - value: object - - pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) - for storage in (pa.large_list(pair_type), pair_type): - logical = _make_logical_type( - f"test.narrow_keys.opaque.{storage.id}", - Opaque, - storage, - lambda value: value.value, - Opaque, - ).get_arrow_extension_type() - schema = pa.schema([("v", logical), ("nested", pa.large_list(logical))]) - require_schema_without_narrow_float_keys(schema) - require_schema_without_narrow_float_keys(storage_form_schema(schema)) - - -@dataclasses.dataclass(frozen=True) -class _StringSet: - values: set[str] - - -@dataclasses.dataclass(frozen=True) -class _StringDict: - values: dict[str, int] - - -def test_d38_custom_set_and_dict_classes_own_float32_storage() -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - - converter = contexts.create_registry().get_context("v1").type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type( - _make_logical_type( - "test.narrow_keys.string_set", - _StringSet, - pa.large_list(pa.float32()), - lambda value: [float(item) for item in value.values], - lambda stored: _StringSet({str(item) for item in stored}), - ) - ) - converter.register_logical_type( - _make_logical_type( - "test.narrow_keys.string_dict", - _StringDict, - _dict_of(pa.float32()), - lambda value: [ - {"key": float(key), "value": item} for key, item in value.values.items() - ], - lambda stored: _StringDict( - {str(row["key"]): row["value"] for row in stored} - ), - ) - ) - rows = [{"items": _StringSet({"0.5"}), "pairs": _StringDict({"0.5": 1})}] - table = converter.python_dicts_to_arrow_table( - rows, python_schema={"items": _StringSet, "pairs": _StringDict} - ) - require_schema_without_narrow_float_keys(table.schema) - require_schema_without_narrow_float_keys(storage_form_schema(table.schema)) - assert converter.arrow_table_to_python_dicts(table) == rows - - -@pytest.mark.parametrize( - ("numpy_type", "arrow_type"), - [(np.float32, pa.float32()), (np.float16, pa.float16())], -) -def test_d38_python_and_map_declarations_are_refused_and_saved_schemas_load( - numpy_type: Any, arrow_type: pa.DataType -) -> None: - from orcapod.pipeline.serialization import ( - arrow_type_texts, - deserialize_arrow_schema, - ) - - for declaration in (list[dict[numpy_type, int]], list[set[numpy_type]]): - with pytest.raises(NarrowFloatKeyError): - Data({"v": []}, python_schema={"v": declaration}) - - schema = pa.schema([("v", pa.list_(pa.map_(arrow_type, pa.int64())))]) - with pytest.raises(NarrowFloatKeyError, match="dict key type"): - require_schema_without_narrow_float_keys(schema) - - saved = pa.schema([("v", _dict_of(arrow_type)), ("s", _live_set(arrow_type))]) - columns = arrow_type_texts(saved) - restored = deserialize_arrow_schema({"columns": columns, "nullable": ["v", "s"]}) - assert arrow_type_texts(restored) == columns - - -@dataclasses.dataclass(frozen=True) -class _Measurement: - magnitude: float - - -def _logical_measurement(name: str, storage_type: pa.DataType) -> LogicalTypeProtocol: - """Represent a measurement by its magnitude in Arrow.""" - return _make_logical_type( - name, _Measurement, storage_type, lambda value: value.magnitude, _Measurement - ) - - -@pytest.mark.parametrize("entry_point", ["convert", "register", "pod"]) -def test_registered_float64_storage_set_declaration(entry_point: str) -> None: - """Python declarations accept registered elements with float64 storage.""" - context = contexts.create_registry().get_context("v1") - converter = context.type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type( - _logical_measurement(f"test.wide_set.measurement.{entry_point}", pa.float64()) - ) - - def declare(annotation: type) -> object: - if entry_point == "convert": - return converter.python_type_to_arrow_type(annotation) - if entry_point == "register": - return converter.register_python_class(annotation) - - def produce(x: int) -> set[_Measurement]: - raise AssertionError("never called") - - produce.__annotations__["return"] = annotation - return function_pod(output_keys="v", data_context=context)(produce) - - assert declare(list[_Measurement]) is not None - assert declare(set[_Measurement]) is not None - - -def test_set_of_logical_sequences_preserves_repeated_coordinates() -> None: - """A logical sequence represented by key/value structs can appear in a set.""" - - @dataclasses.dataclass(frozen=True) - class Frames: - events: tuple[tuple[float, int], ...] - - converter = contexts.create_registry().get_context("v1").type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type( - _make_logical_type( - "test.narrow_set.frames", - Frames, - _dict_of(pa.float32()), - lambda frames: [ - {"key": key, "value": value} for key, value in frames.events - ], - lambda rows: Frames(tuple((row["key"], row["value"]) for row in rows)), - ) - ) - rows = [{"v": {Frames(((0.5, 1), (0.5, 2)))}}] - table = converter.python_dicts_to_arrow_table(rows, {"v": set[Frames]}) - assert converter.arrow_table_to_python_dicts(table) == rows - - -@dataclasses.dataclass(frozen=True) -class _Frames: - events: tuple[tuple[float, int], ...] - - -@dataclasses.dataclass(frozen=True) -class _FrameBox: - frames: _Frames - sequence: list[_Frames] - - -@dataclasses.dataclass(frozen=True) -class _Pair: - key: np.float32 - value: int - - -@structural_dataclass(name="NarrowFloatKeyPair") -class _StructuralPair: - key: np.float32 - value: int - - -@dataclasses.dataclass -class _LegacyDictField: - entries: list[dict[np.float32, int]] - - -@structural_dataclass(name="NarrowFloatLegacySetField") -class _LegacySetField: - entries: list[set[np.float32]] - - -@pytest.mark.parametrize( - ("annotation", "description"), - [ - (list[_LegacyDictField], "dict key type float"), - (list[_LegacySetField], "set element type float"), - ], -) -def test_explicit_arrow_checks_declared_fields_of_user_classes( - annotation: Any, description: str, monkeypatch: pytest.MonkeyPatch -) -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - from orcapod.semantic_types import universal_converter - - converter = contexts.create_registry().get_context("v1").type_converter - assert isinstance(converter, UniversalTypeConverter) - with pytest.raises(NarrowFloatKeyError, match=description): - converter.register_python_class(annotation) - - def allow_legacy_keys(annotation: object, *, is_set: bool) -> None: - pass - - with monkeypatch.context() as legacy: - legacy.setattr( - universal_converter, - "require_supported_python_float_key", - allow_legacy_keys, - ) - arrow_type = converter.register_python_class(annotation) - schema = pa.schema([("legacy", arrow_type)]) - for declaration in (schema, storage_form_schema(schema)): - with pytest.raises(NarrowFloatKeyError, match=description): - require_schema_without_narrow_float_keys(declaration) - - -@pytest.mark.parametrize( - ("value", "is_narrow"), - [ - pytest.param(np.float32(0.5), True, id="float32"), - pytest.param(0.5, False, id="float64"), - ], -) -def test_arrow_user_class_retains_literal_key_width( - value: np.float32 | float, is_narrow: bool -) -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - - if is_narrow and not repr(value).startswith("np.float32("): - pytest.skip("NumPy's legacy repr omits the scalar type from the identity token") - - annotation = Literal[value, None] # pyright: ignore[reportInvalidTypeForm] - cls = dataclasses.make_dataclass( - "LegacyLiteralKey", - [("entries", dict[annotation, int])], - namespace={"__module__": __name__}, - ) - converter = contexts.create_registry().get_context("v1").type_converter - with converting_existing_types(): - table = converter.python_dicts_to_arrow_table( - [{"k": cls({value: 4})}], python_schema={"k": cls} - ) - for schema in (table.schema, storage_form_schema(table.schema)): - if is_narrow: - with pytest.raises(NarrowFloatKeyError, match="dict key type float"): - require_schema_without_narrow_float_keys(schema) - else: - require_schema_without_narrow_float_keys(schema) - - -_FRAMES = _Frames(((0.5, 1), (0.5, 2))) -_PAIR_ROWS = [{"key": 0.5, "value": 1}, {"key": 0.5, "value": 2}] - - -@pytest.fixture(scope="module") -def frames_converter() -> UniversalTypeConverter: - converter = contexts.resolve_context(None).type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type( - _make_logical_type( - "test.source.frames", - _Frames, - _dict_of(pa.float32()), - lambda frames: [ - {"key": key, "value": value} for key, value in frames.events - ], - lambda rows: _Frames(tuple((row["key"], row["value"]) for row in rows)), - ) - ) - return converter - - -@pytest.mark.parametrize( - ("annotation", "value", "storage"), - [ - pytest.param(_Frames, _FRAMES, _PAIR_ROWS, id="opaque-sequence"), - pytest.param(list[_Frames], [_FRAMES], [_PAIR_ROWS], id="list"), - pytest.param(set[_Frames], {_FRAMES}, [_PAIR_ROWS], id="set"), - pytest.param( - list[_FrameBox], - [_FrameBox(_FRAMES, [_FRAMES])], - [{"frames": _PAIR_ROWS, "sequence": [_PAIR_ROWS]}], - id="declared-fields-under-list", - ), - pytest.param( - list[_Pair], - [_Pair(np.float32(0.5), 1), _Pair(np.float32(0.5), 2)], - _PAIR_ROWS, - id="declared-pair-fields", - ), - pytest.param( - list[_StructuralPair], - [_StructuralPair(np.float32(0.5), 1), _StructuralPair(np.float32(0.5), 2)], - _PAIR_ROWS, - id="structural-pair-fields", - ), - ], ) -@pytest.mark.parametrize("route", ["dict", "arrow", "storage", "dataframe", "pod"]) -def test_public_ingestion_preserves_logical_sequences( - frames_converter: UniversalTypeConverter, - annotation: Any, - value: Any, - storage: Any, - route: str, -) -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - - converter = frames_converter - rows = [{"id": 1, "frames": value}] - schema = {"id": int, "frames": annotation} - if route == "pod": - - def produce(x: int) -> Any: - return value - - produce.__annotations__["return"] = annotation - pod = function_pod(output_keys="frames")(produce) - source = pod.pod(ListSource("x", [1])) - elif route == "dict": - source = DictSource( - rows, data_schema=schema, tag_columns="id", tag_only_columns=True - ) - else: - table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) - if route == "storage": - table = table.cast(storage_form_schema(table.schema)) - source_type = ( - DataFrameSource if route in {"dataframe", "storage"} else ArrowTableSource - ) - source = source_type(table, tag_columns="id", tag_only_columns=True) - output = source.as_table() - assert output["frames"].to_pylist() == [storage] - if route not in {"dataframe", "storage"}: - assert converter.arrow_table_to_python_dicts(output)[0]["frames"] == value - - -@pytest.mark.parametrize("storage_type", [pa.float16(), pa.float32()], ids=str) -def test_index_preserves_empty_logical_set_column(storage_type: pa.DataType) -> None: - """An out-of-bounds Index retains the native set type in its empty result.""" - context = contexts.create_registry().get_context("v1") - converter = context.type_converter - assert isinstance(converter, UniversalTypeConverter) - logical = _logical_measurement( - f"test.narrow_set.indexed.{storage_type}", storage_type - ) - converter.register_logical_type(logical) - inner = ListLogicalType(logical, is_set=True) - outer = ListLogicalType(inner) - converter.register_logical_type(outer) - set_type = inner.get_arrow_extension_type() - list_type = outer.get_arrow_extension_type() - assert ( - converter.get_logical_type_by_arrow_extension_name(set_type.extension_name) - is None - ) - values = pa.ExtensionArray.from_storage( - list_type, pa.array([[[0.5, 0.75]]], type=list_type.storage_type) - ) - table = pa.Table.from_arrays( - [pa.array([1]), values], - schema=pa.schema( - [ - pa.field("id", pa.int64(), nullable=False), - pa.field("x", list_type, nullable=False), - ] - ), - ) - stream = ArrowTableStream(table, tag_columns=["id"], data_context=context) - - result = Index("x", 1, fail_on_miss=False).static_process(stream).as_table() - assert result.num_rows == 0 - result_type = result.schema.field("x").type - assert isinstance(result_type, pa.ExtensionType) - assert result_type.extension_name == set_type.extension_name - assert result_type.storage_type == set_type.storage_type - assert result_type.__arrow_ext_serialize__() == set_type.__arrow_ext_serialize__() - - -def test_schema_free_conversion_accepts_inferred_logical_set() -> None: - """Schema inference can round-trip a set of float32-backed logical elements.""" - converter = contexts.create_registry().get_context("v1").type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type( - _logical_measurement("test.narrow_set.inferred", pa.float32()) - ) - rows = [{"v": {_Measurement(0.5)}}] - table = converter.python_dicts_to_arrow_table(rows) - assert converter.arrow_table_to_python_dicts(table) == rows - - -def _set_storage_field(element: pa.DataType) -> pa.Field[Any]: - """A set in its storage form: the storage type, the identifier in field metadata.""" - live = _live_set(element) - return pa.field( - "item", - live.storage_type, - metadata={ - "ARROW:extension:name": live.extension_name, - "ARROW:extension:metadata": live.__arrow_ext_serialize__(), - }, - ) - - -def _live_set(element: pa.DataType) -> Any: - """The native ``set[T]`` container of a plain Arrow element, as the library builds it.""" - from orcapod.logical_types.list_logical_type_factory import ( - ArrowElement, - ListLogicalType, - ) - - return ListLogicalType( - ArrowElement(float, element), is_set=True - ).get_arrow_extension_type() - - -NARROW: list[pa.DataType] = [pa.float32(), pa.float16()] -WIDE_OR_OTHER: list[pa.DataType] = [pa.float64(), pa.int64(), pa.large_string()] - -# Every place a dict key can sit in a column's type: (name, builder of the column type -# from the key type). -DICT_PLACES: list[tuple[str, Callable[[pa.DataType], pa.DataType]]] = [ - ("top_level", _dict_of), - ( - "non_large_list", - lambda k: pa.list_(pa.struct([("key", k), ("value", pa.int64())])), - ), - ( - "value_first", - lambda k: pa.large_list(pa.struct([("value", pa.int64()), ("key", k)])), - ), - ("in_a_list", lambda k: pa.large_list(_dict_of(k))), - ("in_a_fixed_size_list", lambda k: pa.list_(_dict_of(k), 2)), - ("as_a_dict_value", lambda k: _dict_of(pa.large_string(), _dict_of(k))), - ("as_a_dict_key", lambda k: _dict_of(_dict_of(k))), - ("in_a_struct", lambda k: pa.struct([("a", pa.int64()), ("d", _dict_of(k))])), - ( - "deep", - lambda k: pa.large_list( - pa.struct([("s", pa.struct([("d", _dict_of(pa.int64(), _dict_of(k)))]))]) - ), - ), - ("map", lambda k: pa.map_(k, pa.int64())), - ("map_in_a_list", lambda k: pa.large_list(pa.map_(k, pa.int64()))), - ("as_a_map_value", lambda k: pa.map_(pa.large_string(), _dict_of(k))), -] - -# Every place a set element can sit. -SET_PLACES: list[tuple[str, Callable[[pa.DataType], pa.DataType]]] = [ - ("live_set", _live_set), - ("storage_form_in_a_list", lambda e: pa.large_list(_set_storage_field(e))), - ( - "storage_form_in_a_struct", - lambda e: pa.struct( - [pa.field("a", pa.int64()), _set_storage_field(e).with_name("s")] - ), - ), -] - - -def _cases( - places: list[tuple[str, Callable[[pa.DataType], pa.DataType]]], - parts: list[pa.DataType], -) -> list[Any]: - return [ - pytest.param(build, part, id=f"{name}-{part}") - for name, build in places - for part in parts - ] - - -class TestTheRule: - """A check of types, at every depth.""" - - @pytest.mark.parametrize(("build", "key"), _cases(DICT_PLACES, NARROW)) - def test_refuses_a_narrow_float_dict_key_wherever_the_dict_sits( - self, build: Callable[[pa.DataType], pa.DataType], key: pa.DataType - ) -> None: - column_type = build(key) - assert narrow_float_keys(column_type) == [f"dict key type {key}"] - with pytest.raises(NarrowFloatKeyError) as raised: - require_schema_without_narrow_float_keys( - pa.schema([("id", pa.int64()), ("k", column_type)]) - ) - message = str(raised.value) - assert message.startswith(NOT_SUPPORTED) - assert "'k'" in message and "'id'" not in message - assert f"dict key type {key}" in message - assert "float64" in message - - @pytest.mark.parametrize(("build", "element"), _cases(SET_PLACES, NARROW)) - def test_refuses_a_narrow_float_set_element_wherever_the_set_sits( - self, build: Callable[[pa.DataType], pa.DataType], element: pa.DataType - ) -> None: - column_type = build(element) - assert narrow_float_keys(column_type) == [f"set element type {element}"] - with pytest.raises(NarrowFloatKeyError) as raised: - require_schema_without_narrow_float_keys( - pa.schema([("id", pa.int64()), ("s", column_type)]) - ) - message = str(raised.value) - assert message.startswith(NOT_SUPPORTED) - assert "'s'" in message and f"set element type {element}" in message - - @pytest.mark.parametrize("element", NARROW, ids=str) - def test_refuses_a_top_level_set_in_its_storage_form( - self, element: pa.DataType - ) -> None: - field = _set_storage_field(element).with_name("s") - assert narrow_float_keys(field.type) == [] # a plain list without its metadata - with pytest.raises(NarrowFloatKeyError, match="set element type"): - require_schema_without_narrow_float_keys(pa.schema([field])) - - @pytest.mark.parametrize( - ("build", "part"), _cases(DICT_PLACES + SET_PLACES, WIDE_OR_OTHER) - ) - def test_accepts_every_other_key_and_element_type( - self, build: Callable[[pa.DataType], pa.DataType], part: pa.DataType - ) -> None: - column_type = build(part) - assert narrow_float_keys(column_type) == [] - require_schema_without_narrow_float_keys( - pa.schema([("id", pa.int64()), ("k", column_type)]) - ) - - @pytest.mark.parametrize("narrow", NARROW, ids=str) - def test_a_narrow_float_that_is_no_key_and_no_element_is_accepted( - self, narrow: pa.DataType - ) -> None: - """A plain value, a list element, a struct field and a dict VALUE.""" - require_schema_without_narrow_float_keys( - pa.schema( - [ - ("plain", narrow), - ("listed", pa.large_list(narrow)), - ("fixed", pa.list_(narrow, 2)), - ("field", pa.struct([("key", narrow), ("other", pa.int64())])), - ("lone_key", pa.large_list(pa.struct([("key", narrow)]))), - ("dict_value", _dict_of(pa.large_string(), narrow)), - ("map_value", pa.map_(pa.large_string(), narrow)), - ] - ) - ) - - def test_names_every_such_column_whatever_the_column_order(self) -> None: - fields = [ - pa.field("b", _dict_of(pa.float16())), - pa.field("fine", _dict_of(pa.float64())), - pa.field("a", pa.map_(pa.float32(), pa.int64())), - pa.field("c", _live_set(pa.float32())), - pa.field( - "both", _dict_of(pa.float32(), pa.large_list(_dict_of(pa.float16()))) - ), - ] - messages = [] - for ordered in (fields, fields[::-1], fields[2:] + fields[:2]): - with pytest.raises(NarrowFloatKeyError) as raised: - require_schema_without_narrow_float_keys(pa.schema(ordered)) - messages.append(str(raised.value)) - message = messages[0] - assert all(f"'{name}'" in message for name in ("a", "b", "c", "both")) - assert "'fine'" not in message - assert "(dict key type float, dict key type halffloat)" in message - assert "set element type float" in message - assert messages[0] == messages[1] == messages[2] - - def test_the_dict_shape_is_the_type_converters(self) -> None: - """The rule and the converter read one definition of the dict shape.""" - converted = _converter().python_type_to_arrow_type(dict[float, int]) - fields = dict_entry_fields(converted) - assert fields is not None - assert (fields[0].type, fields[1].type) == (pa.float64(), pa.int64()) - assert dict_entry_fields(pa.large_list(pa.float32())) is None - assert ( - dict_entry_fields( - pa.large_list(pa.struct([("key", pa.float32()), ("v", pa.int64())])) - ) - is None - ) - assert dict_entry_fields(pa.map_(pa.float32(), pa.int64())) is None - - def test_the_error_is_an_input_validation_error(self) -> None: - assert issubclass(NarrowFloatKeyError, InputValidationError) - assert issubclass(NarrowFloatKeyError, ValueError) - +from orcapod.types import Schema D = dict[np.float32, int] S = set[np.float32] @@ -743,6 +34,8 @@ def test_the_error_is_an_input_validation_error(self) -> None: ("set_in_a_list", list[S], [{np.float32(0.5)}]), ("dict_as_a_dict_value", dict[str, D], {"a": {np.float32(0.5): 1}}), ("optional_key", dict[np.float32 | None, int], {np.float32(0.5): 1}), + ("half_dict", dict[np.float16, int], {np.float16(0.5): 1}), + ("half_set", set[np.float16], {np.float16(0.5)}), ] PYTHON_CASES = [ pytest.param(python_type, value, id=name) @@ -766,13 +59,22 @@ class HoldsNarrowKey: d: dict[np.float32, int] +@dataclasses.dataclass +class Nested: + inner: HoldsNarrowKey + + class TestPythonDeclarations: """A type declared in Python is refused when it is declared.""" @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) - def test_the_converter_refuses_the_type(self, python_type: Any, value: Any) -> None: + def test_the_converter_refuses_an_explicit_schema( + self, python_type: Any, value: Any + ) -> None: with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - _converter().python_type_to_arrow_type(python_type) + contexts.resolve_context(None).type_converter.python_dicts_to_arrow_table( + [{"k": value}], python_schema={"k": python_type} + ) @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) @pytest.mark.parametrize("kind", [Datagram, Tag, Data]) @@ -805,8 +107,6 @@ def test_a_source_with_a_python_schema_refuses_it( @pytest.mark.parametrize("declared", [tuple[D, D], tuple[int, D]], ids=str) def test_a_tuple_field_is_refused(self, declared: Any) -> None: """A dict in a tuple: where a tuple type is converted (a datagram).""" - with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - _converter().python_type_to_arrow_type(declared) with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): Datagram({"k": ({}, {}), "x": 1}, python_schema={"k": declared, "x": int}) @@ -814,24 +114,35 @@ def test_a_list_source_refuses_it(self) -> None: with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): ListSource("k", [{np.float32(0.5): 1}], data_schema={"k": D}) - def test_a_user_class_field_is_refused(self) -> None: - with pytest.raises(NarrowFloatKeyError) as raised: + def test_a_nested_user_class_field_is_refused(self) -> None: + with pytest.raises( + NarrowFloatKeyError, match=r"Nested\.inner.*HoldsNarrowKey\.d" + ): DictSource( - [{"id": 1, "c": cast(Any, HoldsNarrowKey({}))}], - tag_columns=["id"], - tag_only_columns=True, - data_schema={"id": int, "c": HoldsNarrowKey}, + [{"id": 1, "c": cast(Any, [Nested(HoldsNarrowKey({}))])}], + tag_columns="id", + data_schema={"id": int, "c": list[Nested | None]}, ) - assert "HoldsNarrowKey.d" in str(raised.value) - @pytest.mark.parametrize("declared", [D, S, list[S], dict[str, D]], ids=str) + @pytest.mark.parametrize( + "declared", + [D, S, list[S], dict[str, D], Nested, set[np.float16], dict[np.float16, int]], + ids=str, + ) + @pytest.mark.parametrize("asynchronous", [False, True]) def test_a_function_pod_refuses_a_declared_output_when_defined( - self, declared: Any + self, declared: Any, asynchronous: bool ) -> None: - def produce(x: int, y: int): # noqa: ANN202 - annotated below - raise AssertionError("never called") + if asynchronous: + + async def produce(x: int) -> Any: + raise AssertionError("never called") + else: + + def produce(x: int) -> Any: + raise AssertionError("never called") - produce.__annotations__ = {"x": int, "y": int, "return": declared} + produce.__annotations__ = {"x": int, "return": declared} with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): function_pod(output_keys="o")(produce) @@ -894,1380 +205,75 @@ def keep( assert data.as_dict() == {"v": {"a": 0.5}, "w": {1e-50: 1, 2e-50: 2}} -def _table(column_type: pa.DataType) -> pa.Table: - """One row, two tags, two plain data columns and a column ``k`` of the given type.""" - return pa.table( - { - "id": pa.array([1], pa.int64()), - "g": pa.array(["a"], pa.large_string()), - "x": pa.array([1], pa.int64()), - "y": pa.array([0.5], pa.float32()), - "k": pa.array([None], column_type), - } - ) +@dataclasses.dataclass +class _HalfDictField: + values: list[dict[np.float16, int]] -ARROW_CASES = _cases(DICT_PLACES, NARROW) + _cases(SET_PLACES[:1], NARROW) +@dataclasses.dataclass +class _HalfSetField: + values: set[np.float16] -class TestArrowDeclarations: - """A type declared in Arrow is refused where the declaration enters.""" +@pytest.mark.parametrize( + "instance", + [_HalfDictField([{np.float16(0.5): 1}]), _HalfSetField({np.float16(0.5)})], +) +def test_datagram_refuses_declared_half_float_field(instance: Any) -> None: + with pytest.raises(NarrowFloatKeyError, match=r"Column 'k'.*values"): + Data({"k": instance}, python_schema={"k": type(instance)}) - def test_the_dict_reproduction_no_longer_loses_an_entry(self) -> None: - """``{1e-50: 1, 2e-50: 2}`` was stored with two ``0.0`` keys.""" - with pytest.raises(NarrowFloatKeyError) as raised: - DictSource( - [{"id": 1, "h": 0.1, "k": {1e-50: 1, 2e-50: 2}}], - tag_columns=["id"], - tag_only_columns=True, - data_schema=pa.schema( - [ - ("id", pa.int64()), - ("h", pa.float16()), - ("k", _dict_of(pa.float32())), - ] - ), - ) - message = str(raised.value) - assert message.startswith(NOT_SUPPORTED) - assert "'k'" in message and "'h'" not in message - def test_the_set_reproduction_no_longer_loses_an_element(self) -> None: - """``{1e-50, 2e-50}`` was stored as ``[0.0, 0.0]`` and read back ``{0.0}``.""" - with pytest.raises(NarrowFloatKeyError, match="set element type float"): - DictSource( - [{"id": 1, "k": {1e-50, 2e-50}}], - tag_columns=["id"], - tag_only_columns=True, - data_schema=pa.schema( - [pa.field("id", pa.int64()), pa.field("k", _live_set(pa.float32()))] - ), - ) +@pytest.mark.parametrize( + ("value", "annotation"), + [ + ({np.float32(0.5): 1}, dict[np.float32, int]), + ({np.float32(0.5)}, set[np.float32]), + ], +) +@pytest.mark.parametrize("route", ["data", "converter"]) +def test_undeclared_float32_dict_and_set_are_accepted( + value: Any, annotation: Any, route: str +) -> None: + context = contexts.create_registry().get_context("v1") + converter = context.type_converter + rows = [{"k": value}] + if route == "data": + row = Data(rows[0], data_context=context) + table = row.as_table() + else: + table = converter.python_dicts_to_arrow_table(rows) + assert converter.arrow_table_to_python_dicts(table) == rows + with pytest.raises(NarrowFloatKeyError): + converter.python_dicts_to_arrow_table(rows, python_schema={"k": annotation}) - def test_a_float64_key_and_element_from_an_arrow_schema_keep_every_entry( - self, - ) -> None: - # Register the native set decoder in the context used by source rows. - converter = contexts.resolve_context(None).type_converter - assert isinstance(converter, UniversalTypeConverter) - set_type = converter.register_python_class(set[float]) - source = DictSource( - [{"id": 1, "k": {1e-50: 1, 2e-50: 2}, "s": {1e-50, 2e-50}, "h": 0.5}], - tag_columns=["id"], - tag_only_columns=True, - data_schema=pa.schema( - [ - pa.field("id", pa.int64()), - pa.field("k", _dict_of(pa.float64())), - pa.field("s", set_type), - pa.field("h", pa.float32()), - ] - ), - ) - ((_, data),) = list(source.iter_data()) - assert data.as_dict() == { - "k": {1e-50: 1, 2e-50: 2}, - "s": {1e-50, 2e-50}, - "h": 0.5, - } - - @pytest.mark.parametrize(("build", "part"), ARROW_CASES) - def test_an_arrow_table_source_refuses_it_in_every_role_and_tag_order( - self, build: Callable[[pa.DataType], pa.DataType], part: pa.DataType - ) -> None: - table = _table(build(part)) - for tags, tag_only in ( - (["id", "g"], True), - (["g", "id"], True), - (["id", "g"], False), - (["id", "k"], True), - (["k", "id"], False), - ): - with pytest.raises(NarrowFloatKeyError) as raised: - ArrowTableSource(table, tag_columns=tags, tag_only_columns=tag_only) - assert str(raised.value).startswith(NOT_SUPPORTED) - assert "'k'" in str(raised.value) - - def test_no_value_is_read(self) -> None: - """A table with no rows is refused the same way: the types decide.""" - empty = _table(_dict_of(pa.float32())).slice(0, 0) - with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - ArrowTableSource(empty, tag_columns=["id", "g"]) - - def test_a_data_frame_source_refuses_it(self) -> None: - schema = pa.schema( - [("id", pa.int64()), ("x", pa.int64()), ("k", _dict_of(pa.float32()))] - ) - rows = {"id": [1], "x": [1], "k": [[{"key": 0.5, "value": 1}]]} - with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - DataFrameSource( - rows, tag_columns=["id"], tag_only_columns=True, schema=schema - ) - frame = pl.DataFrame( - rows, - schema={ - "id": pl.Int64, - "x": pl.Int64, - "k": pl.List(pl.Struct({"key": pl.Float32, "value": pl.Int64})), - }, - ) - with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - DataFrameSource(frame, tag_columns=["id"], tag_only_columns=True) - - def test_a_delta_table_source_refuses_it(self, tmp_path: Path) -> None: - from deltalake import write_deltalake - - table = pa.table( - { - "id": pa.array([1], pa.int64()), - "x": pa.array([1], pa.int64()), - "k": pa.array( - [[{"key": 0.5, "value": 1}]], - pa.list_(pa.struct([("key", pa.float32()), ("value", pa.int64())])), - ), - } - ) - path = str(tmp_path / "t") - write_deltalake(path, table) - with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - DeltaTableSource(path, tag_columns=["id"], tag_only_columns=True) - - def test_a_narrow_float_that_is_no_key_passes_through_a_stream(self) -> None: - """A plain float32 column, a list of them and a float32 dict value are kept.""" - table = pa.table( - { - "id": pa.array([1, 2], pa.int64()), - "g": pa.array(["a", "b"], pa.large_string()), - "plain": pa.array([0.5, 1.5], pa.float32()), - "half": pa.array([0.5, 1.5], pa.float16()), - "listed": pa.array([[0.5], [1.5]], pa.large_list(pa.float32())), - "dict_value": pa.array( - [[{"key": "a", "value": 0.5}], []], - _dict_of(pa.large_string(), pa.float32()), - ), - "wide_key": pa.array( - [[{"key": 1e-50, "value": 1}, {"key": 2e-50, "value": 2}], []], - _dict_of(pa.float64()), - ), - } - ) - for tags in (["id", "g"], ["g", "id"]): - source = ArrowTableSource(table, tag_columns=tags, tag_only_columns=True) - out = source.as_table() - for name in ("plain", "half", "listed", "dict_value", "wide_key"): - assert out.column(name).type == table.column(name).type - assert out.column(name).to_pylist() == table.column(name).to_pylist() - rows = [data.as_dict() for _, data in source.iter_data()] - assert rows[0]["wide_key"] == {1e-50: 1, 2e-50: 2} - assert rows[0]["dict_value"] == {"a": 0.5} - - def test_a_plain_arrow_declared_float32_value_is_still_narrowed(self) -> None: - """Known limitation: a plain value (not a key or element) is narrowed as before.""" - source = DictSource( - [{"id": 1, "h": 0.1}], - tag_columns=["id"], - tag_only_columns=True, - data_schema=pa.schema([("id", pa.int64()), ("h", pa.float32())]), - ) - assert source.as_table().column("h").to_pylist() == [float(np.float32(0.1))] - - -@pytest.mark.parametrize("cls", [Datagram, Tag, Data]) -@pytest.mark.parametrize("declaration", ["python", "type", "field"]) -def test_datagram_with_columns_refuses_declared_narrow_dict_key(cls, declaration): - arrow_type = _dict_of(pa.float32()) - declared = { - "python": dict[np.float32, int], - "type": arrow_type, - "field": pa.field("k", arrow_type), - }[declaration] - with pytest.raises(NarrowFloatKeyError, match="column 'k'|Column 'k'"): - cls({"id": 1}).with_columns({"k": declared}, k={1e-50: 1, 2e-50: 2}) - - -@pytest.mark.parametrize("arrow_type", NARROW) -@pytest.mark.parametrize("stored", [False, True]) -@pytest.mark.parametrize("outer_set", [False, True]) -def test_native_nested_set_refuses_narrow_element( - arrow_type: pa.DataType, stored: bool, outer_set: bool -) -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - from orcapod.logical_types.list_logical_type_factory import ( - ArrowElement, - ListLogicalType, - ) - - inner = ListLogicalType(ArrowElement(float, arrow_type), is_set=True) - outer = ListLogicalType(inner, is_set=outer_set).get_arrow_extension_type() - storage = pa.array([[]], type=outer.storage_type) - live = pa.ExtensionArray.from_storage(outer, storage) - table = pa.table({"id": [1], "k": live}) - if stored: - table = pa.Table.from_arrays( - [table["id"], storage], schema=storage_form_schema(table.schema) - ) - with pytest.raises(NarrowFloatKeyError, match="set element type"): - ArrowTableSource(table, tag_columns="id", source_id="nested-set") - - -@pytest.mark.parametrize("operator", ["batch", "group_by", "merge_join"]) -def test_struct_aggregation_keeps_narrow_float_as_data(operator: str) -> None: - from orcapod.core.operators import Batch, GroupBy, MergeJoin - - pair = {"key": 0.5, "value": 1} - pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) - table = pa.table({"id": [1], "pair": pa.array([pair], type=pair_type)}) - source = ArrowTableSource( - table, tag_columns="id", tag_only_columns=True, source_id="pair" - ) - if operator == "batch": - result = Batch().static_process(source) - elif operator == "group_by": - result = GroupBy("id").static_process(source) - else: - result = MergeJoin().static_process(source, source) - assert result.as_table()["pair"].to_pylist() == [ - [pair, pair] if operator == "merge_join" else [pair] - ] - assert next(result.iter_data())[1].as_table()["pair"].to_pylist() == ( - result.as_table()["pair"].to_pylist() - ) - - -def test_struct_aggregation_replays_from_delta(tmp_path: Path) -> None: - from orcapod.core.nodes.operator_node import OperatorJobNode - from orcapod.core.operators import Batch - from orcapod.core.sources.derived_source import DerivedSource - from orcapod.databases import DeltaTableDatabase - from orcapod.pipeline import PipelineJob - from orcapod.types import CacheMode - - pair = {"key": 0.5, "value": 1} - pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) - table = pa.table({"id": [1], "pair": pa.array([pair], type=pair_type)}) - source = ArrowTableSource( - table, tag_columns="id", tag_only_columns=True, source_id="pairs" - ) - writer = OperatorJobNode( - operator=Batch(), - input_streams=(source,), - pipeline_database=DeltaTableDatabase(tmp_path), - cache_mode=CacheMode.LOG, - ) - writer.run() - replay = OperatorJobNode( - operator=Batch(), - input_streams=(source,), - pipeline_database=DeltaTableDatabase(tmp_path), - cache_mode=CacheMode.REPLAY, - ) - replay.run() - - rows = replay.as_table() - assert rows["pair"].type == pa.large_list(pair_type) - assert rows["pair"].to_pylist() == [[pair]] - assert next(replay.iter_data())[1].as_dict()["pair"] == {0.5: 1} - derived = DerivedSource(replay, tags_as_data={"id": "copied_id"}, source_id="copy") - assert derived.as_table()["pair"].to_pylist() == [[pair]] - - job = PipelineJob(database=DeltaTableDatabase(tmp_path / "job")) - with job: - derived.batch(label="batch") - path = tmp_path / "job.json" - job.save(path) - assert PipelineJob.load(path).nodes["copy"].arrow_schemas[1].field("pair").type == ( - rows["pair"].type - ) - - -@pytest.mark.parametrize( - "schema", - [ - pa.schema([("id", pa.int64()), ("k", _dict_of(pa.float32()))]), - {"id": int, "k": set[np.float16]}, - ], -) -def test_polling_source_refuses_declared_schema_without_fetch( - schema: pa.Schema | dict[str, Any], -) -> None: - from unittest.mock import Mock - - from orcapod.core.sources.polling_source import PollingSource - from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol +def test_polling_source_refuses_python_schema_without_fetching() -> None: impl = Mock(spec=DynamicSourceProtocol) - impl.schema.return_value = schema - with pytest.raises(NarrowFloatKeyError, match="column 'k'|Column 'k'"): + impl.schema.return_value = {"id": int, "k": set[np.float16]} + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): PollingSource(impl, "id", source_id="poll", record_id_columns="id") impl.fetch.assert_not_called() -@pytest.mark.parametrize("width", NARROW) -@pytest.mark.parametrize("kind", ["dict", "set"]) -def test_saved_arrow_schema_preserves_narrow_keys( - width: pa.DataType, kind: str -) -> None: - from orcapod import SourceNode - from orcapod.pipeline.serialization import ( - arrow_type_texts, - deserialize_arrow_schema, - deserialize_schema, - ) - - arrow_type = _dict_of(width) if kind == "dict" else _live_set(width) - schema = pa.schema([pa.field("k", arrow_type, nullable=False)]) - columns = arrow_type_texts(schema) - restored = deserialize_arrow_schema({"columns": columns, "nullable": []}) - assert arrow_type_texts(restored) == columns - assert not restored.field("k").nullable - expected = dict[float, int] if kind == "dict" else set[float] - assert deserialize_schema(columns, nullable=[]) == {"k": expected} - - with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - SourceNode("declared", pa.schema([("id", pa.int64())]), schema) - - -def test_saved_cached_source_keeps_its_legacy_identity(tmp_path: Path) -> None: - """A saved inner-source identity can outlive the in-memory source.""" - from orcapod.pipeline.serialization import ( - arrow_type_texts, - resolve_source_from_config, - ) - from orcapod.databases import DeltaTableDatabase - from orcapod.pipeline import PipelineJob - from orcapod.sources import CachedSource - - @function_pod(output_keys="doubled") - def double(v: int | None) -> int: - return 2 * (v or 0) - - source = ArrowTableSource( - pa.table({"id": [1], "v": [3], "k": [0.5]}), - tag_columns="id", - tag_only_columns=True, - source_id="input", - ) - job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) - with job: - double.pod( - CachedSource(source, cache_database=DeltaTableDatabase(tmp_path / "cache")), - label="double", - ) - path = tmp_path / "job.json" - job.save(path) - saved = json.loads(path.read_text()) - sources = saved["bindings"]["sources"] - inner = sources["input"]["inner_source"] - legacy = pa.schema([("k", _live_set(pa.float32()))]) - inner["data_schema"].update(arrow_type_texts(legacy)) - path.write_text(json.dumps(saved)) - - proxy = resolve_source_from_config(inner, fallback_to_proxy=True) - assert proxy.output_schema()[1]["k"] == set[float] | None - resaved = tmp_path / "resaved.json" - restored = PipelineJob.load(path) - assert restored.unbound_sources == ["input"] - restored.save(resaved) - assert json.loads(resaved.read_text())["bindings"]["sources"] == sources - - -def test_legacy_delta_job_keeps_its_source_bound( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - from deltalake import write_deltalake - - from orcapod.core.sources import stream_builder - from orcapod.databases import DeltaTableDatabase - from orcapod.pipeline import PipelineJob - - delta_path = tmp_path / "input" - values = pa.table( - {"id": [1], "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(pa.float32()))} - ) - write_deltalake(delta_path, values) - with monkeypatch.context() as legacy: - legacy.setattr( - stream_builder, - "require_schema_without_narrow_float_keys", - lambda *args, **kwargs: None, - ) - source = DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) - job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) - with job: - source.batch(label="batch") - path = tmp_path / "job.json" - job.save(path) - - restored = PipelineJob.load(path) - assert not restored.unbound_sources - reopened = restored.sources[source.source_name] - assert isinstance(reopened, DeltaTableSource) - write_deltalake(delta_path, values, mode="append") - assert reopened.check_for_new_data() - assert reopened.as_table().num_rows == 2 - with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) - - -def test_saved_delta_job_reports_new_narrow_schema(tmp_path: Path) -> None: - from deltalake import write_deltalake - - from orcapod.databases import DeltaTableDatabase - from orcapod.pipeline import PipelineJob - - delta_path = tmp_path / "input" - - def table(key_type: pa.DataType) -> pa.Table: - return pa.table( - { - "id": [1], - "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(key_type)), - } - ) - - write_deltalake(delta_path, table(pa.float64())) - source = DeltaTableSource(delta_path, tag_columns="id", tag_only_columns=True) - job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) - with job: - source.batch(label="batch") - path = tmp_path / "job.json" - job.save(path) - - write_deltalake( - delta_path, table(pa.float32()), mode="overwrite", schema_mode="overwrite" - ) - with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - PipelineJob.load(path) - - -def test_legacy_spiral_job_keeps_its_source_bound( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - from orcapod.core.sources import SpiralDBTableSource, stream_builder - from orcapod.databases import DeltaTableDatabase - from orcapod.pipeline import PipelineJob - from tests.test_databases import fake_spiral_sdk - - with fake_spiral_sdk.install(tmp_path / "spiral"): - project = fake_spiral_sdk.ExternalProject("p") - table = project.create_table( - "default.pairs", key_schema=pa.schema([("id", pa.string())]) - ) - table.write( - pa.table( - { - "id": ["a"], - "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(pa.float32())), - } - ) - ) - with monkeypatch.context() as legacy: - legacy.setattr( - stream_builder, - "require_schema_without_narrow_float_keys", - lambda *args, **kwargs: None, - ) - source = SpiralDBTableSource( - "p", "pairs", tag_columns="id", tag_only_columns=True - ) - with source: - job = PipelineJob(database=DeltaTableDatabase(tmp_path / "output")) - with job: - source.batch(label="batch") - path = tmp_path / "job.json" - job.save(path) - - restored = PipelineJob.load(path) - assert not restored.unbound_sources - reopened = restored.sources[source.source_name] - assert isinstance(reopened, SpiralDBTableSource) - with reopened: - assert reopened.pipeline_hash() == source.pipeline_hash() - assert reopened.as_table()["k"].to_pylist() == [ - [{"key": 0.5, "value": 1}] - ] - - -def test_direct_spiral_source_reports_narrow_schema(tmp_path: Path) -> None: - from orcapod.sources import SpiralDBTableSource - from tests.test_databases import fake_spiral_sdk - - with fake_spiral_sdk.install(tmp_path): - project = fake_spiral_sdk.ExternalProject("p") - table = project.create_table( - "default.pairs", key_schema=pa.schema([("id", pa.string())]) - ) - table.write( - pa.table( - { - "id": ["a"], - "k": pa.array([[{"key": 0.5, "value": 1}]], _dict_of(pa.float32())), - } - ) - ) - with pytest.raises(NarrowFloatKeyError, match=r"(?s)table 'pairs'.*column 'k'"): - SpiralDBTableSource("p", "pairs", tag_columns="id", tag_only_columns=True) - - -@pytest.mark.parametrize("declared_in_arrow", [False, True]) -def test_pipeline_input_slot_refuses_declared_narrow_type( - declared_in_arrow: bool, -) -> None: - from orcapod.core.nodes.source_node import SourceNode - from orcapod.types import Schema - - with pytest.raises(NarrowFloatKeyError, match="column 'k'|Column 'k'"): - if declared_in_arrow: - SourceNode( - "inputs", pa.schema([]), pa.schema([("k", _dict_of(pa.float32()))]) - ) - else: - SourceNode("inputs", Schema({}), Schema({"k": dict[np.float32, int]})) - - -@pytest.mark.parametrize("cls", [Datagram, Tag, Data]) -@pytest.mark.parametrize("kind", ["dataclass", "structural", "pydantic"]) -def test_datagram_refuses_declared_user_class_field(cls, kind): - from orcapod import dataclass as structural_dataclass - from pydantic import ConfigDict, create_model - - annotation = dict[np.float32, int] - if kind == "pydantic": - model_config = ConfigDict(arbitrary_types_allowed=True) - model = create_model( - "NarrowKeyModel", __config__=model_config, bad=(annotation, ...) - ) - else: - model = type("NarrowKeyClass", (), {"__annotations__": {"bad": annotation}}) - model = ( - structural_dataclass(model) - if kind == "structural" - else dataclasses.dataclass(model) - ) - with pytest.raises(NarrowFloatKeyError, match=r"k.*bad|bad"): - cls({"k": model(bad={})}, python_schema={"k": model}) - - -@pytest.mark.parametrize("is_source", [False, True]) -def test_plain_list_with_unrelated_extension_metadata_is_allowed(is_source): - field = pa.field( - "k", - pa.large_list(pa.float32()), - metadata={b"ARROW:extension:metadata": b'{"category":"set"}'}, - ) - table = pa.Table.from_arrays( - [pa.array([1]), pa.array([[0.5]], type=field.type)], - schema=pa.schema([pa.field("id", pa.int64()), field]), - ) - result = ArrowTableSource(table, tag_columns="id") if is_source else Datagram(table) - assert result.as_table()["k"].to_pylist() == [[0.5]] - - -@pytest.mark.parametrize("container", ["union", "dictionary", "list_view", "run_end"]) -def test_declared_mutation_refuses_map_through_other_arrow_containers( - container: str, -) -> None: - inner = pa.map_(pa.float32(), pa.int64()) - if container == "union": - outer = pa.union([pa.field("map", inner)], mode="sparse") - elif container == "dictionary": - outer = pa.dictionary(pa.int8(), inner) # pyright: ignore[reportArgumentType] # Arrow accepts map values - elif container == "list_view": - outer = pa.large_list_view(inner) - else: - outer = pa.run_end_encoded(pa.int16(), inner) # pyright: ignore[reportArgumentType] # Arrow accepts map values - with pytest.raises(NarrowFloatKeyError, match="dict key type"): - Datagram({"id": 1}).with_columns({"k": outer}, k=[]) - - -@pytest.mark.parametrize("source", ["dict", "frame", "csv"]) -def test_narrow_key_diagnostic_precedes_source_value_conversion( - tmp_path: Path, source: str -) -> None: - from orcapod.core.sources.csv_source import CSVSource - - schema = pa.schema([("id", pa.int64()), ("k", _dict_of(pa.float32()))]) - with pytest.raises(NarrowFloatKeyError, match="float64"): - if source == "dict": - DictSource([{"id": 1, "k": "oops"}], "id", data_schema=schema) - elif source == "frame": - DataFrameSource({"id": [1], "k": ["oops"]}, "id", schema=schema) - else: - path = tmp_path / "narrow.csv" - path.write_text("id,k\n1,oops\n") - CSVSource(str(path), "id", schema=schema) - - -@pytest.mark.parametrize("annotation", [set[np.float16], dict[np.float16, int]]) -def test_pod_refuses_python_float16_key_or_element(annotation): - def run(k): - return len(k) - - run.__annotations__ = {"k": annotation, "return": int} - with pytest.raises(NarrowFloatKeyError, match="float64"): - function_pod(output_keys="n")(run) - - -def test_duplicate_key_struct_is_not_dict_shape() -> None: - pair = pa.struct( - [("key", pa.float32()), ("key", pa.int64()), ("value", pa.int64())] - ) - arrow_type = pa.large_list(pair) - assert dict_entry_fields(arrow_type) is None - table = pa.schema([("id", pa.int64()), ("k", arrow_type)]).empty_table() - with pytest.raises(ValueError, match=r"column 'k'|Column 'k'"): - ArrowTableSource(table, tag_columns="id") - with pytest.raises(ValueError, match=r"column 'k'|Column 'k'"): - DictSource([{"id": 1, "k": []}], "id", data_schema=table.schema) - - -@pytest.mark.parametrize( - "derived", [False, True], ids=["static-batch", "derived-source"] -) -@pytest.mark.parametrize( - "legacy", [False, True], ids=["current-blueprint", "old-provenance-marker"] -) -def test_standalone_blueprint_loads_inherited_batch_input( - tmp_path: Path, derived: bool, legacy: bool -) -> None: - from orcapod import SourceNode - from orcapod.core.operators import Batch - from orcapod.databases import DeltaTableDatabase - from orcapod.pipeline import Pipeline, PipelineJob - - pair_type = pa.struct([("key", pa.float32()), ("value", pa.int64())]) - table = pa.table( - {"id": [1], "pair": pa.array([{"key": 0.5, "value": 1}], type=pair_type)} - ) - source = ArrowTableSource( - table, tag_columns="id", tag_only_columns=True, source_id="pairs" - ) - if derived: - job = PipelineJob( - name="parent", database=DeltaTableDatabase(tmp_path / "cache") - ) - with job: - source.batch(label="parent") - job.run() - stream = job.nodes["parent"].as_source( - tags_as_data={"id": "copied_id"}, source_id="derived_pairs" - ) - else: - stream = Batch().static_process(source) - - pipeline = Pipeline("child") - with pipeline: - Batch()(stream, label="child") - path = tmp_path / "blueprint.json" - pipeline.save(path) - saved = json.loads(path.read_text()) - slot_config = next( - node["source_config"] - for node in saved["nodes"].values() - if node["node_type"] == "source" - ) - if legacy: - slot_config["inherited_types"] = False - path.write_text(json.dumps(saved)) - - restored = Pipeline.load(path) - slot = next(node for node in restored.nodes.values() if node.node_type == "source") - assert isinstance(slot, SourceNode) - assert slot.arrow_schemas[1].field("pair").type == pa.large_list(pair_type) - assert slot.pipeline_hash() == pipeline.nodes[slot.name].pipeline_hash() - restored.save(path) - assert len(Pipeline.load(path).nodes) == 2 - - -@pytest.mark.parametrize("width", NARROW) -@pytest.mark.parametrize("storage_form", [False, True], ids=["live", "storage"]) -@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) -def test_arrow_sources_refuse_narrow_set_before_polars( - width: pa.DataType, storage_form: bool, polling: bool -) -> None: - from unittest.mock import Mock - - from orcapod.core.sources.polling_source import PollingSource - from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol - from orcapod.types import Cursor - - extension = _live_set(width) - values = pa.array([[0.5]], type=extension.storage_type) - if storage_form: - schema = pa.schema( - [pa.field("id", pa.int64()), _set_storage_field(width).with_name("k")] - ) - table = pa.Table.from_arrays([pa.array([1]), values], schema=schema) - else: - table = pa.table( - {"id": [1], "k": pa.ExtensionArray.from_storage(extension, values)} - ) - - if polling: - impl = Mock(spec=DynamicSourceProtocol) - impl.schema.return_value = None - impl.fetch.return_value = (Cursor(value=1), table) - source = PollingSource(impl, "id", source_id="poll", record_id_columns="id") - with pytest.raises(NarrowFloatKeyError, match="column 'k'.*set element type"): - source.check_for_new_data() - else: - with pytest.raises(NarrowFloatKeyError, match="column 'k'.*set element type"): - DataFrameSource(table, tag_columns="id", source_id="dataframe") - - -def _polars_source_table(data: Any, *, polling: bool) -> pa.Table: - from unittest.mock import Mock - - from orcapod.sources import PollingSource - from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol - from orcapod.types import Cursor - - if polling: - impl = Mock(spec=DynamicSourceProtocol) - impl.schema.return_value = None - impl.fetch.return_value = (Cursor(value=1), data) - source = PollingSource(impl, "id", source_id="poll", record_id_columns="id") - else: - source = DataFrameSource( - data, tag_columns="id", source_id="dataframe", tag_only_columns=True - ) - return source.as_table() - - -@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) -@pytest.mark.parametrize( - "nested_mapping", [False, True], ids=["table", "nested-mapping"] -) -def test_portable_native_list_of_pairs_keeps_its_rows( - polling: bool, nested_mapping: bool -) -> None: - written = subprocess.check_output( - [ - sys.executable, - "-c", - """ -from dataclasses import dataclass -import sys - -import numpy as np -import pyarrow as pa -from orcapod import contexts - -@dataclass(frozen=True) -class PortablePair: - key: np.float32 - value: int - -table = contexts.resolve_context(None).type_converter.python_dicts_to_arrow_table( - [{"id": 1, "k": [PortablePair(np.float32(0.5), 1)]}], - python_schema={"id": int, "k": list[PortablePair]}, -) -with pa.ipc.new_file(sys.stdout.buffer, table.schema) as writer: - writer.write(table) -""", - ] - ) - table = pa.ipc.open_file(pa.BufferReader(written)).read_all() - metadata = table.schema.field("k").metadata - assert metadata is not None - assert bytes(metadata[b"ARROW:extension:name"]).startswith(b"list[") - pairs = [{"key": 0.5, "value": 1}] - if nested_mapping: - struct = pa.StructArray.from_arrays( - [table["k"].combine_chunks()], fields=[table.schema.field("k")] - ) - data = {"id": [1], "outer": {"nested": struct, "other": [2]}} - result = _polars_source_table(data, polling=polling) - assert result["outer"].to_pylist() == [{"nested": {"k": pairs}, "other": 2}] - else: - result = _polars_source_table(table, polling=polling) - assert result["k"].type == table["k"].type - assert result["k"].to_pylist() == [pairs] - - -@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) -@pytest.mark.parametrize("width", NARROW, ids=str) -@pytest.mark.parametrize( - "shape", ["array", "pandas", "set-in-struct", "set-in-list", "map-in-struct"] -) -def test_nested_mapping_checks_arrow_declarations( - polling: bool, width: pa.DataType, shape: str -) -> None: - set_field = _set_storage_field(width) - set_storage = pa.array([[0.5]], type=set_field.type) - diagnostic = "set element type" - if shape == "set-in-struct": - column = pa.StructArray.from_arrays([set_storage], fields=[set_field]) - elif shape == "set-in-list": - column = pa.LargeListArray.from_arrays( - pa.array([0, 1], type=pa.int64()), - set_storage, - type=pa.large_list(set_field), - ) - elif shape == "map-in-struct": - mapping = pa.array([[(0.5, 1)]], type=pa.map_(width, pa.int64())) - column = pa.StructArray.from_arrays([mapping], names=["mapping"]) - diagnostic = "dict key type" - else: - extension = _live_set(width) - array = pa.ExtensionArray.from_storage(extension, set_storage) - column = ( - pd.Series(array, dtype=pd.ArrowDtype(extension)) - if shape == "pandas" - else array - ) - data = {"id": [1], "outer": {"column": column}} - with pytest.raises( - NarrowFloatKeyError, match=f"column 'outer'.*{diagnostic} {width}" - ): - _polars_source_table(data, polling=polling) - - -@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) -def test_pandas_python_string_is_exported_once( - polling: bool, monkeypatch: pytest.MonkeyPatch -) -> None: - data = pd.DataFrame( - {"id": [1, 2], "k": pd.Series(["a", None], dtype="string[python]")} - ) - string_array = pd.arrays.StringArray - export = string_array.__arrow_array__ - exports = [] - - def count_export(array, *args, **kwargs): - exports.append(len(array)) - return export(array, *args, **kwargs) - - monkeypatch.setattr(string_array, "__arrow_array__", count_export) - assert _polars_source_table(data, polling=polling)["k"].to_pylist() == ["a", None] - assert exports == [2] - - -@pytest.mark.parametrize( - "python_narrow,arrow_narrow", [(True, True), (True, False), (False, True)] -) -def test_source_node_validates_both_schema_declarations_with_arrow_override( - python_narrow: bool, arrow_narrow: bool -) -> None: - from orcapod import SourceNode - from orcapod.types import Schema - - with pytest.raises(NarrowFloatKeyError, match="[Cc]olumn 'k'"): - SourceNode( - "slot", - Schema({"id": int}), - Schema({"k": dict[np.float32, int] if python_narrow else dict[float, int]}), - arrow_schemas=( - pa.schema([("id", pa.int64())]), - pa.schema( - [("k", _dict_of(pa.float32() if arrow_narrow else pa.float64()))] - ), - ), - ) - - -@pytest.mark.parametrize("nonnullable", [False, True], ids=["mixed", "nonnullable"]) -def test_datagram_checks_narrow_arrow_declaration_before_values( - nonnullable: bool, -) -> None: - narrow = _dict_of(pa.float32()) - row = Data({"id": 1}) - with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - if nonnullable: - row.with_columns({"k": pa.field("k", narrow, nullable=False)}, k=None) - else: - row.with_columns({"m": int, "k": narrow}, m="invalid integer", k={}) - - -@pytest.mark.parametrize("width", NARROW) -@pytest.mark.parametrize( - "input_kind", - [ - "reader", - "mapping", - "capsule", - "array_capsule", - "pandas", - "pandas_nested", - "pandas_in_mapping", - "pandas_sequence", - "pandas_iterator", - ], -) -@pytest.mark.parametrize("polling", [False, True], ids=["dataframe", "polling"]) -def test_arrow_sources_check_readers_and_column_mappings(width, input_kind, polling): - from unittest.mock import Mock - - from orcapod.core.sources import PollingSource - from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol - from orcapod.types import Cursor - - extension = _live_set(width) - values = pa.array([[0.5]], type=extension.storage_type) - table = pa.table( - {"id": [1], "k": pa.ExtensionArray.from_storage(extension, values)} - ) - - class ArrowStream: - def __arrow_c_stream__(self, requested_schema=None): - return table.__arrow_c_stream__(requested_schema) - - class ArrowArray: - def __arrow_c_array__(self, requested_schema=None): - return table.to_batches()[0].__arrow_c_array__(requested_schema) - - if input_kind == "mapping": - data = {"id": [1], "k": table["k"]} - elif input_kind == "reader": - data = table.to_reader() - elif input_kind.startswith("pandas") and input_kind != "pandas_nested": - series = pd.Series(table["k"], name="k", dtype=pd.ArrowDtype(extension)) - if input_kind in {"pandas_sequence", "pandas_iterator"}: - series_columns = [pd.Series([1], name="id"), series] - data = ( - iter(series_columns) - if input_kind == "pandas_iterator" - else series_columns - ) - else: - columns = {"id": [1], "k": series} - data = pd.DataFrame(columns) if input_kind == "pandas" else columns - elif input_kind == "pandas_nested": - nested = pa.StructArray.from_arrays( - [values], fields=[_set_storage_field(width)] - ) - data = pd.DataFrame( - {"id": [1], "k": pd.Series(nested, dtype=pd.ArrowDtype(nested.type))} - ) - elif input_kind == "array_capsule": - data = ArrowArray() - else: - data = ArrowStream() - - with pytest.raises(NarrowFloatKeyError, match="column 'k'.*set element type"): - if polling: - impl = Mock(spec=DynamicSourceProtocol) - impl.schema.return_value = None - impl.fetch.return_value = (Cursor(value=1), data) - source = PollingSource(impl, "id", source_id="poll", record_id_columns="id") - source.check_for_new_data() - else: - DataFrameSource(data, tag_columns="id", source_id="dataframe") - - -@pytest.mark.parametrize("entry", ["converter", "source", "datagram"]) -def test_registry_free_converter_refuses_narrow_set(entry): - from orcapod.semantic_types import UniversalTypeConverter - - converter = UniversalTypeConverter() - context = dataclasses.replace( - contexts.resolve_context(None), type_converter=converter - ) - with pytest.raises(NarrowFloatKeyError, match="set element type"): - if entry == "converter": - converter.python_type_to_arrow_type(set[np.float32]) - elif entry == "source": - DictSource( - [{"id": 1, "k": {1e-50, 2e-50}}], - data_schema={"id": int, "k": set[np.float32]}, - tag_columns="id", - data_context=context, - ) - else: - Data( - {"k": {1e-50, 2e-50}}, - python_schema={"k": set[np.float32]}, - data_context=context, - ).as_table() - - -@pytest.mark.parametrize("narrow_declaration", ["arrow", "python"]) -def test_partially_inherited_job_slot_validates_explicit_override(narrow_declaration): - from orcapod.core.nodes import SourceJobNode - from orcapod.core.operators import Batch - from orcapod.core.streams.base import typed_arrow_schemas - from orcapod.types import Schema - - pair = pa.struct([("key", pa.float32()), ("value", pa.int64())]) - source = ArrowTableSource( - pa.table({"id": [1], "k": pa.array([{"key": 0.5, "value": 1}], type=pair)}), - tag_columns="id", - tag_only_columns=True, - source_id="pair", - ) - batched = Batch().static_process(source) - tag_arrow, data_arrow = typed_arrow_schemas(batched) - # Both fully and partially inferred schemas retain the operator's layout. - assert SourceJobNode("all", bound_source=batched).arrow_schemas[1] == data_arrow - assert ( +def test_source_slot_checks_explicit_python_declaration_even_with_arrow_override() -> ( + None +): + data = Schema({"k": dict[np.float32, int]}) + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + SourceNode("input", Schema({}), data) + source = DictSource([{"id": 1, "k": {"a": 1}}], tag_columns="id") + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): SourceJobNode( - "partial", tag_schema=Schema({"id": list[int]}), bound_source=batched - ).arrow_schemas[1] - == data_arrow - ) - - key_type = np.float32 if narrow_declaration == "python" else float - declared_arrow = ( - data_arrow - if narrow_declaration == "arrow" - else pa.schema([pa.field("k", _dict_of(pa.float64()), nullable=False)]) - ) - with pytest.raises(NarrowFloatKeyError, match="[Cc]olumn 'k'"): - SourceJobNode( - "override", - data_schema=Schema({"k": dict[key_type, int]}), - bound_source=batched, - arrow_schemas=(tag_arrow, declared_arrow), + "input", + bound_source=source, + data_schema=data, + arrow_schemas=source.arrow_schemas, ) -@pytest.mark.parametrize("width", NARROW) -def test_direct_converter_checks_explicit_arrow_schema(width): - with pytest.raises(NarrowFloatKeyError, match="column 'k'.*dict key type"): - _converter().python_dicts_to_arrow_table( - [{"k": {1e-50: 1, 2e-50: 2}}], - arrow_schema=pa.schema([("k", _dict_of(width))]), +def test_datagram_checks_new_python_declaration_next_to_an_arrow_declaration() -> None: + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + Data({"id": 1}).with_columns( + {"k": dict[np.float32, int], "v": pa.int64()}, k={}, v=1 ) - - -def test_arrow_held_datagram_update_preserves_existing_schema(): - table = pa.table({"k": pa.array([[]], type=_dict_of(pa.float32()))}) - assert Data(table).update(k={1e-50: 1, 2e-50: 2}).as_dict()["k"] == {0.0: 2} - - -def test_datagram_checks_new_arrow_declaration_before_materializing_existing_data(): - row = Data({"m": "invalid integer"}, python_schema={"m": int}) - with pytest.raises(NarrowFloatKeyError, match="column 'k'"): - row.with_columns({"k": _dict_of(pa.float32())}, k={}) - - -@dataclasses.dataclass(frozen=True) -class _CustomStringContainers: - pairs: _StringDict - items: _StringSet - - -@pytest.mark.asyncio -@pytest.mark.parametrize("route", ["dict", "arrow", "metadata"]) -async def test_nested_custom_string_containers_own_storage(route: str) -> None: - from orcapod.logical_types.canonical_form import storage_form_schema - - context = contexts.create_registry().get_context("v1") - converter = context.type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type( - _make_logical_type( - "test.narrow_keys.nested_string_dict", - _StringDict, - pa.struct([("values", _dict_of(pa.float32()))]), - lambda value: { - "values": [ - {"key": float(key), "value": item} - for key, item in value.values.items() - ] - }, - lambda stored: _StringDict( - {str(row["key"]): row["value"] for row in stored["values"]} - ), - ) - ) - converter.register_logical_type( - _make_logical_type( - "test.narrow_keys.nested_string_set", - _StringSet, - pa.struct([("values", pa.large_list(pa.float32()))]), - lambda value: {"values": [float(item) for item in value.values]}, - lambda stored: _StringSet({str(item) for item in stored["values"]}), - ) - ) - item = _CustomStringContainers(_StringDict({"0.5": 1}), _StringSet({"0.5"})) - rows: list[dict[str, Any]] = [{"id": 1, "k": item}] - schema = {"id": int, "k": _CustomStringContainers} - if route == "dict": - source = DictSource(rows, "id", data_schema=schema, data_context=context) - else: - table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) - if route == "metadata": - table = table.cast(storage_form_schema(table.schema)) - source = ArrowTableSource(table, "id", data_context=context) - stored = [ - { - "pairs": {"values": [{"key": 0.5, "value": 1}]}, - "items": {"values": [0.5]}, - } - ] - assert source.as_table()["k"].to_pylist() == stored - assert [ - data.as_table()["k"].to_pylist() async for _, data in source.async_iter_data() - ] == [stored] - assert [data.as_table()["k"].to_pylist() for _, data in source.iter_data()] == [ - stored - ] - - # The same boundary applies under bare Arrow containers and both native - # logical containers, no matter which form carries the identifiers. - nested = pa.schema( - [ - ( - "bare_list", - pa.list_(converter.register_python_class(_CustomStringContainers)), - ), - ( - "bare_struct", - pa.struct( - [("v", converter.register_python_class(_CustomStringContainers))] - ), - ), - ( - "native_list", - converter.register_python_class(list[_CustomStringContainers]), - ), - ( - "native_set", - converter.register_python_class(set[_CustomStringContainers]), - ), - ] - ) - for arrow_schema in (nested, storage_form_schema(nested)): - require_schema_without_narrow_float_keys(arrow_schema, converter=converter) - - -@dataclasses.dataclass -class _HalfDictField: - values: list[dict[np.float16, int]] - - -@dataclasses.dataclass -class _HalfSetField: - values: set[np.float16] - - -@pytest.mark.parametrize( - "instance", - [_HalfDictField([{np.float16(0.5): 1}]), _HalfSetField({np.float16(0.5)})], -) -def test_datagram_refuses_declared_half_float_field(instance: Any) -> None: - with pytest.raises(NarrowFloatKeyError, match=r"Column 'k'.*values"): - Data({"k": instance}, python_schema={"k": type(instance)}) - - -@pytest.mark.parametrize( - ("value", "annotation"), - [ - ({np.float32(0.5): 1}, dict[np.float32, int]), - ({np.float32(0.5)}, set[np.float32]), - ], -) -@pytest.mark.parametrize("route", ["data", "converter"]) -def test_undeclared_float32_dict_and_set_are_accepted( - value: Any, annotation: Any, route: str -) -> None: - context = contexts.create_registry().get_context("v1") - converter = context.type_converter - rows = [{"k": value}] - if route == "data": - row = Data(rows[0], data_context=context) - table = row.as_table() - else: - table = converter.python_dicts_to_arrow_table(rows) - assert converter.arrow_table_to_python_dicts(table) == rows - with pytest.raises(NarrowFloatKeyError): - converter.python_dicts_to_arrow_table(rows, python_schema={"k": annotation}) - - -def test_polars_source_accepts_undeclared_python_object_dict() -> None: - columns = { - "id": [1], - "k": pl.Series("k", [{np.float32(0.5): 1}], dtype=pl.Object), - } - table = DataFrameSource(columns, "id").as_table() - assert table["k"].type == _dict_of(pa.float32()) - assert table["k"].to_pylist() == [[{"key": 0.5, "value": 1}]] - - -_USER_CLASS_IPC_WRITER = """ -import sys -from dataclasses import make_dataclass -from pathlib import Path - -import numpy as np -import pyarrow as pa -from pydantic import ConfigDict, create_model - -from orcapod import contexts, dataclass -from orcapod.semantic_types.narrow_float_keys import converting_existing_types - - -def make_class(kind, name, field, annotation): - if kind == "pydantic": - cls = create_model( - name, - __config__=ConfigDict(arbitrary_types_allowed=True), - __module__=__name__, - **{field: (annotation, ...)}, - ) - elif kind == "structural": - cls = dataclass(name=f"test.ipc.{name}")( - type(name, (), {"__module__": __name__, "__annotations__": {field: annotation}}) - ) - else: - cls = make_dataclass( - name, [(field, annotation)], namespace={"__module__": __name__} - ) - globals()[name] = cls - return cls - - -def write(name, item): - with converting_existing_types(): - table = converter.python_dicts_to_arrow_table( - [{"id": 1, "k": item}], python_schema={"id": int, "k": type(item)} - ) - with pa.ipc.new_file(Path(sys.argv[1]) / f"{name}.arrow", table.schema) as writer: - writer.write_table(table) - - -converter = contexts.resolve_context(None).type_converter -wide = make_class("dataclass", "Wide", "entries", dict[str, int]) -write("wide", wide(entries={"string": 4})) -for inner_kind, outer_kind in [ - ("dataclass", "dataclass"), - ("dataclass", "pydantic"), - ("pydantic", "dataclass"), - ("pydantic", "pydantic"), - ("structural", "dataclass"), - ("structural", "pydantic"), - ("structural", "structural"), -]: - for container, annotation, value in [ - ("dict", dict[np.float32, int], {np.float32(0.5): 4}), - ("set", set[np.float32], {np.float32(0.5)}), - ]: - inner = make_class(inner_kind, f"{inner_kind.title()}{container}Inner", - "entries", annotation) - outer = make_class(outer_kind, f"{outer_kind.title()}{container}Outer", - "nested", inner) - write(f"{inner_kind}-{outer_kind}-{container}", outer(nested=inner(entries=value))) -""" - -_USER_CLASS_IPC_READER = """ -import asyncio -import sys -from dataclasses import dataclass -from pathlib import Path - -import numpy as np -import pyarrow as pa - -from orcapod.semantic_types.narrow_float_keys import NarrowFloatKeyError -from orcapod.sources import ArrowTableSource, DataFrameSource, PollingSource -from orcapod.types import Cursor, PollingConfig - - -@dataclass -class Wide: - entries: dict[np.float32, int] - - -class Poll: - def schema(self): - return None - - async def fetch(self, cursor=None): - return Cursor(value=1), table - - async def poll(self, cursor=None): - return cursor is None - - async def close(self): - pass - - def identity(self): - return ("user-class-ipc",) - - -async def read_async(source): - rows = source.async_iter_data() - try: - _, data = await asyncio.wait_for(anext(rows), timeout=5) - return data.as_table()["k"].to_pylist() - finally: - await rows.aclose() - - -def read(route): - if route in ("arrow", "dataframe"): - cls = ArrowTableSource if route == "arrow" else DataFrameSource - return cls(table, "id", source_id=route).as_table()["k"].to_pylist() - source = PollingSource( - Poll(), "id", source_id=route, record_id_columns="id", - polling_config=PollingConfig(interval=0.01, duration=0.5), - ) - if route == "polling-async": - return asyncio.run(read_async(source)) - source.check_for_new_data() - return source.as_table()["k"].to_pylist() - - -route, directory, container = sys.argv[1:] -directory = Path(directory) -paths = [directory / "wide.arrow"] if container == "wide" else sorted( - directory.glob(f"*-{container}.arrow") -) -assert len(paths) == (1 if container == "wide" else 7) -for path in paths: - table = pa.ipc.open_file(path).read_all() - if container == "wide": - assert read(route) == [{"entries": [{"key": "string", "value": 4}]}] - else: - try: - read(route) - except NarrowFloatKeyError as exc: - expected = "dict key type float" if container == "dict" else "set element type float" - assert expected in str(exc), str(exc) - assert ".nested:" in str(exc) and ".entries:" in str(exc), str(exc) - else: - raise AssertionError(f"{route} accepted {path.name}") -""" - - -@pytest.fixture(scope="module") -def user_class_ipc(tmp_path_factory: pytest.TempPathFactory) -> Path: - path = tmp_path_factory.mktemp("user-class-ipc") - subprocess.run( - [sys.executable, "-c", _USER_CLASS_IPC_WRITER, str(path)], check=True - ) - return path - - -@pytest.mark.parametrize("route", ["arrow", "dataframe", "polling", "polling-async"]) -def test_arrow_user_class_uses_stored_fields(user_class_ipc: Path, route: str) -> None: - subprocess.run( - [ - sys.executable, - "-c", - _USER_CLASS_IPC_READER, - route, - str(user_class_ipc), - "wide", - ], - check=True, - ) - - -@pytest.mark.parametrize("route", ["arrow", "dataframe", "polling", "polling-async"]) -@pytest.mark.parametrize("container", ["dict", "set"]) -def test_arrow_nested_user_class_uses_stored_fields( - user_class_ipc: Path, route: str, container: str -) -> None: - subprocess.run( - [ - sys.executable, - "-c", - _USER_CLASS_IPC_READER, - route, - str(user_class_ipc), - container, - ], - check=True, - ) From 6932a7c93441dc243617ca8b7892354af2bf1431 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:59:11 -0800 Subject: [PATCH 26/32] test(sources): type the main Arrow compatibility matrix --- .../test_narrow_float_arrow_compatibility.py | 49 +++++++++++++------ 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py index 1eee7c1f6..b0a62c122 100644 --- a/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py +++ b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py @@ -4,6 +4,7 @@ import asyncio import json +from collections.abc import AsyncGenerator, Callable from dataclasses import dataclass, make_dataclass from pathlib import Path from typing import Any, cast, final @@ -20,6 +21,8 @@ from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.semantic_types import UniversalTypeConverter from orcapod.types import Cursor, PollingConfig SOURCES = ("arrow", "frame", "polling") @@ -59,19 +62,18 @@ class _CustomIntegerCodec(BaseLogicalType): @override def get_arrow_extension_type(self) -> pa.ExtensionType: - return make_arrow_extension_type(_CUSTOM_NAME, _INT_STORAGE)() + factory = make_arrow_extension_type(_CUSTOM_NAME, _INT_STORAGE) + return cast("Callable[[], pa.ExtensionType]", factory)() - @override def get_polars_extension_type(self) -> Any: - return make_polars_extension_type(_CUSTOM_NAME, _INT_STORAGE)() + factory = make_polars_extension_type(_CUSTOM_NAME, _INT_STORAGE) + return cast("Callable[[], Any]", factory)() - @override def python_to_storage( self, value: _CustomInteger, converter: TypeConverterProtocol | None ) -> dict[str, int]: return {"value": value.entries[np.float32(0.5)]} - @override def storage_to_python( self, storage_value: dict[str, int], converter: TypeConverterProtocol | None ) -> _CustomInteger: @@ -95,6 +97,7 @@ def _arrow_input(case: str) -> tuple[pa.Table, contexts.DataContext]: context = _context() if case.startswith("custom"): converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) converter.register_logical_type(_CustomIntegerCodec()) # The custom class's Python implementation contains a narrow key. Its # registered codec presents an integer field in the Arrow declaration. @@ -126,7 +129,13 @@ def _arrow_input(case: str) -> tuple[pa.Table, contexts.DataContext]: replacement = make_dataclass( "Entries", [("entries", dict[np.float32, int])], namespace=namespace ) - context.type_converter.register_python_class(replacement) + assert (replacement.__module__, replacement.__qualname__) == ( + original.__module__, + original.__qualname__, + ) + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_python_class(replacement) else: annotation = ( set[np.float32] if case.endswith("set") else dict[np.float32, int] @@ -169,21 +178,33 @@ def schema(self) -> pa.Schema | None: def identity(self) -> tuple[str]: return ("itl1591-arrow-compatibility",) - async def poll(self, cursor: Cursor | None = None) -> bool: + async def poll(self, cursor: Cursor[int] | None = None) -> bool: return cursor is None - async def fetch(self, cursor: Cursor | None = None) -> tuple[Cursor, pa.Table]: + async def fetch( + self, cursor: Cursor[int] | None = None + ) -> tuple[Cursor[int], pa.Table]: assert cursor is None return Cursor(value=1), self.table + def to_config(self) -> None: + return None + + @classmethod + def from_config(cls, config: dict[str, Any]) -> _PollOnce: + raise NotImplementedError + async def close(self) -> None: pass async def _read_async( - source: ArrowTableSource | DataFrameSource | PollingSource[pa.Table], -) -> tuple[Any, Any]: - rows = source.async_iter_data() + source: ArrowTableSource | DataFrameSource | PollingSource[int], +) -> tuple[TagProtocol, DataProtocol]: + rows = cast( + "AsyncGenerator[tuple[TagProtocol, DataProtocol], None]", + source.async_iter_data(), + ) try: return await asyncio.wait_for(anext(rows), timeout=5) finally: @@ -193,7 +214,7 @@ async def _read_async( def _source_result(case: str, kind: str, asynchronous: bool) -> dict[str, Any]: table, context = _arrow_input(case) declared = table.schema if case.startswith("declared-") else None - source: ArrowTableSource | DataFrameSource | PollingSource[pa.Table] + source: ArrowTableSource | DataFrameSource | PollingSource[int] try: if kind == "arrow": source = ArrowTableSource(table, "id", source_id=kind, data_context=context) @@ -211,7 +232,7 @@ def _source_result(case: str, kind: str, asynchronous: bool) -> dict[str, Any]: polling_config=PollingConfig(interval=0.01, duration=0.5), ) if not asynchronous: - source.check_for_new_data() + _ = source.check_for_new_data() tag, data = ( asyncio.run(_read_async(source)) if asynchronous @@ -238,7 +259,7 @@ def _source_result(case: str, kind: str, asynchronous: bool) -> dict[str, Any]: @pytest.fixture(scope="module") def main_results() -> dict[str, Any]: - """Rows, hashes and pre-existing map errors recorded on main at 1fb2a7f7.""" + """Rows, hashes and pre-existing map errors recorded on main at 14def388.""" return json.loads( Path(__file__).with_name("narrow_float_arrow_main.json").read_text() ) From 4a25aa0d47962a68f991697b83b255c10baf1c78 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:03:45 -0800 Subject: [PATCH 27/32] fix(function-pods): preserve schemas reconstructed from Arrow --- src/orcapod/core/function_pod.py | 23 +++++++------ .../test_narrow_float_arrow_compatibility.py | 32 +++++++++++++++++++ 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 08c4c748a..d9324301c 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -19,14 +19,12 @@ import pyarrow as pa from orcapod import contexts -from orcapod.semantic_types.narrow_float_keys import ( - require_python_schema_without_narrow_float_keys, -) from orcapod.channels import ReadableChannel, WritableChannel 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_proxy import DataFunctionProxy from orcapod.core.datagrams import Data from orcapod.core.data_tags import ( materialization_diagnostic_off, @@ -69,6 +67,9 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, @@ -150,14 +151,16 @@ def __init__( ) self._ctx_arg_name: str | None = ctx_arg_name converter = self.data_context.type_converter - require_python_schema_without_narrow_float_keys( - self.input_data_schema, converter - ) - require_python_schema_without_narrow_float_keys( - data_function.output_data_schema, converter - ) + # A proxy's types come from its saved schema. + if not isinstance(data_function, DataFunctionProxy): + require_python_schema_without_narrow_float_keys( + self.input_data_schema, converter + ) + require_python_schema_without_narrow_float_keys( + data_function.output_data_schema, converter + ) # Register types for schema validation, excluding ctx (not a data column). - self.data_context.type_converter.ensure_types_registered_for_schemas( + converter.ensure_types_registered_for_schemas( self.input_data_schema, data_function.output_data_schema, ) diff --git a/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py index b0a62c122..d801fab0e 100644 --- a/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py +++ b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py @@ -15,12 +15,15 @@ from typing_extensions import override from orcapod import contexts +from orcapod.core.data_function import PYTHON_FUNCTION +from orcapod.core.function_pod import FunctionPod from orcapod.core.sources import ArrowTableSource, DataFrameSource, PollingSource from orcapod.errors import SchemaInconsistencyError from orcapod.logical_types import make_arrow_extension_type, make_polars_extension_type from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.pipeline.serialization import arrow_type_texts from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.semantic_types import UniversalTypeConverter from orcapod.types import Cursor, PollingConfig @@ -274,3 +277,32 @@ def test_arrow_input_matches_main( observed = _source_result(case, kind, asynchronous) # Convert Arrow map tuples to JSON arrays before comparison. assert json.loads(json.dumps(observed)) == main_results[case][kind] + + +@dataclass +class _SavedPayload: + entries: dict[np.float32, int] + + +def test_proxy_keeps_its_saved_arrow_schema() -> None: + converter = contexts.resolve_context(None).type_converter + table = converter.python_dicts_to_arrow_table( + [{"payload": cast(Any, _SavedPayload({np.float32(0.5): 4}))}] + ) + pod = FunctionPod.from_config( + { + "data_function": { + "data_function_type_id": PYTHON_FUNCTION.type_id, + "uri": ["saved", "saved-schema-hash", "v1", PYTHON_FUNCTION.type_id], + "config": { + "module_path": "missing_itl1591_function", + "callable_name": "saved", + "version": "v1.0", + "input_data_schema": {}, + "output_data_schema": arrow_type_texts(table.schema), + }, + } + }, + fallback_to_proxy=True, + ) + assert pod.data_function.output_data_schema["payload"] is _SavedPayload From 754a2f1ec8dfa8a865d8988827c921c0cb006cfe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:22:08 -0800 Subject: [PATCH 28/32] docs: reference the narrow-float Arrow follow-up --- changelog.d/ITL-1591.md | 2 +- docs/dev/design_issues/ITL-1591-NFK1.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 0a8eb3b06..8e6e94450 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -9,4 +9,4 @@ ### Known limitations - Arrow input with a narrow-float dictionary key or set element is accepted as on main. - For example, `Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` returns `{0.0: 2}`. This is a follow-up issue to be filed by the coordinator. + For example, `Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` returns `{0.0: 2}`. ITL-1693 tracks the Arrow-input follow-up. diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index 6316c9fd0..be7d906ed 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -21,4 +21,4 @@ dict values remain supported. behavior. Arrow tables, declared Arrow schemas, raw streams, saved schemas and stored results can still carry these types. For example, `Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` -returns `{0.0: 2}`. Arrow input is a follow-up issue to be filed by the coordinator. +returns `{0.0: 2}`. ITL-1693 tracks the Arrow-input follow-up. From a2fbb85f47b1662173ae730d03b6c4e2998b7af8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:37:44 -0800 Subject: [PATCH 29/32] fix(schema): validate narrow float keys at declaration time --- changelog.d/ITL-1591.md | 7 +- docs/dev/design_issues/ITL-1591-NFK1.md | 4 +- src/orcapod/core/cached_function_pod.py | 10 +- src/orcapod/core/data_function.py | 30 ++- src/orcapod/core/datagrams/datagram.py | 97 +++++---- src/orcapod/core/datagrams/tag_data.py | 56 ++--- src/orcapod/core/function_pod.py | 23 +- src/orcapod/core/nodes/function_node.py | 7 +- src/orcapod/core/nodes/source_node.py | 22 +- src/orcapod/core/operators/add_tags.py | 5 +- src/orcapod/core/sources/cached_source.py | 4 +- src/orcapod/core/sources/data_frame_source.py | 6 +- src/orcapod/core/sources/dict_source.py | 15 +- src/orcapod/core/sources/list_source.py | 13 +- src/orcapod/core/sources/polling_source.py | 8 +- src/orcapod/pipeline/serialization.py | 6 +- .../semantic_types/_schema_conversion.py | 56 +++++ .../semantic_types/narrow_float_keys.py | 34 +-- .../semantic_types/universal_converter.py | 32 ++- src/orcapod/utils/arrow_utils.py | 4 +- src/orcapod/utils/schema_utils.py | 8 +- .../test_narrow_float_keys_refused.py | 204 +++++++++++++++--- 22 files changed, 468 insertions(+), 183 deletions(-) create mode 100644 src/orcapod/semantic_types/_schema_conversion.py diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index 8e6e94450..b794d49b8 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -2,9 +2,10 @@ - Python declarations of `float32` or `float16` dictionary keys or set elements raise `NarrowFloatKeyError` in function pods, Python schemas for sources and stream input - slots, and `Data` (ITL-1591). The check follows nested Python types and stored fields - of user classes. Two distinct values can narrow to one stored value and lose an entry. - Declare the key or element as `float` to retain double precision. + slots, datagrams, and explicit Python schemas passed to public converters (ITL-1591). + The check follows nested Python types and stored fields of user classes. Two distinct + values can narrow to one stored value and lose an entry. Declare the key or element + as `float` to retain double precision. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index be7d906ed..b8d034977 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -12,7 +12,9 @@ that representation can have fewer entries than the original. **Fix:** D41 selects fallback (b) for D16 and D25. At a Python declaration boundary, `semantic_types/narrow_float_keys.py` raises `NarrowFloatKeyError` for a narrow-float dict key or set element. It checks function pod inputs and outputs, source and -stream slot Python schemas, and datagrams. It follows native container annotations +stream slot Python schemas, datagrams, and explicit schemas at public converter +entry points. Row construction and conversion use the existing schema without +running declaration validation. The check follows native container annotations and stored fields of native user classes, including nested classes. A registered custom logical type owns its storage. Plain narrow-float values, list elements and dict values remain supported. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 30c1d0570..a123466a4 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -42,6 +42,8 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol +from orcapod.semantic_types._schema_conversion import arrow_schema_for_types + if TYPE_CHECKING: import pyarrow as pa @@ -116,8 +118,8 @@ def require_storable_results(self) -> None: }, **pf.output_data_schema, } - declared = self.data_context.type_converter.python_schema_to_arrow_schema( - python_schema + declared = arrow_schema_for_types( + self.data_context.type_converter, python_schema ) schema = pa.schema( [ @@ -246,11 +248,13 @@ def process_data( var_dg = Datagram( pf.get_function_variation_data(), python_schema=pf.get_function_variation_data_schema(), + _inherited_schema=True, data_context=pf.data_context, ) exec_dg = Datagram( pf.get_execution_data(), python_schema=pf.get_execution_data_schema(), + _inherited_schema=True, data_context=pf.data_context, ) # Write if missing (ITL-1503): a result stored for this input since the @@ -315,11 +319,13 @@ async def _async_compute_and_store( var_dg = Datagram( pf.get_function_variation_data(), python_schema=pf.get_function_variation_data_schema(), + _inherited_schema=True, data_context=pf.data_context, ) exec_dg = Datagram( pf.get_execution_data(), python_schema=pf.get_execution_data_schema(), + _inherited_schema=True, data_context=pf.data_context, ) # Write if missing (ITL-1503): a result stored for this input since the diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 286c6a0ea..1600bad0b 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -64,6 +64,11 @@ from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + if TYPE_CHECKING: from orcapod.logical_types.protocols import ( TypeConverterProtocol as LogicalTypeConverterProtocol, @@ -835,6 +840,8 @@ def __init__( data_context: str | DataContext | None = None, config: OrcapodConfig | None = None, executor: PythonFunctionExecutorProtocol | None = None, + *, + _ctx_arg_name: str | None = None, ) -> None: # default to the basic PythonFunctionExecutor @@ -919,6 +926,15 @@ def __init__( output_typespec=output_schema, ) + declared_inputs = { + name: annotation + for name, annotation in self._input_schema.items() + if name != _ctx_arg_name + } + require_python_schema_without_narrow_float_keys( + declared_inputs, self.data_context.type_converter, 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) @@ -1111,6 +1127,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: source_info=source_info, record_uuid=new_record_uuid, python_schema=output_schema, + _inherited_schema=True, data_context=self.data_context, ) # Validate storage eagerly, but retain compatible user-class instances. Reading @@ -1125,6 +1142,7 @@ def _build_output_data(self, values: Any) -> DataProtocol: return Data( normalized, python_schema=output_schema, + _inherited_schema=True, source_info=source_info, record_uuid=new_record_uuid, data_context=self.data_context, @@ -1168,15 +1186,17 @@ def _convert_outputs( """ converter = self.data_context.type_converter try: - return converter.python_dicts_to_arrow_table( - [output_data], python_schema=output_schema + return arrow_table_for_rows( + converter, [output_data], python_schema=output_schema ) except Exception as exc: # Find the output that fails on its own, so the error can name it. for key, value in output_data.items(): try: - _ = converter.python_dicts_to_arrow_table( - [{key: value}], python_schema={key: output_schema[key]} + _ = arrow_table_for_rows( + converter, + [{key: value}], + python_schema={key: output_schema[key]}, ) except UnstorableDatetimeError as failure: # The datetime rule says what is wrong and how to convert, @@ -1630,11 +1650,13 @@ def _build_metadata_datagrams(self) -> tuple[Datagram, Datagram]: variation_datagram = Datagram( self.get_function_variation_data(), python_schema=self.get_function_variation_data_schema(), + _inherited_schema=True, data_context=self.data_context, ) execution_datagram = Datagram( self.get_execution_data(), python_schema=self.get_execution_data_schema(), + _inherited_schema=True, data_context=self.data_context, ) return variation_datagram, execution_datagram diff --git a/src/orcapod/core/datagrams/datagram.py b/src/orcapod/core/datagrams/datagram.py index 91c4cdedc..39f8d7a50 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -38,13 +38,17 @@ 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.narrow_float_keys import ( - materializing_inferred_schema, require_python_schema_without_narrow_float_keys, ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, DataType, DataValue, Schema, SchemaLike from orcapod.utils import arrow_utils +from orcapod.semantic_types._schema_conversion import ( + arrow_schema_for_types, + arrow_table_for_rows, +) + logger = logging.getLogger(__name__) @@ -143,15 +147,26 @@ def __init__( record_uuid: uuid.UUID | None = None, data_context: str | contexts.DataContext | None = None, config: OrcapodConfig | None = None, + *, + _inherited_schema: bool = False, ) -> None: if isinstance(data, pa.RecordBatch): data = pa.Table.from_batches([data]) if isinstance(data, pa.Table): self._init_from_table(data, meta_info, data_context, record_uuid) + if python_schema is not None and not _inherited_schema: + require_python_schema_without_narrow_float_keys( + python_schema, self.converter + ) else: self._init_from_dict( - data, python_schema, meta_info, data_context, record_uuid + data, + python_schema, + meta_info, + data_context, + record_uuid, + inherited_schema=_inherited_schema, ) def _init_from_dict( @@ -161,6 +176,8 @@ def _init_from_dict( meta_info: Mapping[str, DataValue] | None, data_context: str | contexts.DataContext | None, record_uuid: uuid.UUID | None, + *, + inherited_schema: bool, ) -> None: data_columns: dict[str, DataValue] = {} meta_columns: dict[str, DataValue] = {} @@ -177,6 +194,10 @@ def _init_from_dict( super().__init__(data_context=data_context or extracted_context) self._datagram_uuid = record_uuid + if python_schema is not None and not inherited_schema: + require_python_schema_without_narrow_float_keys( + python_schema, self.converter + ) self._data_dict: dict[str, DataValue] | None = data_columns self._data_table: pa.Table | None = None @@ -192,10 +213,6 @@ def _init_from_dict( if python_schema else inferred ) - if python_schema is not None: - require_python_schema_without_narrow_float_keys( - python_schema, self.converter - ) self._data_dict = self._canonical_dict_values( data_columns, self._data_python_schema ) @@ -292,7 +309,7 @@ def _init_from_row( else f"{constants.META_PREFIX}{k}": v for k, v in meta_info.items() } - new_meta = self.converter.python_dicts_to_arrow_table([normalized_meta]) + new_meta = arrow_table_for_rows(self.converter, [normalized_meta]) if meta_table is None: meta_table = new_meta else: @@ -420,11 +437,11 @@ def _ensure_data_table(self) -> pa.Table: """ if self._data_table is None: assert self._data_dict is not None - with materializing_inferred_schema(): - self._data_table = self.converter.python_dicts_to_arrow_table( - [self._data_dict], - self._data_python_schema, - ) + self._data_table = arrow_table_for_rows( + self.converter, + [self._data_dict], + self._data_python_schema, + ) return self._data_table def _ensure_python_schema(self) -> Schema: @@ -450,8 +467,8 @@ def _ensure_arrow_schema(self) -> pa.Schema: if self._data_table is not None: self._data_arrow_schema = self._data_table.schema else: - self._data_arrow_schema = self.converter.python_schema_to_arrow_schema( - self._ensure_python_schema() + self._data_arrow_schema = arrow_schema_for_types( + self.converter, self._ensure_python_schema() ) return self._data_arrow_schema @@ -474,10 +491,9 @@ def _ensure_meta_table(self) -> pa.Table | None: if not self._meta: return None if self._meta_table is None: - with materializing_inferred_schema(): - self._meta_table = self.converter.python_dicts_to_arrow_table( - [self._meta], python_schema=self._meta_python_schema - ) + self._meta_table = arrow_table_for_rows( + self.converter, [self._meta], python_schema=self._meta_python_schema + ) return self._meta_table # ------------------------------------------------------------------ @@ -771,13 +787,13 @@ def with_meta_columns(self, **meta_updates: DataValue) -> Self: ) ) if prefixed: - with materializing_inferred_schema(): - tables.append( - self.converter.python_dicts_to_arrow_table( - [prefixed], - python_schema=Schema({k: merged[k] for k in prefixed}), - ) + tables.append( + arrow_table_for_rows( + self.converter, + [prefixed], + python_schema=Schema({k: merged[k] for k in prefixed}), ) + ) meta_names = list(new_d.meta_columns) new_d._meta_table = ( arrow_utils.hstack_tables(*tables).select(meta_names) @@ -1021,8 +1037,8 @@ def update(self, **updates: DataValue) -> Self: sub_schema = arrow_utils.schema_select( self._data_table.schema, list(updates.keys()) ) - update_table = self.converter.python_dicts_to_arrow_table( - [updates], arrow_schema=sub_schema + update_table = arrow_table_for_rows( + self.converter, [updates], arrow_schema=sub_schema ) new_d = self.copy(include_cache=False) new_d._data_table = arrow_utils.hstack_tables( @@ -1100,16 +1116,17 @@ def _new_columns_table( tables: list[pa.Table] = [] if python_schema: - with materializing_inferred_schema(): - tables.append( - self.converter.python_dicts_to_arrow_table( - [{n: updates[n] for n in python_schema}], - python_schema=python_schema, - ) + tables.append( + arrow_table_for_rows( + self.converter, + [{n: updates[n] for n in python_schema}], + python_schema=python_schema, ) + ) if arrow_fields: tables.append( - self.converter.python_dicts_to_arrow_table( + arrow_table_for_rows( + self.converter, [{n: updates[n] for n in arrow_fields}], arrow_schema=pa.schema(list(arrow_fields.values())), ) @@ -1164,15 +1181,13 @@ def with_columns( f"Use update() to modify existing columns." ) - if column_types: + if declared_python_types := { + name: declared + for name, declared in (column_types or {}).items() + if name in updates and not isinstance(declared, (pa.DataType, pa.Field)) + }: require_python_schema_without_narrow_float_keys( - { - name: declared - for name, declared in column_types.items() - if name in updates - and not isinstance(declared, (pa.DataType, pa.Field)) - }, - self.converter, + declared_python_types, self.converter ) has_arrow_types = column_types is not None and any( isinstance(t, (pa.DataType, pa.Field)) for t in column_types.values() diff --git a/src/orcapod/core/datagrams/tag_data.py b/src/orcapod/core/datagrams/tag_data.py index c5fc7d180..2b3d7f124 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -26,7 +26,6 @@ from orcapod import contexts from orcapod.core.datagrams.datagram import Datagram, context_key_field from orcapod.semantic_types import infer_python_schema_from_pylist_data -from orcapod.semantic_types.narrow_float_keys import materializing_inferred_schema from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, @@ -39,6 +38,11 @@ ) from orcapod.utils import arrow_utils +from orcapod.semantic_types._schema_conversion import ( + arrow_schema_for_types, + arrow_table_for_rows, +) + if TYPE_CHECKING: from orcapod.protocols.core_protocols import DataProtocol @@ -98,6 +102,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, @@ -159,20 +164,20 @@ def _merge_system_tag_table( for field in schema: if not field.nullable and replacements[field.name] is None: raise ValueError(f"Column {field.name!r} is declared non-nullable") - updated = self.converter.python_dicts_to_arrow_table( - [replacements], arrow_schema=schema + updated = arrow_table_for_rows( + self.converter, [replacements], arrow_schema=schema ) table = arrow_utils.hstack_tables( table.drop_columns(list(replacements)), updated ).select(table.column_names) if additions: - with materializing_inferred_schema(): - added = self.converter.python_dicts_to_arrow_table( - [additions], - python_schema=infer_python_schema_from_pylist_data( - [additions], default_type=str - ), - ) + added = arrow_table_for_rows( + self.converter, + [additions], + python_schema=infer_python_schema_from_pylist_data( + [additions], default_type=str + ), + ) table = arrow_utils.hstack_tables(table, added) return table @@ -253,13 +258,11 @@ def rows_of( def _ensure_system_tags_table(self) -> "pa.Table": if self._system_tags_table is None: - with materializing_inferred_schema(): - self._system_tags_table = ( - self._data_context.type_converter.python_dicts_to_arrow_table( - [self._system_tags], - python_schema=self._system_tags_python_schema, - ) - ) + self._system_tags_table = arrow_table_for_rows( + self._data_context.type_converter, + [self._system_tags], + python_schema=self._system_tags_python_schema, + ) return self._system_tags_table # ------------------------------------------------------------------ @@ -341,7 +344,10 @@ def as_datagram( data = self.as_dict(columns=columns, all_info=all_info) python_schema = self.schema(columns=columns, all_info=all_info) return Datagram( - data, python_schema=python_schema, data_context=self._data_context + data, + python_schema=python_schema, + data_context=self._data_context, + _inherited_schema=True, ) def copy(self, include_cache: bool = True, preserve_id: bool = False) -> Self: @@ -448,6 +454,7 @@ def __init__( data_table, si_table = self._data_and_source_info_tables(data, source_info) super().__init__( data_table, + python_schema=python_schema, meta_info=meta_info, data_context=data_context, record_uuid=record_uuid, @@ -668,16 +675,12 @@ def function_output_zero_row_table( fields = list( output_arrow_schema if output_arrow_schema is not None - else data_context.type_converter.python_schema_to_arrow_schema( - python_schema - ) + else arrow_schema_for_types(data_context.type_converter, python_schema) ) fields.append(context_key_field()) if meta_python_schema: fields.extend( - data_context.type_converter.python_schema_to_arrow_schema( - meta_python_schema - ) + arrow_schema_for_types(data_context.type_converter, meta_python_schema) ) # A data function's source-info token is always a string (see # ``PythonDataFunction``): the type is the one a string token gives. @@ -1051,7 +1054,10 @@ def as_datagram( data = self.as_dict(columns=columns, all_info=all_info) python_schema = self.schema(columns=columns, all_info=all_info) return Datagram( - data=data, python_schema=python_schema, data_context=self._data_context + data=data, + python_schema=python_schema, + data_context=self._data_context, + _inherited_schema=True, ) def with_columns_of(self, other: "DataProtocol", names: "Sequence[str]") -> Self: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index d9324301c..1c3511304 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -24,7 +24,6 @@ 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_proxy import DataFunctionProxy from orcapod.core.datagrams import Data from orcapod.core.data_tags import ( materialization_diagnostic_off, @@ -67,9 +66,6 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data -from orcapod.semantic_types.narrow_float_keys import ( - require_python_schema_without_narrow_float_keys, -) from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, @@ -92,6 +88,8 @@ RunStats, ) +from orcapod.semantic_types._schema_conversion import struct_dicts_for_rows + logger = logging.getLogger(__name__) if TYPE_CHECKING: @@ -150,17 +148,8 @@ def __init__( f"(schema keys: {list(data_function.input_data_schema.keys())})" ) self._ctx_arg_name: str | None = ctx_arg_name - converter = self.data_context.type_converter - # A proxy's types come from its saved schema. - if not isinstance(data_function, DataFunctionProxy): - require_python_schema_without_narrow_float_keys( - self.input_data_schema, converter - ) - require_python_schema_without_narrow_float_keys( - data_function.output_data_schema, converter - ) # Register types for schema validation, excluding ctx (not a data column). - converter.ensure_types_registered_for_schemas( + self.data_context.type_converter.ensure_types_registered_for_schemas( self.input_data_schema, data_function.output_data_schema, ) @@ -993,6 +982,7 @@ def from_fn( function_name=name or getattr(fn, "__name__", "unknown"), version=version, label=label, + _ctx_arg_name=ctx_arg_name, ) return cls( data_function=data_function, @@ -1701,8 +1691,8 @@ def _table_from_pairs( # typed from their values. python_schema = dict(infer_python_schema_from_pylist_data(all_data)) python_schema.update(self.output_schema()[1]) - struct_data = converter.python_dicts_to_struct_dicts( - all_data, python_schema=python_schema + struct_data = struct_dicts_for_rows( + converter, all_data, python_schema=python_schema ) all_tags_as_tables = arrow_utils.concat_tables_by_name(tag_tables) all_data_as_tables: pa.Table = pa.Table.from_pylist( @@ -1996,6 +1986,7 @@ def decorator(func: Callable) -> CallableWithPodProtocol: version=version, label=label, executor=executor, + _ctx_arg_name=ctx_arg, **kwargs, ) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index f27c84b7e..0bef2a24b 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -132,6 +132,8 @@ ) from orcapod.utils import arrow_utils, schema_utils +from orcapod.semantic_types._schema_conversion import arrow_schema_for_types + logger = logging.getLogger(__name__) PIPELINE_RUN_ID_COL = "__pipeline_run_id" @@ -830,8 +832,9 @@ def _table_from_pairs( tag_python_schema, data_python_schema = self.output_schema(all_info=True) return pa.Table.from_pylist( [], - schema=self.data_context.type_converter.python_schema_to_arrow_schema( - tag_python_schema + data_python_schema + schema=arrow_schema_for_types( + self.data_context.type_converter, + tag_python_schema + data_python_schema, ), ) try: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 27545086f..1dcae1617 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -77,18 +77,18 @@ ) if TYPE_CHECKING: - from orcapod.pipeline.job import PipelineJob - from orcapod.types.explanation import Explanation from orcapod.channels import WritableChannel + from orcapod.pipeline.job import PipelineJob from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, ) - from orcapod.protocols.observability_protocols import ExecutionObserverProtocol from orcapod.protocols.hashing_protocols import ( IdentityWalkProtocol, SemanticHasherProtocol, ) + from orcapod.protocols.observability_protocols import ExecutionObserverProtocol + from orcapod.types.explanation import Explanation logger = logging.getLogger(__name__) @@ -587,8 +587,9 @@ def __init__( data_schema = Schema(converter.arrow_schema_to_python_schema(data_schema)) elif not _inherited_types: converter = self.data_context.type_converter - require_python_schema_without_narrow_float_keys(tag_schema, converter) - require_python_schema_without_narrow_float_keys(data_schema, converter) + require_python_schema_without_narrow_float_keys( + tag_schema, converter, data_schema + ) self._name = name self._tag_schema = tag_schema self._data_schema = data_schema @@ -1685,13 +1686,12 @@ def __init__( "SourceJobNode requires either explicit tag_schema/data_schema " "or a bound_source to derive schemas from." ) - if not _inherited_types: + declared_schema = tag_schema if tag_schema is not None else data_schema + if declared_schema is not None and not _inherited_types: converter = contexts.resolve_context(data_context).type_converter - for schema in (tag_schema, data_schema): - if schema is not None: - require_python_schema_without_narrow_float_keys( - schema, converter - ) + require_python_schema_without_narrow_float_keys( + declared_schema, converter + ) derived_tag, derived_data = bound_source.output_schema() if arrow_schemas is None: # Each role's Arrow schema from where that role comes from: an omitted diff --git a/src/orcapod/core/operators/add_tags.py b/src/orcapod/core/operators/add_tags.py index 925891d76..4d49c51f8 100644 --- a/src/orcapod/core/operators/add_tags.py +++ b/src/orcapod/core/operators/add_tags.py @@ -22,6 +22,8 @@ from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import schema_utils +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + if TYPE_CHECKING: from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol @@ -224,7 +226,8 @@ def _constants(self, converter: TypeConverterProtocol, num_rows: int) -> pa.Tabl """ cached = self._one_row.get(id(converter)) if cached is None or cached[0] is not converter: - one_row = converter.python_dicts_to_arrow_table( + one_row = arrow_table_for_rows( + converter, [dict(self._tags)], python_schema={name: type(value) for name, value in self._tags.items()}, ) diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 5c00d1641..97d79cec3 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -60,6 +60,8 @@ from orcapod.types import ColumnConfig, Schema from orcapod.utils import schema_utils +from orcapod.semantic_types._schema_conversion import arrow_schema_for_types + if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.database_protocols import DatabaseRegistryProtocol @@ -752,7 +754,7 @@ def _empty_table(self) -> pa.Table: merged = dict(tag_schema) merged.update(data_schema) type_converter = self.data_context.type_converter - arrow_schema = type_converter.python_schema_to_arrow_schema(merged) + arrow_schema = arrow_schema_for_types(type_converter, merged) require_supported_nullable_types(arrow_schema) return pa.Table.from_pylist([], schema=arrow_schema) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index a435b32fb..5249488e0 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -22,6 +22,8 @@ from orcapod.utils import arrow_utils, polars_data_utils from orcapod.utils.schema_utils import _normalize_column_list +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + if TYPE_CHECKING: from polars._typing import ( ArrowArrayExportable, @@ -114,8 +116,8 @@ def __init__( logger.info( f"Converting {len(object_columns)} object column(s) to Arrow format" ) - sub_table = self.data_context.type_converter.python_dicts_to_arrow_table( - df.select(object_columns).to_dicts() + sub_table = arrow_table_for_rows( + self.data_context.type_converter, df.select(object_columns).to_dicts() ) df = df.with_columns([pl.from_arrow(c) for c in sub_table]) diff --git a/src/orcapod/core/sources/dict_source.py b/src/orcapod/core/sources/dict_source.py index 26eefb169..69506c1ea 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -22,6 +22,11 @@ from orcapod.utils.schema_utils import _normalize_column_list from orcapod.utils.tensor_conversions import warn_source_tensor_conversions +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + class DictSource(RootSource): """A source backed by a collection of Python dictionaries. @@ -64,6 +69,10 @@ def __init__( **kwargs: Any, ) -> None: super().__init__(source_id=source_id, **kwargs) + if not isinstance(data_schema, pa.Schema) and data_schema is not None: + require_python_schema_without_narrow_float_keys( + data_schema, self.data_context.type_converter + ) tag_columns = _normalize_column_list(tag_columns) # Read the first input row before its origin is erased by dict(row). @@ -87,12 +96,14 @@ def __init__( # pa.Schema directly via data_schema; route to the converter accordingly. if isinstance(data_schema, pa.Schema): require_supported_nullable_types(data_schema) - arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( + arrow_table = arrow_table_for_rows( + self.data_context.type_converter, rows, arrow_schema=data_schema, ) else: - arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( + arrow_table = arrow_table_for_rows( + self.data_context.type_converter, rows, python_schema=data_schema, ) diff --git a/src/orcapod/core/sources/list_source.py b/src/orcapod/core/sources/list_source.py index 1433cbc71..8e00aa704 100644 --- a/src/orcapod/core/sources/list_source.py +++ b/src/orcapod/core/sources/list_source.py @@ -19,6 +19,11 @@ from orcapod.utils import arrow_utils from orcapod.utils.tensor_conversions import warn_source_tensor_conversions +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + if TYPE_CHECKING: pass @@ -84,6 +89,10 @@ def __init__( **kwargs: Passed on to ``RootSource``. """ super().__init__(source_id=source_id, **kwargs) + if data_schema is not None: + require_python_schema_without_narrow_float_keys( + data_schema, self.data_context.type_converter + ) self.name = name self._elements = list(data) @@ -136,8 +145,8 @@ def __init__( warn_first_python_float( rows[0], float32_columns, first_tag, python_column=name ) - arrow_table = self.data_context.type_converter.python_dicts_to_arrow_table( - rows, python_schema=data_schema + arrow_table = arrow_table_for_rows( + self.data_context.type_converter, rows, python_schema=data_schema ) if data_schema is None: # Canonical pattern for Python-origin sources: the type converter diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index b44ab1840..74e39a3d6 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -60,12 +60,14 @@ declared_arrow_schema, ) +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + if TYPE_CHECKING: - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types import Schema T = TypeVar("T") @@ -928,8 +930,8 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: # Handle Object-dtype columns (same pattern as DataFrameSource) object_columns = [c for c in df.columns if df[c].dtype == pl.Object] if object_columns: - sub_table = self.data_context.type_converter.python_dicts_to_arrow_table( - df.select(object_columns).to_dicts() + sub_table = arrow_table_for_rows( + self.data_context.type_converter, df.select(object_columns).to_dicts() ) df = df.with_columns([pl.from_arrow(c) for c in sub_table]) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index f58b4638e..eaa877be4 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -24,6 +24,8 @@ require_readable, ) +from orcapod.semantic_types._schema_conversion import arrow_schema_for_types + if TYPE_CHECKING: import pyarrow as pa @@ -1050,9 +1052,7 @@ def nullable_column_names(schema: Any, type_converter: Any) -> list[str]: names: list[str] = [] for name, python_type in schema.items(): try: - arrow_schema = type_converter.python_schema_to_arrow_schema( - {name: python_type} - ) + arrow_schema = arrow_schema_for_types(type_converter, {name: python_type}) except Exception: continue if arrow_schema.field(name).nullable: diff --git a/src/orcapod/semantic_types/_schema_conversion.py b/src/orcapod/semantic_types/_schema_conversion.py new file mode 100644 index 000000000..b2b3609d0 --- /dev/null +++ b/src/orcapod/semantic_types/_schema_conversion.py @@ -0,0 +1,56 @@ +"""Convert schemas already obtained from a declaration, Arrow, or inference.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable + + import pyarrow as pa + + from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol + from orcapod.types import SchemaLike + + +def arrow_schema_for_types( + converter: TypeConverterProtocol, schema: SchemaLike +) -> pa.Schema: + """Convert existing Python types to Arrow fields.""" + convert: Callable[[SchemaLike], pa.Schema] = getattr( + converter, + "_python_schema_to_arrow_schema", + converter.python_schema_to_arrow_schema, + ) + return convert(schema) + + +def struct_dicts_for_rows( + converter: TypeConverterProtocol, + rows: list[dict[str, Any]], + python_schema: SchemaLike | None = None, +) -> list[dict[str, Any]]: + """Convert rows under an existing or inferred schema.""" + convert: Callable[ + [list[dict[str, Any]], SchemaLike | None], list[dict[str, Any]] + ] = getattr( + converter, + "_python_dicts_to_struct_dicts", + converter.python_dicts_to_struct_dicts, + ) + return convert(rows, python_schema) + + +def arrow_table_for_rows( + converter: TypeConverterProtocol, + rows: list[dict[str, Any]], + python_schema: SchemaLike | None = None, + arrow_schema: pa.Schema | None = None, +) -> pa.Table: + """Materialize rows under an existing or inferred schema.""" + convert: Callable[ + [list[dict[str, Any]], SchemaLike | None, pa.Schema | None], pa.Table + ] = getattr( + converter, "_python_dicts_to_arrow_table", converter.python_dicts_to_arrow_table + ) + return convert(rows, python_schema, arrow_schema) diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 562767a2a..3929f7195 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -3,8 +3,6 @@ from __future__ import annotations from collections.abc import Iterable, Iterator -from contextlib import contextmanager -from contextvars import ContextVar from types import UnionType from typing import ( TYPE_CHECKING, @@ -32,9 +30,6 @@ "Two distinct values can narrow to the same stored value and lose an entry. " "Declare the key or element as float, an integer, or a string." ) -_materializing_inferred_schema = ContextVar( - "materializing_inferred_schema", default=False -) class NarrowFloatKeyError(InputValidationError, ValueError): @@ -47,16 +42,6 @@ class _LogicalTypeLookup(Protocol): def get_logical_type(self, python_type: type) -> LogicalTypeProtocol | None: ... -@contextmanager -def materializing_inferred_schema() -> Iterator[None]: - """Keep internal row conversion from treating inferred types as declarations.""" - token = _materializing_inferred_schema.set(True) - try: - yield - finally: - _materializing_inferred_schema.reset(token) - - def _float_width(annotation: object) -> str | None: origin = get_origin(annotation) args = get_args(annotation) @@ -119,14 +104,13 @@ def _violations( def require_python_schema_without_narrow_float_keys( - schema: SchemaLike, converter: _LogicalTypeLookup + schema: SchemaLike, converter: _LogicalTypeLookup, *other_schemas: SchemaLike ) -> None: - """Check declared Python columns without converting values or Arrow types.""" - if _materializing_inferred_schema.get(): - return - for name, annotation in schema.items(): - if found := sorted(set(_violations(annotation, converter))): - error = NarrowFloatKeyError( - f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {', '.join(found)}. {_REMEDY}" - ) - raise with_context(f"Column {name!r} ({annotation})", error) + """Check the Python schemas of one declaration.""" + for declared_schema in (schema, *other_schemas): + for name, annotation in declared_schema.items(): + if found := sorted(set(_violations(annotation, converter))): + error = NarrowFloatKeyError( + f"{NARROW_FLOAT_KEYS_NOT_SUPPORTED}: {', '.join(found)}. {_REMEDY}" + ) + raise with_context(f"Column {name!r} ({annotation})", error) diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 9bf0a0465..2f8dcdc5e 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -56,11 +56,11 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: - from orcapod.logical_types.registry import LogicalTypeRegistry from orcapod.logical_types.protocols import ( LogicalTypeFactoryProtocol, LogicalTypeProtocol, ) + from orcapod.logical_types.registry import LogicalTypeRegistry logger = logging.getLogger(__name__) @@ -1081,6 +1081,11 @@ def python_schema_to_arrow_schema(self, python_schema: SchemaLike) -> pa.Schema: (Optional[T]) maps to ``nullable=True``; plain ``T`` maps to ``nullable=False``. This uses caches for type conversion. """ + require_python_schema_without_narrow_float_keys(python_schema, self) + return self._python_schema_to_arrow_schema(python_schema) + + def _python_schema_to_arrow_schema(self, python_schema: SchemaLike) -> pa.Schema: + """Convert types already known to the caller.""" fields = [] for field_name, python_type in python_schema.items(): try: @@ -1281,6 +1286,16 @@ def python_dicts_to_struct_dicts( This uses the main conversion logic and caches results for performance. """ + if python_schema is not None: + require_python_schema_without_narrow_float_keys(python_schema, self) + return self._python_dicts_to_struct_dicts(python_dicts, python_schema) + + def _python_dicts_to_struct_dicts( + self, + python_dicts: list[dict[str, Any]], + python_schema: SchemaLike | None = None, + ) -> list[dict[str, Any]]: + """Convert rows under an existing or inferred schema.""" if python_schema is None: python_schema = infer_python_schema_from_pylist_data(python_dicts) @@ -1375,6 +1390,17 @@ def python_dicts_to_arrow_table( """ if python_schema is not None: require_python_schema_without_narrow_float_keys(python_schema, self) + return self._python_dicts_to_arrow_table( + python_dicts, python_schema, arrow_schema + ) + + def _python_dicts_to_arrow_table( + self, + python_dicts: list[dict[str, Any]], + python_schema: SchemaLike | None = None, + arrow_schema: pa.Schema | None = None, + ) -> pa.Table: + """Materialize rows under an existing or inferred schema.""" if python_schema is not None and arrow_schema is not None: logger.warning( "Both Python and Arrow schemas are provided. If they are not compatible, this may lead to unexpected behavior." @@ -1392,7 +1418,7 @@ def python_dicts_to_arrow_table( # a no-op for primitives and already-registered types. assert python_schema is not None, "Python schema should not be None here" self.ensure_types_registered_for_schemas(python_schema) - arrow_schema = self.python_schema_to_arrow_schema(python_schema) + arrow_schema = self._python_schema_to_arrow_schema(python_schema) if python_schema is None: assert arrow_schema is not None, ( @@ -1400,7 +1426,7 @@ def python_dicts_to_arrow_table( ) python_schema = self.arrow_schema_to_python_schema(arrow_schema) - struct_dicts = self.python_dicts_to_struct_dicts( + struct_dicts = self._python_dicts_to_struct_dicts( python_dicts, python_schema=python_schema ) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c69d5ccdb..3f2b56572 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -33,7 +33,9 @@ def make_empty_table( Returns: A zero-row ``pa.Table`` with the correct Arrow schema. """ - arrow_schema = type_converter.python_schema_to_arrow_schema(python_schema) + from orcapod.semantic_types._schema_conversion import arrow_schema_for_types + + arrow_schema = arrow_schema_for_types(type_converter, python_schema) return pa.Table.from_batches([], schema=arrow_schema) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index d9d70fba5..222d03de9 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -13,6 +13,8 @@ from orcapod.types import ContentHash, Schema, SchemaLike from orcapod.utils.output_containers import EXCLUDED_OUTPUT_CONTAINERS +from orcapod.semantic_types._schema_conversion import arrow_schema_for_types + logger = logging.getLogger(__name__) TokenShapeViolation = tuple[str, str, pa.DataType, pa.DataType, int | None] @@ -622,7 +624,7 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register TypeError, ValueError: If a field has no Arrow type even after registration. """ try: - return converter.python_schema_to_arrow_schema(schema) + return arrow_schema_for_types(converter, schema) except (TypeError, ValueError): pass optional = getattr(schema, "optional_fields", frozenset()) @@ -632,10 +634,10 @@ class a factory covers (a dataclass, a pydantic model) that nothing has register {name: python_type}, optional_fields=[name] if name in optional else None ) try: - converted = converter.python_schema_to_arrow_schema(single) + converted = arrow_schema_for_types(converter, single) except (TypeError, ValueError): converter.ensure_types_registered_for_schemas(single) - converted = converter.python_schema_to_arrow_schema(single) + converted = arrow_schema_for_types(converter, single) fields.append(converted.field(name)) return pa.schema(fields) diff --git a/tests/test_semantic_types/test_narrow_float_keys_refused.py b/tests/test_semantic_types/test_narrow_float_keys_refused.py index 9b18ec74f..e6c76103b 100644 --- a/tests/test_semantic_types/test_narrow_float_keys_refused.py +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -11,37 +11,24 @@ import pytest from orcapod import contexts, function_pod +from orcapod.core.data_function import PythonDataFunction from orcapod.core.datagrams import Data, Datagram, Tag from orcapod.core.nodes import SourceJobNode, SourceNode -from orcapod.core.sources import DictSource, ListSource, PollingSource +from orcapod.core.sources import ArrowTableSource, DictSource, ListSource, PollingSource from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol +from orcapod.semantic_types.precomputed_converters import SemanticSchemaConverter +from orcapod.semantic_types import UniversalTypeConverter from orcapod.semantic_types.narrow_float_keys import ( NARROW_FLOAT_KEYS_NOT_SUPPORTED as NOT_SUPPORTED, +) +from orcapod.semantic_types.narrow_float_keys import ( NarrowFloatKeyError, ) -from orcapod.types import Schema +from orcapod.types import DataValue, Schema D = dict[np.float32, int] S = set[np.float32] -# Declared Python types that hold a float32 key or element, with a value of each. -PYTHON_TYPES: list[tuple[str, Any, Any]] = [ - ("dict", D, {np.float32(0.5): 1}), - ("set", S, {np.float32(0.5)}), - ("optional_dict", D | None, None), - ("optional_set", S | None, None), - ("dict_in_a_list", list[D], [{np.float32(0.5): 1}]), - ("set_in_a_list", list[S], [{np.float32(0.5)}]), - ("dict_as_a_dict_value", dict[str, D], {"a": {np.float32(0.5): 1}}), - ("optional_key", dict[np.float32 | None, int], {np.float32(0.5): 1}), - ("half_dict", dict[np.float16, int], {np.float16(0.5): 1}), - ("half_set", set[np.float16], {np.float16(0.5)}), -] -PYTHON_CASES = [ - pytest.param(python_type, value, id=name) - for name, python_type, value in PYTHON_TYPES -] - # Declared Python types that must keep working, with a value of each. ACCEPTED_PYTHON: dict[str, tuple[Any, Any]] = { "plain": (np.float32, np.float32(0.5)), @@ -64,6 +51,41 @@ class Nested: inner: HoldsNarrowKey +@dataclasses.dataclass +class HoldsHalfKey: + entries: list[dict[np.float16, int]] + + +@dataclasses.dataclass +class NestedHalf: + inner: HoldsHalfKey + + +# Declared Python types that hold a float32 key or element, with a value of each. +PYTHON_TYPES: list[tuple[str, Any, Any]] = [ + ("dict", D, {np.float32(0.5): 1}), + ("set", S, {np.float32(0.5)}), + ("optional_dict", D | None, None), + ("optional_set", S | None, None), + ("dict_in_a_list", list[D], [{np.float32(0.5): 1}]), + ("set_in_a_list", list[S], [{np.float32(0.5)}]), + ("dict_as_a_dict_value", dict[str, D], {"a": {np.float32(0.5): 1}}), + ("optional_key", dict[np.float32 | None, int], {np.float32(0.5): 1}), + ("half_dict", dict[np.float16, int], {np.float16(0.5): 1}), + ("half_set", set[np.float16], {np.float16(0.5)}), + ("nested_class", list[Nested | None], [Nested(HoldsNarrowKey({}))]), + ("nested_half_class", list[NestedHalf | None], [NestedHalf(HoldsHalfKey([]))]), + ("optional_half_dict", dict[np.float16, int] | None, None), + ("optional_half_set", set[np.float16] | None, None), + ("half_dict_in_a_list", list[dict[np.float16, int]], []), + ("half_set_in_a_list", list[set[np.float16]], []), +] +PYTHON_CASES = [ + pytest.param(python_type, value, id=name) + for name, python_type, value in PYTHON_TYPES +] + + class TestPythonDeclarations: """A type declared in Python is refused when it is declared.""" @@ -110,9 +132,10 @@ def test_a_tuple_field_is_refused(self, declared: Any) -> None: with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): Datagram({"k": ({}, {}), "x": 1}, python_schema={"k": declared, "x": int}) - def test_a_list_source_refuses_it(self) -> None: + @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) + def test_a_list_source_refuses_it(self, python_type: Any, value: Any) -> None: with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): - ListSource("k", [{np.float32(0.5): 1}], data_schema={"k": D}) + ListSource("k", [value], data_schema={"k": python_type}) def test_a_nested_user_class_field_is_refused(self) -> None: with pytest.raises( @@ -125,9 +148,7 @@ def test_a_nested_user_class_field_is_refused(self) -> None: ) @pytest.mark.parametrize( - "declared", - [D, S, list[S], dict[str, D], Nested, set[np.float16], dict[np.float16, int]], - ids=str, + "declared", [pytest.param(t, id=name) for name, t, _ in PYTHON_TYPES] ) @pytest.mark.parametrize("asynchronous", [False, True]) def test_a_function_pod_refuses_a_declared_output_when_defined( @@ -146,7 +167,9 @@ def produce(x: int) -> Any: with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): function_pod(output_keys="o")(produce) - @pytest.mark.parametrize("declared", [D, S, list[S], dict[str, D]], ids=str) + @pytest.mark.parametrize( + "declared", [pytest.param(t, id=name) for name, t, _ in PYTHON_TYPES] + ) def test_a_function_pod_refuses_a_declared_input_when_defined( self, declared: Any ) -> None: @@ -248,18 +271,24 @@ def test_undeclared_float32_dict_and_set_are_accepted( converter.python_dicts_to_arrow_table(rows, python_schema={"k": annotation}) -def test_polling_source_refuses_python_schema_without_fetching() -> None: +@pytest.mark.parametrize( + "declared", [pytest.param(t, id=name) for name, t, _ in PYTHON_TYPES] +) +def test_polling_source_refuses_python_schema_without_fetching(declared: Any) -> None: impl = Mock(spec=DynamicSourceProtocol) - impl.schema.return_value = {"id": int, "k": set[np.float16]} + impl.schema.return_value = {"id": int, "k": declared} with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): PollingSource(impl, "id", source_id="poll", record_id_columns="id") impl.fetch.assert_not_called() -def test_source_slot_checks_explicit_python_declaration_even_with_arrow_override() -> ( - None -): - data = Schema({"k": dict[np.float32, int]}) +@pytest.mark.parametrize( + "declared", [pytest.param(t, id=name) for name, t, _ in PYTHON_TYPES] +) +def test_source_slot_checks_explicit_python_declaration_even_with_arrow_override( + declared: Any, +) -> None: + data = Schema({"k": declared}) with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): SourceNode("input", Schema({}), data) source = DictSource([{"id": 1, "k": {"a": 1}}], tag_columns="id") @@ -277,3 +306,114 @@ def test_datagram_checks_new_python_declaration_next_to_an_arrow_declaration() - Data({"id": 1}).with_columns( {"k": dict[np.float32, int], "v": pa.int64()}, k={}, v=1 ) + + +@pytest.mark.parametrize("kind", [Tag, Data]) +@pytest.mark.parametrize("arrow_backed", [False, True]) +def test_as_datagram_preserves_undeclared_user_class_fields( + kind: type[Tag] | type[Data], arrow_backed: bool +) -> None: + context = contexts.create_registry().get_context("v1") + values: dict[str, DataValue] = { + "k": cast(Any, HoldsNarrowKey({np.float32(0.5): 4})) + } + table = context.type_converter.python_dicts_to_arrow_table([values]) + row = kind(table if arrow_backed else values, data_context=context) + datagram = row.as_datagram() + assert datagram.as_dict() == values + assert datagram.as_table().equals(table) + + +@pytest.mark.parametrize("role", ["tag", "data"]) +@pytest.mark.parametrize("arrow_backed", [False, True]) +def test_as_datagram_of_undeclared_source_row(role: str, arrow_backed: bool) -> None: + values: dict[str, DataValue] = { + "id": 1, + "k": cast(Any, HoldsNarrowKey({np.float32(0.5): 4})), + } + tag_column = "k" if role == "tag" else "id" + if arrow_backed: + converter = contexts.resolve_context(None).type_converter + table = converter.python_dicts_to_arrow_table([values]) + source = ArrowTableSource(table, tag_column, tag_only_columns=True) + else: + source = DictSource([values], tag_column, tag_only_columns=True) + tag, data = next(source.iter_data()) + row = cast(Tag, tag) if role == "tag" else cast(Data, data) + assert row.as_datagram().as_dict() == {"k": values["k"]} + + +@pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) +def test_converter_schema_and_struct_routes_check_declarations( + python_type: Any, value: Any +) -> None: + converter = contexts.resolve_context(None).type_converter + schema = {"k": python_type} + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + converter.python_schema_to_arrow_schema(schema) + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + converter.python_dicts_to_struct_dicts([{"k": value}], python_schema=schema) + assert isinstance(converter, UniversalTypeConverter) + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + SemanticSchemaConverter(converter, python_schema=schema) + + +@pytest.mark.parametrize( + "declared", [pytest.param(t, id=name) for name, t, _ in PYTHON_TYPES] +) +@pytest.mark.parametrize("direction", ["input", "output"]) +def test_data_function_refuses_an_explicit_schema( + declared: Any, direction: str +) -> None: + def echo(x: int) -> int: + return x + + input_schema = {"x": declared} if direction == "input" else None + output_schema = {"k": declared} if direction == "output" else None + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + PythonDataFunction( + echo, + output_keys="k", + input_schema=input_schema, + output_schema=output_schema, + ) + + +def test_validator_runs_once_for_a_pod_definition_and_never_for_its_rows() -> None: + import sys + + from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, + ) + + calls = 0 + + def profile(frame: Any, event: str, arg: Any) -> None: + nonlocal calls + if ( + event == "call" + and frame.f_code is require_python_schema_without_narrow_float_keys.__code__ + ): + calls += 1 + + source = DictSource([{"x": i} for i in range(10_000)]) + original_profile = sys.getprofile() + sys.setprofile(profile) + try: + + @function_pod(output_keys="k") + def echo(x: int) -> dict[str, np.float32]: + return {"x": np.float32(x)} + + definition_calls = calls + count = 0 + for tag, data in echo.pod(source).iter_data(): + # Force row conversion and derived-schema materialization. + assert cast(Tag, tag).as_datagram().as_dict() == tag.as_dict() + assert cast(Data, data).as_datagram().as_table().num_rows == 1 + count += 1 + finally: + sys.setprofile(original_profile) + + assert count == 10_000 + assert (definition_calls, calls - definition_calls) == (1, 0) From ea8ba171e3a0bfbf66ea6a5b19b7657e782fc6e1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:43:58 -0800 Subject: [PATCH 30/32] fix(schema): honor custom factories in narrow float validation --- docs/dev/design_issues/ITL-1591-NFK1.md | 7 +- .../semantic_types/narrow_float_keys.py | 58 +++++++++- .../semantic_types/universal_converter.py | 12 +- .../test_narrow_float_custom_storage.py | 107 ++++++++++++++++++ 4 files changed, 171 insertions(+), 13 deletions(-) create mode 100644 tests/test_semantic_types/test_narrow_float_custom_storage.py diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index b8d034977..f6b254d70 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -15,9 +15,10 @@ dict key or set element. It checks function pod inputs and outputs, source and stream slot Python schemas, datagrams, and explicit schemas at public converter entry points. Row construction and conversion use the existing schema without running declaration validation. The check follows native container annotations -and stored fields of native user classes, including nested classes. A registered -custom logical type owns its storage. Plain narrow-float values, list elements and -dict values remain supported. +and stored fields of native user classes, including nested classes. It uses the +converter's write-side factory selection to identify the storage owner before a +codec is built. A custom registration owns its storage from its first declaration. +Plain narrow-float values, list elements and dict values remain supported. **Known limitations:** Schema-free Python inference and Arrow input retain main's behavior. Arrow tables, declared Arrow schemas, raw streams, saved schemas and diff --git a/src/orcapod/semantic_types/narrow_float_keys.py b/src/orcapod/semantic_types/narrow_float_keys.py index 3929f7195..3df89db8f 100644 --- a/src/orcapod/semantic_types/narrow_float_keys.py +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -12,6 +12,7 @@ Union, get_args, get_origin, + runtime_checkable, ) import numpy as np @@ -21,7 +22,10 @@ from orcapod.types import SchemaLike if TYPE_CHECKING: - from orcapod.logical_types.protocols import LogicalTypeProtocol + from orcapod.logical_types.protocols import ( + LogicalTypeFactoryProtocol, + LogicalTypeProtocol, + ) NARROW_FLOAT_KEYS_NOT_SUPPORTED = ( "float32 and float16 are not supported as a dict key type or a set element type" @@ -37,10 +41,23 @@ class NarrowFloatKeyError(InputValidationError, ValueError): class _LogicalTypeLookup(Protocol): - """Read Python registrations without creating new ones.""" + """Look up the logical type for a Python class.""" def get_logical_type(self, python_type: type) -> LogicalTypeProtocol | None: ... + def get_logical_type_for_python_type( + self, annotation: type + ) -> LogicalTypeProtocol | None: ... + + +@runtime_checkable +class _FactoryLookup(Protocol): + """Select a factory without constructing the class codec.""" + + def get_logical_type_factory_for_python_class( + self, python_type: type + ) -> LogicalTypeFactoryProtocol | None: ... + def _float_width(annotation: object) -> str | None: origin = get_origin(annotation) @@ -67,12 +84,43 @@ def _class_fields( ) -> Iterable[tuple[str, object]]: """Read stored annotations of native user classes. Custom codecs own their types.""" from orcapod.logical_types import user_class_identity - from orcapod.logical_types.user_class_logical_type import UserClassLogicalType + from orcapod.logical_types.dataclass_logical_type_factory import ( + DataclassLogicalType, + DataclassLogicalTypeFactory, + ) + from orcapod.logical_types.pydantic_logical_type_factory import ( + PydanticLogicalType, + PydanticLogicalTypeFactory, + ) + from orcapod.logical_types.structural_logical_type_factory import ( + StructuralLogicalType, + StructuralLogicalTypeFactory, + ) if user_class_identity.class_kind(cls) is None: return - registered = converter.get_logical_type(cls) - if registered is not None and not isinstance(registered, UserClassLogicalType): + try: + owner: LogicalTypeProtocol | LogicalTypeFactoryProtocol | None = ( + converter.get_logical_type(cls) + ) + if owner is None: + if isinstance(converter, _FactoryLookup): + # A native factory may fail to build a codec for an unsupported + # field (such as float16). Dispatch still identifies its owner. + owner = converter.get_logical_type_factory_for_python_class(cls) + else: + owner = converter.get_logical_type_for_python_type(cls) + except (ImportError, TypeError, ValueError): + # Leave resolution errors to the converter at the point that needs the type. + return + if type(owner) not in ( + DataclassLogicalType, + PydanticLogicalType, + StructuralLogicalType, + DataclassLogicalTypeFactory, + PydanticLogicalTypeFactory, + StructuralLogicalTypeFactory, + ): return try: hints = user_class_identity.type_hints(cls) diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 2f8dcdc5e..22fcc4b56 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -544,7 +544,7 @@ def _register_python_class_impl( ) # Factory dispatch via MRO walk - factory = self._find_factory_for_class(annotation) + factory = self.get_logical_type_factory_for_python_class(annotation) if factory is None: raise TypeError( f"No LogicalType or LogicalTypeFactory registered for {annotation!r}. " @@ -638,14 +638,14 @@ def _make_or_get_arrow_element_set_type( existing = lt return existing.get_arrow_extension_type() - def _find_factory_for_class( + def get_logical_type_factory_for_python_class( self, python_type: type, ) -> "LogicalTypeFactoryProtocol | None": - """Find the most-specific registered factory for ``python_type``. + """Find the write-side factory for ``python_type`` without building its codec. - Walks ``python_type.__mro__`` and returns the first factory in - ``_python_class_factories`` whose ``supports_class(python_type)`` returns True. + Used when there is no registered logical type for the class. Walks the + class MRO and uses the first factory that supports the class. Falls back to an ``issubclass`` scan for ABC-registered factories. Args: @@ -654,6 +654,8 @@ def _find_factory_for_class( Returns: The matching ``LogicalTypeFactoryProtocol``, or ``None`` if none found. """ + if self._logical_type_registry is None: + return None factories = self._logical_type_registry._python_class_factories # MRO walk — most-specific base first diff --git a/tests/test_semantic_types/test_narrow_float_custom_storage.py b/tests/test_semantic_types/test_narrow_float_custom_storage.py new file mode 100644 index 000000000..324df940d --- /dev/null +++ b/tests/test_semantic_types/test_narrow_float_custom_storage.py @@ -0,0 +1,107 @@ +"""Custom codecs own the storage of their Python classes (ITL-1591).""" + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, cast + +import numpy as np +import pyarrow as pa +import pytest +from typing_extensions import override + +from orcapod import contexts +from orcapod.logical_types import make_arrow_extension_type, make_polars_extension_type +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.logical_types.protocols import TypeConverterProtocol +from orcapod.semantic_types import UniversalTypeConverter +from orcapod.sources import DictSource + + +@dataclass(frozen=True) +class Payload: + entries: dict[np.float32, int] + + +_STORAGE = pa.large_list(pa.struct([("key", pa.float64()), ("value", pa.int64())])) + + +class PayloadCodec(BaseLogicalType): + logical_type_name = "test.itl1591.payload" + python_type = Payload + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + factory = make_arrow_extension_type(self.logical_type_name, _STORAGE) + return cast("Callable[[], pa.ExtensionType]", factory)() + + def get_polars_extension_type(self) -> Any: + factory = make_polars_extension_type(self.logical_type_name, _STORAGE) + return cast("Callable[[], Any]", factory)() + + def python_to_storage( + self, value: Payload, converter: TypeConverterProtocol | None + ) -> list[dict[str, float | int]]: + return [ + {"key": float(key), "value": item} + for key, item in sorted(value.entries.items()) + ] + + def storage_to_python( + self, + storage_value: list[dict[str, float | int]], + converter: TypeConverterProtocol | None, + ) -> Payload: + return Payload( + {np.float32(pair["key"]): int(pair["value"]) for pair in storage_value} + ) + + +class PayloadFactory: + def supports_class(self, python_type: type) -> bool: + return python_type is Payload + + def create_for_python_type( + self, python_type: type, converter: TypeConverterProtocol + ) -> PayloadCodec: + assert self.supports_class(python_type) + return PayloadCodec() + + def reconstruct_from_arrow( + self, + arrow_extension_name: str, + storage_type: pa.DataType, + metadata: dict[str, Any], + converter: TypeConverterProtocol, + ) -> PayloadCodec: + return PayloadCodec() + + +@pytest.mark.parametrize("route", ["converter", "source"]) +def test_first_python_declaration_respects_custom_factory(route: str) -> None: + context = contexts.create_registry().get_context("v1") + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type_factory(PayloadFactory(), python_bases=(Payload,)) + assert converter.get_logical_type(Payload) is None + + payload = Payload({np.float32(0.5): 4, np.float32(1.25): 7}) + rows: list[dict[str, Any]] = [{"id": 1, "payload": payload}] + schema = {"id": int, "payload": Payload} + if route == "converter": + table = converter.python_dicts_to_arrow_table(rows, python_schema=schema) + else: + table = ( + DictSource( + rows, + "id", + data_schema=schema, + tag_only_columns=True, + data_context=context, + ) + .as_table() + .select(["id", "payload"]) + ) + arrow_type = table.schema.field("payload").type + assert isinstance(arrow_type, pa.ExtensionType) + assert arrow_type.storage_type == _STORAGE + assert converter.arrow_table_to_python_dicts(table) == rows From 346e6b379444cbc15f84cbaae7faa82c6cac9ebb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 01:14:23 -0800 Subject: [PATCH 31/32] fix(function-pod): use the supplied context for schema validation --- changelog.d/ITL-1591.md | 6 ++++-- docs/dev/design_issues/ITL-1591-NFK1.md | 5 +++-- src/orcapod/core/function_pod.py | 1 + .../test_narrow_float_custom_storage.py | 19 +++++++++++++++++++ 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/changelog.d/ITL-1591.md b/changelog.d/ITL-1591.md index b794d49b8..d0f798265 100644 --- a/changelog.d/ITL-1591.md +++ b/changelog.d/ITL-1591.md @@ -9,5 +9,7 @@ ### Known limitations -- Arrow input with a narrow-float dictionary key or set element is accepted as on main. - For example, `Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` returns `{0.0: 2}`. ITL-1693 tracks the Arrow-input follow-up. +- Arrow input retains the behavior on main. A declared Arrow field with float32 dict + keys can still narrow `1e-50` and `2e-50` to the same stored key, `0.0`. + Reading that column as a dict raises `RepeatedDictKeyError` (ITL-907). + ITL-1693 tracks the Arrow-input follow-up. diff --git a/docs/dev/design_issues/ITL-1591-NFK1.md b/docs/dev/design_issues/ITL-1591-NFK1.md index f6b254d70..232ba4bf8 100644 --- a/docs/dev/design_issues/ITL-1591-NFK1.md +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -23,5 +23,6 @@ Plain narrow-float values, list elements and dict values remain supported. **Known limitations:** Schema-free Python inference and Arrow input retain main's behavior. Arrow tables, declared Arrow schemas, raw streams, saved schemas and stored results can still carry these types. For example, -`Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2}).as_dict()["k"]` -returns `{0.0: 2}`. ITL-1693 tracks the Arrow-input follow-up. +`Data({"id": 1}).with_columns({"k": pa.large_list(pa.struct([("key", pa.float32()), ("value", pa.int64())]))}, k={1e-50: 1, 2e-50: 2})` +stores two keys of `0.0` in Arrow. Reading that column with `as_dict()` raises +`RepeatedDictKeyError` (ITL-907). ITL-1693 tracks the Arrow-input follow-up. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 1c3511304..92182eb44 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -982,6 +982,7 @@ def from_fn( function_name=name or getattr(fn, "__name__", "unknown"), version=version, label=label, + data_context=kwargs.get("data_context"), _ctx_arg_name=ctx_arg_name, ) return cls( diff --git a/tests/test_semantic_types/test_narrow_float_custom_storage.py b/tests/test_semantic_types/test_narrow_float_custom_storage.py index f5919c25e..748ba1511 100644 --- a/tests/test_semantic_types/test_narrow_float_custom_storage.py +++ b/tests/test_semantic_types/test_narrow_float_custom_storage.py @@ -10,6 +10,8 @@ from typing_extensions import override from orcapod import contexts +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.function_pod import FunctionPod from orcapod.logical_types import make_arrow_extension_type, make_polars_extension_type from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.protocols import TypeConverterProtocol @@ -108,3 +110,20 @@ def test_first_python_declaration_respects_custom_factory(route: str) -> None: assert isinstance(arrow_type, pa.ExtensionType) assert arrow_type.storage_type == _STORAGE assert converter.arrow_table_to_python_dicts(table) == rows + + +def test_function_pod_from_fn_respects_custom_factory() -> None: + context = contexts.create_registry().get_context("v1") + converter = context.type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type_factory(PayloadFactory(), python_bases=(Payload,)) + assert converter.get_logical_type(Payload) is None + + def count_entries(payload: Payload) -> int: + return len(payload.entries) + + pod = FunctionPod.from_fn(count_entries, "count", data_context=context) + assert pod.input_data_schema["payload"] is Payload + data_function = pod.data_function + assert isinstance(data_function, PythonDataFunction) + assert data_function.data_context is context From eb1c049e1683e9046cf8a41db5bb6a920d1e4800 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 02:10:16 -0800 Subject: [PATCH 32/32] fix(function-pod): preserve the default function context --- src/orcapod/core/function_pod.py | 1 - .../test_narrow_float_custom_storage.py | 19 ------------------- 2 files changed, 20 deletions(-) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 92182eb44..1c3511304 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -982,7 +982,6 @@ def from_fn( function_name=name or getattr(fn, "__name__", "unknown"), version=version, label=label, - data_context=kwargs.get("data_context"), _ctx_arg_name=ctx_arg_name, ) return cls( diff --git a/tests/test_semantic_types/test_narrow_float_custom_storage.py b/tests/test_semantic_types/test_narrow_float_custom_storage.py index 748ba1511..f5919c25e 100644 --- a/tests/test_semantic_types/test_narrow_float_custom_storage.py +++ b/tests/test_semantic_types/test_narrow_float_custom_storage.py @@ -10,8 +10,6 @@ from typing_extensions import override from orcapod import contexts -from orcapod.core.data_function import PythonDataFunction -from orcapod.core.function_pod import FunctionPod from orcapod.logical_types import make_arrow_extension_type, make_polars_extension_type from orcapod.logical_types.base_logical_type import BaseLogicalType from orcapod.logical_types.protocols import TypeConverterProtocol @@ -110,20 +108,3 @@ def test_first_python_declaration_respects_custom_factory(route: str) -> None: assert isinstance(arrow_type, pa.ExtensionType) assert arrow_type.storage_type == _STORAGE assert converter.arrow_table_to_python_dicts(table) == rows - - -def test_function_pod_from_fn_respects_custom_factory() -> None: - context = contexts.create_registry().get_context("v1") - converter = context.type_converter - assert isinstance(converter, UniversalTypeConverter) - converter.register_logical_type_factory(PayloadFactory(), python_bases=(Payload,)) - assert converter.get_logical_type(Payload) is None - - def count_entries(payload: Payload) -> int: - return len(payload.entries) - - pod = FunctionPod.from_fn(count_entries, "count", data_context=context) - assert pod.input_data_schema["payload"] is Payload - data_function = pod.data_function - assert isinstance(data_function, PythonDataFunction) - assert data_function.data_context is context