diff --git a/.zed/rules b/.zed/rules index 38da81257..994dc92f0 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1608,6 +1608,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 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 e732bb4d3..568c4b3a0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1653,6 +1653,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 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 new file mode 100644 index 000000000..d0f798265 --- /dev/null +++ b/changelog.d/ITL-1591.md @@ -0,0 +1,15 @@ +### Fixed + +- Python declarations of `float32` or `float16` dictionary keys or set elements raise + `NarrowFloatKeyError` in function pods, Python schemas for sources and stream input + 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 + +- 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/concepts/function-pods.md b/docs/concepts/function-pods.md index 4f9c32463..59436b848 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -285,6 +285,17 @@ 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 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. + A pod definition can declare a set of user classes stored as structs. When the first returned value is converted to native set storage, Orcapod 0.4.0 reports an `OutputTypeError` for that output. Use `list[T]` to return these values, including inside diff --git a/docs/concepts/logical-type-identifiers.md b/docs/concepts/logical-type-identifiers.md index 0bd59cb4e..fc63eb022 100644 --- a/docs/concepts/logical-type-identifiers.md +++ b/docs/concepts/logical-type-identifiers.md @@ -210,6 +210,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 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 new file mode 100644 index 000000000..232ba4bf8 --- /dev/null +++ b/docs/dev/design_issues/ITL-1591-NFK1.md @@ -0,0 +1,28 @@ +## `src/orcapod/semantic_types/universal_converter.py` + +### NFK1 — Declared narrow-float dictionary keys and set elements can lose entries +**Status:** resolved +**Severity:** high +**Issue:** ITL-1591 (related: ITL-924, ITL-1613) + +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:** 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, 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. 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 +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})` +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/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 0f960e8a7..bd21a2871 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -65,6 +65,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, @@ -836,6 +841,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 @@ -920,6 +927,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) @@ -1112,6 +1128,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 @@ -1126,6 +1143,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, @@ -1169,15 +1187,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, @@ -1633,11 +1653,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 f5d74dac2..39f8d7a50 100644 --- a/src/orcapod/core/datagrams/datagram.py +++ b/src/orcapod/core/datagrams/datagram.py @@ -37,10 +37,18 @@ 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 ( + 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__) @@ -139,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( @@ -157,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] = {} @@ -173,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 @@ -284,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: @@ -412,7 +437,8 @@ 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_table = arrow_table_for_rows( + self.converter, [self._data_dict], self._data_python_schema, ) @@ -441,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 @@ -465,8 +491,8 @@ 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 + self._meta_table = arrow_table_for_rows( + self.converter, [self._meta], python_schema=self._meta_python_schema ) return self._meta_table @@ -762,7 +788,8 @@ def with_meta_columns(self, **meta_updates: DataValue) -> Self: ) if prefixed: tables.append( - self.converter.python_dicts_to_arrow_table( + arrow_table_for_rows( + self.converter, [prefixed], python_schema=Schema({k: merged[k] for k in prefixed}), ) @@ -1010,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( @@ -1090,14 +1117,16 @@ def _new_columns_table( tables: list[pa.Table] = [] if python_schema: tables.append( - self.converter.python_dicts_to_arrow_table( + 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())), ) @@ -1152,6 +1181,14 @@ def with_columns( f"Use update() to modify existing columns." ) + 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( + 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 15a2a086f..2b3d7f124 100644 --- a/src/orcapod/core/datagrams/tag_data.py +++ b/src/orcapod/core/datagrams/tag_data.py @@ -38,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 @@ -97,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, @@ -158,14 +164,15 @@ 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: - added = self.converter.python_dicts_to_arrow_table( + added = arrow_table_for_rows( + self.converter, [additions], python_schema=infer_python_schema_from_pylist_data( [additions], default_type=str @@ -251,11 +258,10 @@ 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, - ) + 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 @@ -338,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: @@ -445,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, @@ -665,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. @@ -1048,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 973bc85d8..c344d2646 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -95,6 +95,8 @@ RunStats, ) +from orcapod.semantic_types._schema_conversion import struct_dicts_for_rows + logger = logging.getLogger(__name__) if TYPE_CHECKING: @@ -991,6 +993,7 @@ def from_fn( version=version, label=label, data_context=data_context, + _ctx_arg_name=ctx_arg_name, ) return cls( data_function=data_function, @@ -1720,8 +1723,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( @@ -2017,6 +2020,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 315c3a5af..99585a62f 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -141,6 +141,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" @@ -856,8 +858,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 2e1ec9911..7b0f8d9ac 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -22,6 +22,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.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig from orcapod.core.base import ContentIdentifiableBase, TraceableBase @@ -74,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__) @@ -557,6 +560,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): @@ -580,6 +585,11 @@ 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 not _inherited_types: + converter = self.data_context.type_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 @@ -1603,6 +1613,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), @@ -1656,6 +1667,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: from orcapod.pipeline.source_consistency import ( binding_dependency_error, @@ -1670,6 +1683,12 @@ def __init__( "SourceJobNode requires either explicit tag_schema/data_schema " "or a bound_source to derive schemas from." ) + 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 + 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 @@ -1690,12 +1709,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._binding_generation = 0 @@ -2305,6 +2326,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 @@ -2316,6 +2338,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 @@ -2342,6 +2365,7 @@ def from_stream( data_schema=data_schema, arrow_schemas=typed_arrow_schemas(stream), bound_source=stream, + _inherited_types=True, ) @classmethod @@ -2366,6 +2390,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: @@ -2383,6 +2408,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/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 e14373dfb..156da6a7c 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -63,6 +63,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.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.database_protocols import DatabaseRegistryProtocol @@ -825,7 +827,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 9492bc553..2953acc90 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -23,6 +23,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 FrameInitTypes @@ -106,8 +108,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 51317377b..3ddb1319f 100644 --- a/src/orcapod/core/sources/dict_source.py +++ b/src/orcapod/core/sources/dict_source.py @@ -23,6 +23,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. @@ -65,6 +70,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). @@ -89,12 +98,14 @@ def __init__( if isinstance(data_schema, pa.Schema): require_supported_nullable_types(data_schema) require_live_logical_types(data_schema, exclude=system_tag_columns) - 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 21331350c..f6d2ac7e4 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -53,12 +53,17 @@ from orcapod.types import ColumnConfig, ContentHash, 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, declared_arrow_schema, ) +from orcapod.semantic_types._schema_conversion import arrow_table_for_rows + if TYPE_CHECKING: from polars._typing import FrameInitTypes @@ -371,6 +376,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 ) @@ -930,8 +938,8 @@ def _build_stream_from_df( # 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/graph.py b/src/orcapod/pipeline/graph.py index 7bfe340e8..af96679a0 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -484,6 +484,7 @@ def load(cls, path: str | Path) -> "Pipeline": data_schema=data_schema, data_context=saved_context, arrow_schemas=arrow_schemas, + _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/serialization.py b/src/orcapod/pipeline/serialization.py index f774500d1..1f2394bc9 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 @@ -1115,9 +1117,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 new file mode 100644 index 000000000..3df89db8f --- /dev/null +++ b/src/orcapod/semantic_types/narrow_float_keys.py @@ -0,0 +1,164 @@ +"""Reject narrow float keys and elements in declared Python types (ITL-1591).""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from types import UnionType +from typing import ( + TYPE_CHECKING, + Annotated, + Literal, + Protocol, + Union, + get_args, + get_origin, + runtime_checkable, +) + +import numpy as np + +from orcapod.errors import InputValidationError +from orcapod.semantic_types.nested_none import with_context +from orcapod.types import SchemaLike + +if TYPE_CHECKING: + 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" +) +_REMEDY = ( + "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." +) + + +class NarrowFloatKeyError(InputValidationError, ValueError): + """A Python declaration has a float32 or float16 dict key or set element.""" + + +class _LogicalTypeLookup(Protocol): + """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) + 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)] + 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} + return _float_width(next(iter(value_types))) if len(value_types) == 1 else None + if annotation is np.float16: + return "float16" + if annotation is np.float32 or ( + isinstance(annotation, str) and annotation == "float32" + ): + return "float32" + return None + + +def _class_fields( + cls: type, converter: _LogicalTypeLookup +) -> 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.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 + 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) + except ValueError: + # Leave resolution errors to the converter at the point that needs the type. + return + for name in user_class_identity.stored_field_names(cls): + if name in hints: + yield name, hints[name] + + +def _violations( + annotation: object, converter: _LogicalTypeLookup, ancestors: tuple[type, ...] = () +) -> Iterator[str]: + 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 _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_schema_without_narrow_float_keys( + schema: SchemaLike, converter: _LogicalTypeLookup, *other_schemas: SchemaLike +) -> None: + """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 42c2fe969..8971e74b6 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -48,6 +48,9 @@ unrestorable_none_error, with_context, ) +from orcapod.semantic_types.narrow_float_keys import ( + require_python_schema_without_narrow_float_keys, +) from orcapod.semantic_types.nested_storage import ( NestedTypeNotStorableError, UserClassSetNotStorableError, @@ -62,11 +65,11 @@ from orcapod.hashing.semantic_hashing.type_handler_registry import ( PythonTypeHandlerRegistry, ) - 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__) @@ -640,7 +643,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}. " @@ -734,14 +737,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: @@ -750,6 +753,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 @@ -1177,6 +1182,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: @@ -1379,6 +1389,20 @@ 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, _explicit_arrow_schema=_explicit_arrow_schema + ) + + def _python_dicts_to_struct_dicts( + self, + python_dicts: list[dict[str, Any]], + python_schema: SchemaLike | None = None, + *, + _explicit_arrow_schema: pa.Schema | None = None, + ) -> list[dict[str, Any]]: + """Convert rows under an existing or inferred schema.""" if python_schema is None: python_schema = infer_python_schema_from_pylist_data(python_dicts) @@ -1513,6 +1537,19 @@ def python_dicts_to_arrow_table( Returns: A PyArrow ``Table`` containing the converted data. """ + 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.""" explicit_arrow_schema = None if python_schema is not None and arrow_schema is not None: explicit_arrow_schema = arrow_schema @@ -1532,7 +1569,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, ( @@ -1540,7 +1577,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, _explicit_arrow_schema=explicit_arrow_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 22d69eefe..67466d532 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/narrow_float_arrow_main.json b/tests/test_semantic_types/narrow_float_arrow_main.json new file mode 100644 index 000000000..bc5f94e5b --- /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:81c9ea7a7e40e9946603087f878bc910652fa38250dfc5e4ad85181196c98084", "content_hash": "semantic_v1:d60e9854e8e510770cd262028c3a390900aed6c615ec8bf0d748453f2a857a94", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002b0f2e2fc31f63b654b75a24c221ad405f730e92a1140250d35e6fee1ef29dfaf"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:81c9ea7a7e40e9946603087f878bc910652fa38250dfc5e4ad85181196c98084", "content_hash": "semantic_v1:05f0422752aaf833f96b8017ba3a024f2f6c7e7ecbd0fa0780cb244fdf4bac62", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002b0f2e2fc31f63b654b75a24c221ad405f730e92a1140250d35e6fee1ef29dfaf"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:a717a7dc660e291eedbd70129a3296f5cf2d36a8b2b6bf1a49cbc2fd3d933f1a", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002bcd93197c5bd37c8f918f6235bad0123809f8f81d7e3cb502e3fac1b75c68d88"} + }, + "custom-metadata": { + "arrow": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:81c9ea7a7e40e9946603087f878bc910652fa38250dfc5e4ad85181196c98084", "content_hash": "semantic_v1:d60e9854e8e510770cd262028c3a390900aed6c615ec8bf0d748453f2a857a94", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002b0f2e2fc31f63b654b75a24c221ad405f730e92a1140250d35e6fee1ef29dfaf"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:81c9ea7a7e40e9946603087f878bc910652fa38250dfc5e4ad85181196c98084", "content_hash": "semantic_v1:05f0422752aaf833f96b8017ba3a024f2f6c7e7ecbd0fa0780cb244fdf4bac62", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002b0f2e2fc31f63b654b75a24c221ad405f730e92a1140250d35e6fee1ef29dfaf"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"value": 4}}}], "data": [{"nested": {"value": 4}}], "pipeline_hash": "semantic_v1:a717a7dc660e291eedbd70129a3296f5cf2d36a8b2b6bf1a49cbc2fd3d933f1a", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:000002bcd93197c5bd37c8f918f6235bad0123809f8f81d7e3cb502e3fac1b75c68d88"} + }, + "newer-class": { + "arrow": {"rows": [{"id": 1, "k": {"entries": [{"key": "string", "value": 4}]}}], "data": [{"entries": [{"key": "string", "value": 4}]}], "pipeline_hash": "semantic_v1:023b1ebb62de5247a024cdbaab668be1c76e957ce82cee1a10867a629788667b", "content_hash": "semantic_v1:3d10532965399d572978dc72f28be16ecc4ea86eeb1b596d848e6fd3b0f4ba32", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000251543c01e5af380bc047c20a661b434143f8aeaa67d352ef1d55b4ba14c1b005"}, + "frame": {"rows": [{"id": 1, "k": {"entries": [{"key": "string", "value": 4}]}}], "data": [{"entries": [{"key": "string", "value": 4}]}], "pipeline_hash": "semantic_v1:023b1ebb62de5247a024cdbaab668be1c76e957ce82cee1a10867a629788667b", "content_hash": "semantic_v1:c4a2d2dd3fc06ba3c49d731bd560b257bacdc4d38aab2edd428f37e42c672d9d", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000251543c01e5af380bc047c20a661b434143f8aeaa67d352ef1d55b4ba14c1b005"}, + "polling": {"rows": [{"id": 1, "k": {"entries": [{"key": "string", "value": 4}]}}], "data": [{"entries": [{"key": "string", "value": 4}]}], "pipeline_hash": "semantic_v1:ce5b973b3f95611037edf4a42c5b55c606e298024bef77e5477c2c7d2be2d0d1", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000020cf06f773d69b88d2fd7f5a37a84e517201e15c74e86cea98f1d376dabda0b28"} + }, + "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:89cd61929894e195d665f6cedaafa7e0c367d46e1592f9ad934d3ed9c215cd43", "content_hash": "semantic_v1:4302735f2370edcbee024bb50442ffa10439c4ffdae8c6ab69ece868687b67c6", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000283bb309ccc18189145f5bfd25414e80eb739f4e908da3b0b5ea38a72d2e0a46b"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"entries": [{"key": 0.5, "value": 4}]}}}], "data": [{"nested": {"entries": [{"key": 0.5, "value": 4}]}}], "pipeline_hash": "semantic_v1:89cd61929894e195d665f6cedaafa7e0c367d46e1592f9ad934d3ed9c215cd43", "content_hash": "semantic_v1:4dc5cfab445ccf253abd162e941e7680142a6244800eb9afc91880bbbbb24d4e", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000283bb309ccc18189145f5bfd25414e80eb739f4e908da3b0b5ea38a72d2e0a46b"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"entries": [{"key": 0.5, "value": 4}]}}}], "data": [{"nested": {"entries": [{"key": 0.5, "value": 4}]}}], "pipeline_hash": "semantic_v1:87418db74f35ad33be0e3c13351adfcf65f6723c70e165c5dd926419cc7cc949", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000249cd32963f982b58150a8e8ebc5aed3bb8b0323c1f74f5a64b807abad11d1e5d"} + }, + "missing-set": { + "arrow": {"rows": [{"id": 1, "k": {"nested": {"entries": [0.5]}}}], "data": [{"nested": {"entries": [0.5]}}], "pipeline_hash": "semantic_v1:340b898a303074dd9223e3768f1db6a48b1a7fea30aec9f32a200f355ac85622", "content_hash": "semantic_v1:f7adccfb1e35cc7c1005e7937aca26022dadc05320f64c1607d57220ba794ae3", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000022876bb95c668e3e455d803565df901f082d357d34c9a56f68824e64c53e85dca"}, + "frame": {"rows": [{"id": 1, "k": {"nested": {"entries": [0.5]}}}], "data": [{"nested": {"entries": [0.5]}}], "pipeline_hash": "semantic_v1:340b898a303074dd9223e3768f1db6a48b1a7fea30aec9f32a200f355ac85622", "content_hash": "semantic_v1:31aeaa6bc01127f6d8884eced25ff805d29771dc03a4369af07089346c464ed9", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:0000022876bb95c668e3e455d803565df901f082d357d34c9a56f68824e64c53e85dca"}, + "polling": {"rows": [{"id": 1, "k": {"nested": {"entries": [0.5]}}}], "data": [{"nested": {"entries": [0.5]}}], "pipeline_hash": "semantic_v1:a8dad8344348eb395de070011d8a79cacfa4c84e50763eea090cfc4331b24d6b", "content_hash": "semantic_v1:adf12dfab359ca9c533d99e298e97c710735f8197dc607dd12bbe0b4f98f2451", "tag_hash": "arrow_v1:000002d3122ddf1a79cb984d444c44a4ac4f280a067256691df03293e37dc9f3ea8dae", "data_hash": "arrow_v1:00000284a033494ec12b297faf7e35ce93039dda4e3495d1a921c36ad5c0300cd6a7a3"} + } +} 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..f4407c939 --- /dev/null +++ b/tests/test_semantic_types/test_narrow_float_arrow_compatibility.py @@ -0,0 +1,313 @@ +"""Arrow inputs preserve source behavior captured on main before ITL-1591.""" + +from __future__ import annotations + +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 + +import numpy as np +import pyarrow as pa +import pytest +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 + +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" +_CUSTOM_METADATA = b'{"value_hash":"stored"}' + + +@final +class _CustomIntegerCodec(BaseLogicalType): + logical_type_name = _CUSTOM_NAME + python_type = _CustomInteger + + @override + def get_arrow_extension_type(self) -> pa.ExtensionType: + factory = make_arrow_extension_type( + _CUSTOM_NAME, _INT_STORAGE, _CUSTOM_METADATA + ) + return cast("Callable[[], pa.ExtensionType]", factory)() + + def get_polars_extension_type(self) -> Any: + factory = make_polars_extension_type( + _CUSTOM_NAME, _INT_STORAGE, _CUSTOM_METADATA.decode("ascii") + ) + return cast("Callable[[], Any]", factory)() + + def python_to_storage( + self, value: _CustomInteger, converter: TypeConverterProtocol | None + ) -> dict[str, int]: + return {"value": value.entries[np.float32(0.5)]} + + 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 + 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. + 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 + ) + 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] + ) + 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[int] | None = None) -> bool: + return cursor is None + + 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[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: + 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[int] + 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 source diagnostics recorded on main at 2b4d30dc.""" + 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] + + +@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 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..f5919c25e --- /dev/null +++ b/tests/test_semantic_types/test_narrow_float_custom_storage.py @@ -0,0 +1,110 @@ +"""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())])) +_METADATA = b'{"value_hash":"stored"}' + + +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, _METADATA) + return cast("Callable[[], pa.ExtensionType]", factory)() + + def get_polars_extension_type(self) -> Any: + factory = make_polars_extension_type( + self.logical_type_name, _STORAGE, _METADATA.decode("ascii") + ) + 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 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..e6c76103b --- /dev/null +++ b/tests/test_semantic_types/test_narrow_float_keys_refused.py @@ -0,0 +1,419 @@ +"""The narrow-float key and element rule applies at Python declaration boundaries.""" + +from __future__ import annotations + +import dataclasses +from typing import Any, cast +from unittest.mock import Mock + +import numpy as np +import pyarrow as pa +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 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 DataValue, Schema + +D = dict[np.float32, int] +S = set[np.float32] + +# 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] + + +@dataclasses.dataclass +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.""" + + @pytest.mark.parametrize(("python_type", "value"), PYTHON_CASES) + def test_the_converter_refuses_an_explicit_schema( + self, python_type: Any, value: Any + ) -> None: + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + 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]) + 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="Column 'k'"): + Datagram({"k": ({}, {}), "x": 1}, python_schema={"k": declared, "x": int}) + + @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", [value], data_schema={"k": python_type}) + + 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, [Nested(HoldsNarrowKey({}))])}], + tag_columns="id", + data_schema={"id": int, "c": list[Nested | None]}, + ) + + @pytest.mark.parametrize( + "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( + self, declared: Any, asynchronous: bool + ) -> None: + 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, "return": declared} + with pytest.raises(NarrowFloatKeyError, match=NOT_SUPPORTED): + function_pod(output_keys="o")(produce) + + @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: + """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}} + + +@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}) + + +@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": declared} + 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( + "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") + with pytest.raises(NarrowFloatKeyError, match="Column 'k'"): + SourceJobNode( + "input", + bound_source=source, + data_schema=data, + arrow_schemas=source.arrow_schemas, + ) + + +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 + ) + + +@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)