diff --git a/changelog.d/ITL-907.md b/changelog.d/ITL-907.md new file mode 100644 index 000000000..4a9301d31 --- /dev/null +++ b/changelog.d/ITL-907.md @@ -0,0 +1,23 @@ +### Breaking changes and migration + +- A source refuses a dict column that holds one key twice in a cell, before presenting it + (`RepeatedDictKeyError`, an `InputValidationError`, naming the column and the key). To + Orcapod a bare Arrow list of `struct` is a `dict[K, V]`, so this applies to + any such column of a table built outside Orcapod, at any depth. Remove the repeated + entries before building the source, or, if the column is meant as a list of pairs, give + the struct's fields other names. Every source kind applies the check to the rows it + presents, also to rows read back from a cache (`CachedSource`), from a job node's + store (`DerivedSource`) and from a SpiralDB table. Python values are checked as they + are stored: distinct Python keys that store as one key (for example, two floats narrowed + to the same `float32`) are refused as well. No stored value, path or hash changes (ITL-907). + Native lists and sets keep their declared element type. The check follows that type + into any user-class fields that hold dicts. + +### Fixed + +- A stored dict with a repeated key is no longer read as a Python `dict` that silently lost + an entry. `as_dict()`, `iter_data()` and a function pod taking the column raise + `RepeatedDictKeyError`, also for a stream built from an Arrow table of your own, which + is not scanned when it is built. Two keys are the same key exactly when a Python `dict` + would keep one of them: `0.0` and `-0.0` are, two nulls are, two NaN keys are not + (ITL-907). diff --git a/docs/api/errors.md b/docs/api/errors.md index 16a8fcd8a..9be9f78e3 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -40,6 +40,8 @@ These exceptions and warnings report problems identifying, binding, or reading s ::: orcapod.errors.RowIdentifierError +::: orcapod.errors.RepeatedDictKeyError + ::: orcapod.errors.SourceTooLargeError ::: orcapod.errors.UnboundSourceError diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index f0cded5c4..5836b2207 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -360,6 +360,62 @@ categorical column) is not a dictionary column: it is a library value, stored an (see [Arrays and other library values](arrays.md)), and is accepted. Supporting dictionary-encoded columns themselves is future work (ITL-1277). +### A bare list of key/value structs is a dict + +A `dict[K, V]` column is stored as a list of structs with the two fields `key` and `value`, +and Orcapod reads a bare Arrow list of that shape (a list, large list or fixed-size list of +`struct`, the fields in either order) as a `dict[K, V]`. Native lists and +sets of dataclasses follow their element's declared type, including classes with fields +named `key` and `value`. A dict holds each key once. An Arrow table built +outside Orcapod can hold a cell with one key twice; read as a Python `dict` it would lose an +entry. A source refuses such a column before presenting its rows, with +`RepeatedDictKeyError` (an `InputValidationError`) naming the column and key. It checks +dicts nested in lists, sets, dict values, structs and user-class fields. Polling and SpiralDB sources +check each batch. Cached and derived sources also check the stored rows they present. + +Two keys are repeated when a Python `dict` would keep one of them. For example, `0.0` +and `-0.0` are one key, two `date64` values of the same day read as one `date`, and +two NaN keys stay distinct. A raw `ArrowTableStream` retains the original rows in +`as_table()`. Reading a repeated key as a `dict` with `as_dict()` or a function pod raises +the same error. Remove the repeated entries first, or, if the column is meant as a list of +pairs, give the struct's fields other names. + +```python +import pyarrow as pa + +from orcapod.errors import RepeatedDictKeyError +from orcapod.sources import ArrowTableSource + +counts_type = pa.large_list( + pa.struct([("key", pa.large_string()), ("value", pa.int64())]) +) +counts = pa.table( + { + "session": ["s1", "s2"], + "counts": pa.array( + [ + [{"key": "left", "value": 3}, {"key": "right", "value": 5}], + [{"key": "left", "value": 1}, {"key": "left", "value": 4}], + ], + counts_type, + ), + } +) +try: + ArrowTableSource(counts, tag_columns=["session"], tag_only_columns=True) +except RepeatedDictKeyError as exc: + print(exc.column, exc.key) +# counts left + +source = ArrowTableSource( + counts.slice(0, 1), tag_columns=["session"], tag_only_columns=True +) +print(source.output_schema()[1]) +# Schema({'counts': dict[str, int] | None}) +print([data.as_dict() for _, data in source.iter_data()]) +# [{'counts': {'left': 3, 'right': 5}}] +``` + ### A CSV file's types: `schema=` A CSV file holds text only, so `CSVSource` infers each column's type from the file, and diff --git a/docs/dev/design_issues/ITL-907-DK1.md b/docs/dev/design_issues/ITL-907-DK1.md new file mode 100644 index 000000000..147b73122 --- /dev/null +++ b/docs/dev/design_issues/ITL-907-DK1.md @@ -0,0 +1,21 @@ +## `src/orcapod/semantic_types/universal_converter.py` + +### DK1 — A stored dict with a repeated key was read as a dict that lost an entry +**Status:** resolved +**Severity:** critical +**Issue:** ITL-907 + +A `dict[K, V]` column is stored as a list of key/value structs. A table built outside +Orcapod can hold a cell with one key twice (`[{key: 'a', value: 1}, {key: 'a', value: 2}]`). +`ArrowTableSource` accepted it; the table and its hash held both entries, while `as_dict()` +returned `{'a': 2}` and a function pod reading the column received a dict that had silently +lost an entry. An explicit storage type can also cause distinct Python keys to store as one key. + +**Fix:** Both refusals (developer, November 28, 2026). Which Arrow type is a dict has one +definition for bare Arrow types, `UniversalTypeConverter.dict_entry_fields`. Sources +follow declared logical types through native containers and user-class fields and check +dicts at the table-to-stream boundary (`source_stream`). That covers eager tables, +polling and SpiralDB batches, and cached or derived rows. The check uses Arrow values +when storage equality matches Python equality, and decoded keys otherwise. The Python +dict reader also refuses repeats on raw streams. Both raise `RepeatedDictKeyError` +with the key and column. Stored layouts and hashes are unchanged. diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 5c00d1641..a2ebea0cb 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -17,6 +17,7 @@ from orcapod.core.sources.source_ids import parse_source_id from orcapod.core.sources.stream_builder import ( require_supported_nullable_types, + source_stream, validate_source_table, ) from orcapod.errors import ( @@ -24,10 +25,6 @@ InputValidationError, UnstorableColumnError, ) -from orcapod.core.streams.arrow_table_stream import ( - ArrowTableStream, - stream_from_derived_table, -) from orcapod.core.streams.base import ( typed_arrow_schemas, check_head_size, @@ -61,7 +58,7 @@ from orcapod.utils import schema_utils if TYPE_CHECKING: - from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.database_protocols import DatabaseRegistryProtocol from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types import ContentHash @@ -704,8 +701,9 @@ def _build_merged_stream(self) -> ArrowTableStream: tag_keys = self._source.keys()[0] # Cached rows are this source's: give them its data context, not the default. - return stream_from_derived_table( + return source_stream( all_records, + self.data_context.type_converter, tag_columns=tag_keys, data_context=self.data_context, data_tags=stream_data_tags(self._source), diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index f045d3786..24f5952f4 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -24,14 +24,11 @@ from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( - require_supported_nullable_types, - validate_source_table, SourceStreamBuilder, normalize_record_id_columns, -) -from orcapod.core.streams.arrow_table_stream import ( - ArrowTableStream, - stream_from_derived_table, + require_supported_nullable_types, + source_stream, + validate_source_table, ) from orcapod.core.streams.view import ( ViewStatus, @@ -50,6 +47,7 @@ from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: + from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.protocols.core_protocols import StreamProtocol @@ -702,9 +700,9 @@ def _get_stream(self) -> ArrowTableStream: # earlier read (ITL-1331), as a provisional operator's stream does. self._require_origin_bindings() self._note_provisional_identity_use() + if self._cached_stream is not None: + return self._cached_stream if self._tags_as_data is not None: - if self._cached_stream is not None: - return self._cached_stream self._origin_seen = self._origin.last_modified stream, has_rows = self._build_derived_stream(self._tags_as_data) if has_rows: @@ -713,14 +711,14 @@ def _get_stream(self) -> ArrowTableStream: self._cached_stream = stream return stream - if self._cached_table is None: - self._origin_seen = self._origin.last_modified - records = self._origin_records() - if records is None: - self._cached_table = self._empty_origin_table() - else: - self._cached_table = records - return self._stream_over(self._cached_table) + seen = self._origin.last_modified + records = self._origin_records() + table = self._empty_origin_table() if records is None else records + stream = self._stream_over(table) + self._origin_seen = seen + self._cached_table = table + self._cached_stream = stream + return stream def _held_rows(self) -> "pa.Table | None": """The rows this source holds from its origin, or ``None`` before a read.""" @@ -777,10 +775,13 @@ def check_for_new_data(self) -> bool: # The stored rows' ids may not be theirs to keep in another order: order # counts unless a record_id_columns were given (never assume). unchanged = same_rows(held, read, ordered=not self._record_id_columns) - self._origin_seen = seen if unchanged: + self._origin_seen = seen return False + stream = self._stream_over(read) + self._origin_seen = seen self._cached_table = read + self._cached_stream = stream self._update_modified_time() return True @@ -812,13 +813,10 @@ def head( self._note_provisional_identity_use() config = ColumnConfig.handle_config(columns, all_info=all_info) origin_kind = "held" if isinstance(self._origin, RootSource) else "stored" - if self._tags_as_data is not None and self._cached_stream is not None: + if self._cached_stream is not None: return self._cached_stream.head(n, columns=config).for_stream( self, origin=origin_kind ) - if self._tags_as_data is None and self._cached_table is not None: - stream = self._stream_over(self._cached_table) - return stream.head(n, columns=config).for_stream(self, origin=origin_kind) if isinstance(self._origin, RootSource): origin_head = self._origin.head(n) if ( @@ -883,8 +881,9 @@ def _stream_over(self, table: "pa.Table") -> ArrowTableStream: """Return this source's stream over the origin rows ``table``.""" if self._tags_as_data is not None: return self._derive_from(table, self._tags_as_data) - return stream_from_derived_table( + return source_stream( validate_source_table(table), + self.data_context.type_converter, tag_columns=self._origin.keys()[0], data_tags=self._data_tags(), ) diff --git a/src/orcapod/core/sources/dict_keys.py b/src/orcapod/core/sources/dict_keys.py new file mode 100644 index 000000000..8fa2b90a9 --- /dev/null +++ b/src/orcapod/core/sources/dict_keys.py @@ -0,0 +1,289 @@ +"""A source refuses a stored dict that repeats a key (ITL-907). + +A ``dict[K, V]`` column is stored as a bare list of key/value structs, as recognized by +the type converter's ``dict_entry_fields``. A table built outside Orcapod can hold a +cell with one key twice; read as a Python ``dict`` it would lose an entry. Source +streams scan only columns whose types contain a dict, including dicts nested +inside other values. + +The scan compares scalar keys with matching Arrow and Python equality in Polars. +Other keys are decoded with the same converter used to read the dict, so distinct +stored values that read as one key are caught as well. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, cast + +import numpy as np +import polars as pl +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.core.operators import arrow_keys +from orcapod.errors import RepeatedDictKeyError + +if TYPE_CHECKING: + from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol + + +def holds_dict_type(arrow_type: pa.DataType, converter: TypeConverterProtocol) -> bool: + """Return whether a column's type is, or holds at any depth, a dict type. + + Decided from the type alone, following the declared children of native containers + and user classes. + + Args: + arrow_type: The Arrow type of a column, or of a part of one. + converter: The type converter, which defines the dict type. + + Returns: + True when a value of the type can hold a dict. + """ + if _dict_entry_fields(arrow_type, converter) is not None: + return True + return any( + holds_dict_type(field.type, converter) + for field in _storage_fields(arrow_type, converter) + ) + + +def _dict_entry_fields( + arrow_type: pa.DataType, converter: TypeConverterProtocol +) -> tuple[pa.Field[Any], pa.Field[Any]] | None: + """Identify a bare Arrow dict using the converter's storage rules.""" + if not arrow_keys.is_list_kind(arrow_type): + return None + return converter.dict_entry_fields(arrow_type) + + +def _storage_fields( + arrow_type: pa.DataType, converter: TypeConverterProtocol +) -> tuple[pa.Field[Any], ...]: + """Return the fields read individually, preserving nested logical types.""" + if isinstance(arrow_type, pa.BaseExtensionType): + return converter.logical_storage_fields(arrow_type) + if arrow_keys.is_list_kind(arrow_type): + lists = cast("pa.LargeListType[Any]", arrow_type) + return (lists.value_field,) + if pa.types.is_struct(arrow_type): + return tuple(cast("pa.StructType", arrow_type)) + return () + + +def refuse_repeated_dict_keys( + column: pa.ChunkedArray[Any], converter: TypeConverterProtocol +) -> None: + """Refuse a column in which one cell's dict holds a key more than once. + + Called only for a column whose type ``holds_dict_type``. The caller knows the + column's name and adds it (``RepeatedDictKeyError.in_column``). + + Args: + column: The column, as the source was given it. + converter: The type converter, which defines the dict type. + + Raises: + RepeatedDictKeyError: If a dict, at any depth, repeats a key. It holds the key. + """ + for chunk in column.chunks: + _scan(chunk, column.type, converter) + + +def _scan( + array: pa.Array[Any], arrow_type: pa.DataType, converter: TypeConverterProtocol +) -> None: + """Check every dict in ``array``, at every depth, for a repeated key.""" + if len(array) == 0: + return + if _dict_entry_fields(arrow_type, converter) is not None: + _check_dicts(cast("pa.LargeListArray[Any]", array), converter) + return + fields = _storage_fields(arrow_type, converter) + if not any(holds_dict_type(field.type, converter) for field in fields): + return + if isinstance(array, pa.ExtensionArray): + array = array.storage + if arrow_keys.is_list_kind(array.type): + # ``flatten`` leaves out what a null list or a slice does not hold. + _scan( + cast("pa.LargeListArray[Any]", array).flatten(), fields[0].type, converter + ) + return + # A struct: each child with the struct's own nulls, so a null struct holds nothing. + for child, field in zip( + cast("pa.StructArray", array).flatten(), fields, strict=True + ): + _scan(child, field.type, converter) + + +def _check_dicts( + dicts: pa.LargeListArray[Any], converter: TypeConverterProtocol +) -> None: + """Check one array of dicts: each cell's keys, then the dicts its entries hold.""" + fields = _dict_entry_fields(dicts.type, converter) + assert fields is not None + key_field, value_field = fields + entries = cast("pa.StructArray", dicts.flatten()) + cells = _parent_indices(dicts) + # A null entry is no key/value pair (the read refuses it on its own terms). + if entries.null_count: + valid = entries.is_valid() + entries = cast("pa.StructArray", entries.filter(valid)) + cells = cells.filter(valid) + flat = dict(zip((f.name for f in entries.type), entries.flatten(), strict=True)) + keys = flat[key_field.name] + if len(keys) > 1: + to_python = converter.get_arrow_to_python_converter(key_field.type) + if _stored_equality_is_python_equality(key_field.type): + found = _first_repeat(cells, keys) + if found is not None: + raise RepeatedDictKeyError(to_python(keys[found].as_py())) + else: + _refuse_repeat_in_python(cells, keys, to_python) + _scan(keys, key_field.type, converter) + _scan(flat[value_field.name], value_field.type, converter) + + +def _stored_equality_is_python_equality(key_type: pa.DataType) -> bool: + """Return whether two stored keys are equal exactly when their Python values are. + + True only for the scalar types whose value reads back exactly, with ``0.0`` equal + to ``-0.0`` and a NaN equal to nothing (``_first_repeat`` applies both). False for + everything Python compares another way than its storage: a logical type (the + class's own equality), a struct or a list (a tuple, an unhashable value, an empty + value for a null), a ``date64`` (one ``date`` per day), a ``time64[ns]`` and every + other nanosecond type (read to the microsecond), a timestamp in a zone other than + UTC (two instants of one wall-clock time compare equal), a decimal of negative + scale or of a width Polars may not read. Those are compared in Python. + + Args: + key_type: The Arrow type of a dict's keys. + + Returns: + True when the repeats can be found on the stored values. + """ + types = pa.types + if isinstance(key_type, pa.BaseExtensionType): + return False + if ( + types.is_integer(key_type) + or types.is_boolean(key_type) + or types.is_floating(key_type) + or types.is_string(key_type) + or types.is_large_string(key_type) + or types.is_string_view(key_type) + or types.is_binary(key_type) + or types.is_large_binary(key_type) + or types.is_binary_view(key_type) + or types.is_fixed_size_binary(key_type) + or types.is_date32(key_type) + or types.is_time32(key_type) + ): + return True + if types.is_decimal128(key_type) or types.is_decimal256(key_type): + return 0 <= cast(int, key_type.scale) <= cast(int, key_type.precision) + if types.is_time64(key_type) or types.is_duration(key_type): + return key_type.unit != "ns" + if types.is_timestamp(key_type): + return key_type.unit != "ns" and key_type.tz in (None, "UTC") + return False + + +def _parent_indices(lists: pa.Array[Any]) -> pa.Array[Any]: + """Return, for each element ``lists.flatten()`` gives, the row of ``lists`` it is in.""" + if pa.types.is_fixed_size_list(lists.type): + size = cast(int, lists.type.list_size) + rows = np.repeat(np.arange(len(lists), dtype=np.int64), size) + if lists.null_count: + rows = rows[ + np.repeat(lists.is_valid().to_numpy(zero_copy_only=False), size) + ] + return pa.array(rows, pa.int64()) + counted = pc.list_value_length(lists) + lengths = counted.fill_null(0).to_numpy(zero_copy_only=False) + return pa.array( + np.repeat(np.arange(len(lists), dtype=np.int64), lengths), pa.int64() + ) + + +def _first_repeat(cells: pa.Array[Any], keys: pa.Array[Any]) -> int | None: + """Return the position of a key its cell holds more than once, or ``None``. + + For a key type whose stored equality is Python's + (``_stored_equality_is_python_equality``). + + Args: + cells: For each key, the cell (row of the dict array) it is in. + keys: The keys of every cell, in cell order. + + Returns: + The position in ``keys`` of the first key that repeats an earlier key of its + cell, or ``None`` when no cell repeats a key. + """ + # A NaN equals nothing in Python, so a NaN key is never a repeat; Polars would + # match two NaN. Such keys are left out before Polars compares. + positions = np.arange(len(keys), dtype=np.int64) + if pa.types.is_floating(keys.type): + floats = keys.cast(pa.float32()) if pa.types.is_float16(keys.type) else keys + nan = cast("pa.BooleanArray", pc.is_nan(floats).fill_null(False)) + if pc.any(nan).as_py(): + kept = pc.invert(nan) + positions = positions[kept.to_numpy(zero_copy_only=False)] + cells, keys = cells.filter(kept), keys.filter(kept) + if len(keys) < 2: + return None + frame = cast( + "pl.DataFrame", + pl.from_arrow( + pa.Table.from_arrays( + [cells, arrow_keys.polars_ready(keys)], names=["cell", "key"] + ) + ), + ) + # The first key that an earlier key of its cell equals: the one the read raises on. + first = frame.select(pl.struct("cell", "key").is_first_distinct().alias("first"))[ + "first" + ].to_numpy() + hits = np.flatnonzero(~first) + return int(positions[hits[0]]) if len(hits) else None + + +def _refuse_repeat_in_python( + cells: pa.Array[Any], keys: pa.Array[Any], to_python: Callable[[Any], Any] +) -> None: + """Refuse a cell that repeats a key, comparing the keys as the read does. + + Each key is converted as the read converts it and looked up in its cell's keys + with Python's own equality, so a repeat is exactly a key the ``dict`` would lose. + A cell whose read fails on a key for another reason (a key Python cannot hash, a + null the conversion cannot read) is no repeat: the read raises that error itself, + at that key, so the rest of the cell is not compared. + + Args: + cells: For each key, the cell (row of the dict array) it is in. + keys: The stored keys of every cell, in cell order. + to_python: The converter's conversion of one stored key. + + Raises: + RepeatedDictKeyError: If a cell repeats a key. It holds the key. + """ + held: dict[Any, Any] = {} + current: Any = None + failed = False + for position, cell in enumerate(cells.to_pylist()): + if cell != current: + current, held, failed = cell, {}, False + if failed: + continue + try: + key = to_python(keys[position].as_py()) + repeated = key in held + if not repeated: + held[key] = None + except Exception: # noqa: BLE001 # whatever the read raises on this key + failed = True + continue + if repeated: + raise RepeatedDictKeyError(key) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index fad31d780..6af115e13 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -16,6 +16,7 @@ import pyarrow as pa +from orcapod.core.sources import dict_keys from orcapod.core.sources.source_ids import ( build_source_id, hash_source_name, @@ -23,7 +24,11 @@ require_source_name, ) from orcapod.core.streams.arrow_table_stream import stream_from_derived_table -from orcapod.errors import InputValidationError, RowIdentifierError +from orcapod.errors import ( + InputValidationError, + RepeatedDictKeyError, + RowIdentifierError, +) from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, @@ -44,6 +49,7 @@ from orcapod.contexts import DataContext from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.hashing_protocols import ArrowHasherProtocol + from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol def _stored_logical_fields(field: pa.Field[Any]) -> Iterator[tuple[str, str]]: @@ -931,9 +937,43 @@ def attach_provenance( row_identifiers, ) # Nullable flags are already correct — the caller set them. - return stream_from_derived_table( - table=table, + return source_stream( + table, + self._data_context.type_converter, tag_columns=tag_columns, system_tag_columns=system_tag_columns, data_tags=data_tags, ) + + +def source_stream( + table: pa.Table, + converter: TypeConverterProtocol, + *, + tag_columns: Collection[str], + system_tag_columns: Collection[str] = (), + data_tags: Collection[str] = (), + data_context: DataContext | None = None, +) -> ArrowTableStream: + """Validate and wrap a source's rows, including batches and stored records. + + Only columns whose type contains a dict need a value scan. Raw streams and + operator results check dicts on Python reads. + """ + if table.num_rows: + # Name the first offending column consistently across table layouts. + for index, field in sorted( + enumerate(table.schema), key=lambda item: item[1].name + ): + if dict_keys.holds_dict_type(field.type, converter): + try: + dict_keys.refuse_repeated_dict_keys(table.column(index), converter) + except RepeatedDictKeyError as exc: + raise exc.in_column(field.name) from exc + return stream_from_derived_table( + table, + tag_columns=tag_columns, + system_tag_columns=system_tag_columns, + data_tags=data_tags, + data_context=data_context, + ) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index bdba06582..3a913faa7 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -18,6 +18,59 @@ class RowIdentifierError(InputValidationError, ValueError): """ +class RepeatedDictKeyError(InputValidationError, ValueError): + """A stored dict holds one key more than once (ITL-907). + + To Orcapod a bare list of key/value structs is a ``dict[K, V]``, and a dict holds each + key once. A table built outside Orcapod can hold a cell with a repeated key; + reading it as a Python ``dict`` would silently drop an entry. A source refuses + such a column when it is built, and the read of such a cell as a ``dict`` raises. + Two keys are repeated when the Python ``dict`` would keep only one of them + (``0.0`` and ``-0.0``, two nulls; two NaN keys are two keys). + + Attributes: + key: The repeated key, as the Python value it is read as. + column: The column holding the dict, when the raiser knows it. + """ + + key: Any + column: str | None + + def __init__(self, key: Any, column: str | None = None) -> None: + """Build the error. + + Args: + key: The repeated key, as the Python value it is read as. + column: The column holding the dict, or ``None`` when not known. + """ + self.key = key + self.column = column + where = "" if column is None else f"Column {column!r}: " + super().__init__( + f"{where}a stored dict holds the key {key!r} more than once. To Orcapod " + f"a bare list of key/value structs is a dict (dict[K, V]) and a dict holds " + f"each key once: read as a dict it would lose an entry. Remove the " + f"repeated entries before the table is given to Orcapod, or, if the " + f"column is meant as a list of pairs, rename the struct's fields " + f"(anything but exactly 'key' and 'value')." + ) + + def __reduce__(self) -> tuple[object, ...]: + """Rebuild from the key and column when sent across processes.""" + return (type(self), (self.key, self.column), self.__dict__) + + def in_column(self, column: str) -> "RepeatedDictKeyError": + """Return the same refusal naming the column the dict is in. + + Args: + column: The column the caller knows the dict was read from. + + Returns: + A new error with the same key and ``column``. + """ + return type(self)(self.key, column) + + class SchemaInconsistencyError(InputValidationError): """Raised when a data batch has a schema that is incompatible with the expected schema. diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 39cba09ff..f23c28a88 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -115,7 +115,7 @@ def __init__( self._logical_name = logical_name self._python_type = python_type self._storage_type = storage_type - self._field_annotations = field_annotations + self._field_annotations = tuple(field_annotations) self._identity_record = identity_record metadata: dict[str, Any] = {"category": self.category, "value_hash": "stored"} @@ -150,6 +150,11 @@ def storage_type(self) -> pa.StructType: """The Arrow struct type of the stored fields.""" return self._storage_type + @property + def field_annotations(self) -> tuple[tuple[str, Any], ...]: + """The declared types used to decode this class's stored fields.""" + return self._field_annotations + def get_arrow_extension_type(self) -> pa.ExtensionType: """Return the cached Arrow extension type (name = identity string).""" if self._arrow_ext is None: diff --git a/src/orcapod/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index b09b3b3d7..3ab03e28d 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -60,3 +60,31 @@ def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": . def get_logical_type_for_python_type( self, annotation: Any ) -> "LogicalTypeProtocol | None": ... + + def dict_entry_fields( + self, arrow_type: "pa.DataType" + ) -> "tuple[pa.Field[Any], pa.Field[Any]] | None": + """Identify the entry fields if this Arrow type represents a dict. + + Args: + arrow_type: The Arrow type to classify. + + Returns: + The fields in key/value order regardless of Arrow field order, or + ``None`` for another type. + """ + ... + + def logical_storage_fields( + self, arrow_type: "pa.BaseExtensionType" + ) -> "tuple[pa.Field[Any], ...]": + """Describe the children the converter reads from an extension's storage. + + Args: + arrow_type: The Arrow extension type to inspect. + + Returns: + The children in storage order with their logical types restored, or + an empty tuple for an opaque extension. + """ + ... diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 678270275..bfb6b719b 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -20,7 +20,7 @@ from datetime import date, datetime, timezone # Handle generic types -from typing import TYPE_CHECKING, Any, TypedDict, get_args, get_origin +from typing import TYPE_CHECKING, Any, TypedDict, cast, get_args, get_origin import pyarrow as pa @@ -30,6 +30,7 @@ InstantOutOfRangeError, NaiveDatetimeError, NotADatetimeError, + RepeatedDictKeyError, SubMicrosecondDatetimeError, UnsupportedValueError, ) @@ -1425,6 +1426,9 @@ def arrow_table_to_python_dicts( python_dict[field_name] = converters[field_name](value) except NestedNoneNotRestorableError as exc: raise with_context(f"Column {field_name!r}", exc) from exc + except RepeatedDictKeyError as exc: + # The dict's own conversion cannot say which column it was in. + raise exc.in_column(field_name) from exc else: python_dict[field_name] = None python_dicts.append(python_dict) @@ -1701,18 +1705,14 @@ def _convert_arrow_to_python(self, arrow_type: pa.DataType) -> type | Any: ): element_type = arrow_type.value_type - # Check if this is a dict representation: list> - if pa.types.is_struct(element_type): - field_names = [field.name for field in element_type] - if set(field_names) == {"key", "value"}: - # This is a dict - key_field = next(f for f in element_type if f.name == "key") - value_field = next(f for f in element_type if f.name == "value") + # A dict representation: list> + entry_fields = self.dict_entry_fields(arrow_type) + if entry_fields is not None: + key_field, value_field = entry_fields + key_python_type = self.arrow_type_to_python_type(key_field.type) + value_python_type = self.arrow_type_to_python_type(value_field.type) - key_python_type = self.arrow_type_to_python_type(key_field.type) - value_python_type = self.arrow_type_to_python_type(value_field.type) - - return dict[key_python_type, value_python_type] + return dict[key_python_type, value_python_type] # Regular list element_python_type = self.arrow_type_to_python_type(element_type) @@ -2028,31 +2028,31 @@ def _create_arrow_to_python_converter( ): element_type = arrow_type.value_type - # Check if this is a dict representation - if pa.types.is_struct(element_type): - field_names = [field.name for field in element_type] - if set(field_names) == {"key", "value"}: - # Dict representation - key_field = next(f for f in element_type if f.name == "key") - value_field = next(f for f in element_type if f.name == "value") - - key_converter = self.get_arrow_to_python_converter(key_field.type) - value_converter = self._nested_value_converter(value_field.type) - - def convert_entries(value: Any) -> dict[Any, Any]: - if not value: - return {} - converted = {} - for item in value: - # A null entry is not a key/value pair: never drop it. - if item is None: - raise unrestorable_none_error(element_type) - converted[key_converter(item["key"])] = value_converter( - item["value"] - ) - return converted - - return convert_entries + # A dict representation + entry_fields = self.dict_entry_fields(arrow_type) + if entry_fields is not None: + key_field, value_field = entry_fields + key_converter = self.get_arrow_to_python_converter(key_field.type) + value_converter = self._nested_value_converter(value_field.type) + + def convert_entries(value: Any) -> dict[Any, Any]: + if not value: + return {} + converted = {} + for item in value: + # A null entry is not a key/value pair: never drop it. + if item is None: + raise unrestorable_none_error(element_type) + key = key_converter(item["key"]) + # A dict holds a key once: a stored repeat is never read as + # a dict that lost an entry (ITL-907). The caller names the + # column. + if key in converted: + raise RepeatedDictKeyError(key) + converted[key] = value_converter(item["value"]) + return converted + + return convert_entries # Regular list element_converter = self._nested_value_converter(element_type) @@ -2108,6 +2108,80 @@ def convert_entries(value: Any) -> dict[Any, Any]: # Default passthrough return lambda value: value + @staticmethod + def dict_entry_fields( + arrow_type: pa.DataType, + ) -> tuple[pa.Field[Any], pa.Field[Any]] | None: + """Return the key and value fields of a dict type, or ``None`` for any other type. + + A bare list, large list or fixed-size list whose element is a struct with + exactly the two fields ``key`` and ``value``, in either order, is the stored + form of a ``dict[K, V]`` (ITL-907). A logical type defines how its own + storage is read. + + Args: + arrow_type: An Arrow type, not looked into: a type that only holds a dict + type (a list of dicts) gives ``None``. + + Returns: + ``(key field, value field)`` for a dict type, else ``None``. + """ + if not ( + pa.types.is_list(arrow_type) + or pa.types.is_large_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + ): + return None + element_type = arrow_type.value_type + if not pa.types.is_struct(element_type): + return None + if {field.name for field in element_type} != {"key", "value"}: + return None + key_field = next(f for f in element_type if f.name == "key") + value_field = next(f for f in element_type if f.name == "value") + return key_field, value_field + + def logical_storage_fields( + self, arrow_type: pa.BaseExtensionType + ) -> tuple[pa.Field[Any], ...]: + """Return the logical types of a native container's or user class's children. + + Arrow storage omits the nested extensions. Recover them from the same + registered types the reader uses, keeping the stored Arrow types for bare + children. A logical type that decodes its own storage exposes no children. + + Args: + arrow_type: The Arrow extension type of a column. + + Returns: + Storage fields in Arrow order with their logical types restored, or the + empty tuple for an opaque or unregistered logical type. + """ + from orcapod.logical_types.list_logical_type_factory import ListLogicalType + from orcapod.logical_types.user_class_logical_type import UserClassLogicalType + + logical_type = self.get_logical_type_by_arrow_extension_name( + arrow_type.extension_name + ) + if isinstance(logical_type, ListLogicalType): + storage = cast("pa.LargeListType[Any]", arrow_type.storage_type) + field = storage.value_field + element = logical_type.element_logical_type + if element is not None: + field = field.with_type(element.get_arrow_extension_type()) + return (field,) + if isinstance(logical_type, UserClassLogicalType): + annotations = dict(logical_type.field_annotations) + storage = cast("pa.StructType", arrow_type.storage_type) + fields = [] + for field in storage: + declared = self.python_type_to_arrow_type(annotations[field.name]) + if isinstance(declared, pa.BaseExtensionType): + field = field.with_type(declared) + fields.append(field) + return tuple(fields) + return () + def _is_user_class_extension(self, extension_name: str) -> bool: """Whether *extension_name* is the logical type of a user class (ITL-1144). diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py new file mode 100644 index 000000000..1529249ec --- /dev/null +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -0,0 +1,1140 @@ +"""A stored dict with a repeated key is refused, at the source and when read (ITL-907). + +Developer decision, November 28, 2026: both refusals. A ``dict[K, V]`` column is stored as +a list of key/value structs, and to Orcapod a bare list of ``struct`` is a dict +(the type converter's one definition, ``dict_entry_fields``). A table built outside Orcapod +can hold a cell with a repeated key; ``as_dict()`` used to return a dict that had silently +lost an entry while the table and its hash held both. + +* A source refuses such a column when it is built (the source builder every source goes + through before presenting rows), naming the column and the key. +* The conversion of a stored key/value list to a Python ``dict`` raises on a repeated key, + which covers every route that passes no source (a raw ``ArrowTableStream``). + +Two keys are repeated exactly when the Python ``dict`` would keep one of them: ``0.0`` and +``-0.0`` are, two nulls are, two NaN keys are not. +""" + +from __future__ import annotations + +import asyncio +import json +import math +import pickle +import warnings +from dataclasses import dataclass, field, replace +from datetime import date, datetime, timedelta +from decimal import Decimal +from importlib.resources import files +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest +from deltalake import write_deltalake + +from orcapod import function_pod +from orcapod.channels import Channel +from orcapod.contexts import get_default_context +from orcapod.contexts.registry import JSONDataContextRegistry +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.sources import ( + ArrowTableSource, + CachedSource, + DeltaTableSource, + DictSource, + PollingSource, + SpiralDBTableSource, +) +from orcapod.core.sources import dict_keys +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ( + InputValidationError, + ProvisionalHashWarning, + RepeatedDictKeyError, + UnrecordedTableSchemaWarning, +) +from orcapod.logical_types import make_arrow_extension_type, make_polars_extension_type +from orcapod.logical_types.base_logical_type import BaseLogicalType +from orcapod.operators import SelectDataColumns +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.types import CacheMode, Cursor, PollingConfig +from orcapod.utils.arrow_utils import normalize_extension_columns +from tests.test_databases import fake_spiral_sdk + +KV = pa.struct([("key", pa.large_string()), ("value", pa.int64())]) +DICT = pa.large_list(KV) + + +def _entries(*keys: Any) -> list[dict[str, Any]]: + """One cell: the entries ``key -> position`` in the order given.""" + return [{"key": key, "value": index} for index, key in enumerate(keys)] + + +GOOD = [_entries("p", "q"), _entries("q"), _entries()] +# The repeat at the start and at the end of the cell, in the middle row. +REPEATS = { + "start": [_entries("p"), _entries("a", "a", "b"), _entries("q", "r")], + "end": [_entries("p"), _entries("b", "c", "a", "a"), _entries("q", "r")], +} +LAYOUTS = { + "tags_first": ["a", "b", "d", "e", "v", "w"], + "data_first": ["w", "e", "v", "d", "b", "a"], +} + + +def _table( + d: Any, e: Any = None, layout: str = "tags_first", dict_type: pa.DataType = DICT +) -> pa.Table: + """Tags ``a``, ``b``, data ``v``, ``w`` and the dict columns ``d`` and ``e``.""" + columns = { + "a": pa.array(["x", "y", "z"], pa.large_string()), + "b": pa.array([1, 2, 3], pa.int64()), + "v": pa.array([1.5, 2.5, 3.5], pa.float64()), + "w": pa.array(["m", "n", "o"], pa.large_string()), + "d": d if isinstance(d, pa.Array) else pa.array(d, dict_type), + "e": pa.array(GOOD if e is None else e, DICT), + } + names = LAYOUTS[layout] + return pa.table([columns[name] for name in names], names=names) + + +def _source(table: pa.Table, role: str = "data", dicts: tuple[str, ...] = ("d",)): + """An ``ArrowTableSource`` whose columns ``dicts`` have ``role``.""" + if role == "data": + return ArrowTableSource(table, tag_columns=["b", "a"], tag_only_columns=True) + return ArrowTableSource( + table, + tag_columns=["b", *dicts, "a"], + tag_only_columns=True if role == "tag" else ["a", "b"], + ) + + +def _refused(info: pytest.ExceptionInfo[RepeatedDictKeyError], column: str, key: Any): + error = info.value + assert isinstance(error, InputValidationError) + assert isinstance(error, ValueError) + assert error.column == column + assert error.key == key + assert f"Column {column!r}" in str(error) + assert f"the key {key!r} more than once" in str(error) + + +@pytest.mark.parametrize("column", [None, "d"]) +def test_repeated_dict_key_error_preserves_its_diagnostic_when_pickled( + column: str | None, +) -> None: + error = RepeatedDictKeyError((1, "a"), column) + restored = pickle.loads(pickle.dumps(error)) + assert isinstance(restored, RepeatedDictKeyError) + assert (restored.key, restored.column, str(restored)) == ( + error.key, + error.column, + str(error), + ) + + +class ForwardingConverter: + """A converter adapter forwarding the full conversion interface.""" + + def __init__( + self, delegate: UniversalTypeConverter | None = None, **kwargs: Any + ) -> None: + self._converter = delegate or UniversalTypeConverter(**kwargs) + + def __getattr__(self, name: str) -> Any: + return getattr(self._converter, name) + + +class ConverterWithUnusedStorageProperty(ForwardingConverter): + @property + def logical_storage_fields(self) -> Any: + raise AssertionError("A bare dict must not inspect the logical storage hook") + + +@pytest.mark.parametrize("from_spec", [False, True], ids=["direct", "from-spec"]) +def test_a_forwarding_converter_can_validate_a_source( + from_spec: bool, tmp_path: Path +) -> None: + if from_spec: + spec = json.loads( + files("orcapod.contexts").joinpath("data", "v1.json").read_text() + ) + spec["type_converter"]["_class"] = f"{__name__}.ForwardingConverter" + _ = (tmp_path / "v1.json").write_text(json.dumps(spec)) + context = JSONDataContextRegistry(contexts_dir=tmp_path).get_context() + else: + context = replace(get_default_context(), type_converter=ForwardingConverter()) + + plain = ArrowTableSource(pa.table({"i": [1, 2]}), data_context=context) + assert plain.as_table().to_pydict() == {"i": [1, 2]} + valid = ArrowTableSource(_one_row(["p", "q"]), data_context=context) + assert valid.as_table()["d"].to_pylist() == [_entries("p", "q")] + with pytest.raises(RepeatedDictKeyError) as info: + ArrowTableSource(_one_row(["dup", "dup"]), data_context=context) + _refused(info, "d", "dup") + + +def test_a_bare_dict_does_not_inspect_the_logical_storage_hook() -> None: + context = replace( + get_default_context(), type_converter=ConverterWithUnusedStorageProperty() + ) + with pytest.raises(RepeatedDictKeyError) as info: + ArrowTableSource(_one_row(["dup", "dup"]), data_context=context) + _refused(info, "d", "dup") + + +# ── at the door: a source ─────────────────────────────────────────────────── + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +@pytest.mark.parametrize("where", sorted(REPEATS)) +@pytest.mark.parametrize("role", ["tag", "data-tag", "data"]) +def test_a_source_refuses_a_dict_column_with_a_repeated_key( + role: str, where: str, layout: str +) -> None: + table = _table(REPEATS[where], layout=layout) + with pytest.raises(RepeatedDictKeyError) as info: + _source(table, role) + _refused(info, "d", "a") + + +@pytest.mark.parametrize( + ("stored", "repeated"), + [(True, False), (False, True), (True, True)], + ids=["stored-form", "repeated-key", "both"], +) +def test_stored_logical_form_is_refused_before_repeated_dict_keys( + stored: bool, repeated: bool +) -> None: + """An invalid logical annotation is rejected before the dict value scan.""" + table = _table(REPEATS["start"] if repeated else GOOD) + converter = get_default_context().type_converter + paths = converter.python_dicts_to_arrow_table( + [{"path": Path("a")}, {"path": Path("b")}, {"path": Path("c")}] + ) + if stored: + paths = normalize_extension_columns(paths) + table = table.append_column(paths.schema.field("path"), paths["path"]) + + if stored: + with pytest.raises( + InputValidationError, match=r"'path'.*orcapod\.path.*stored form" + ) as error: + _source(table) + assert type(error.value) is InputValidationError + else: + with pytest.raises(RepeatedDictKeyError) as info: + _source(table) + _refused(info, "d", "a") + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +@pytest.mark.parametrize("role", ["tag", "data-tag", "data"]) +def test_a_source_with_two_dict_columns_names_the_one_with_the_repeat( + role: str, layout: str +) -> None: + only_e = _table( + GOOD, [_entries("p"), _entries("q"), _entries("k", "j", "k")], layout + ) + with pytest.raises(RepeatedDictKeyError) as info: + _source(only_e, role, ("d", "e")) + _refused(info, "e", "k") + + both = _table( + REPEATS["start"], [_entries("k", "k"), _entries(), _entries()], layout + ) + with pytest.raises(RepeatedDictKeyError) as info: + _source(both, role, ("d", "e")) + # The first in name order, whatever the table's layout and the columns' roles. + _refused(info, "d", "a") + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +@pytest.mark.parametrize("role", ["tag", "data-tag", "data"]) +def test_a_dict_column_without_a_repeat_is_unchanged(role: str, layout: str) -> None: + table = _table(GOOD, [_entries("k", "j"), _entries("j"), _entries("k")], layout) + source = _source(table, role, ("d", "e")) + out = source.as_table() + assert out.column("d").to_pylist() == GOOD + assert out.column("d").type == DICT + rows = [{**tag.as_dict(), **data.as_dict()} for tag, data in source.iter_data()] + assert [row["d"] for row in rows] == [{"p": 0, "q": 1}, {"q": 0}, {}] + assert [row["e"] for row in rows] == [{"k": 0, "j": 1}, {"j": 0}, {"k": 0}] + + +VK = pa.struct([("value", pa.int64()), ("key", pa.large_string())]) +SHAPES = { + "large_list": pa.large_list(KV), + "list": pa.list_(pa.struct([("key", pa.string()), ("value", pa.int64())])), + "fixed_size_list": pa.list_(KV, 2), + "value_before_key": pa.large_list(VK), +} + + +@pytest.mark.parametrize("shape", sorted(SHAPES)) +def test_every_list_of_key_value_structs_is_a_dict(shape: str) -> None: + """A list of pairs, in either field order and any list kind, is a dict to Orcapod.""" + cells = [_entries("p", "q"), _entries("a", "a"), _entries("q", "r")] + table = _table(cells, dict_type=SHAPES[shape]) + with pytest.raises(RepeatedDictKeyError) as info: + _source(table) + _refused(info, "d", "a") + good = [_entries("p", "q"), _entries("a", "b"), _entries("q", "r")] + rows = [ + d.as_dict()["d"] + for _, d in _source(_table(good, dict_type=SHAPES[shape])).iter_data() + ] + assert rows == [{"p": 0, "q": 1}, {"a": 0, "b": 1}, {"q": 0, "r": 1}] + + +def test_a_list_of_structs_with_other_field_names_is_not_a_dict() -> None: + pairs = pa.large_list( + pa.struct([("name", pa.large_string()), ("value", pa.int64())]) + ) + cells = [[{"name": "a", "value": 1}, {"name": "a", "value": 2}], [], []] + source = _source(_table(cells, dict_type=pairs)) + assert source.as_table().column("d").to_pylist() == cells + + +NESTED = { + # list[dict[str, int]] + "in_a_list": ( + pa.large_list(DICT), + [[_entries("p")], [_entries("p", "q"), _entries("b", "a", "a")], []], + "a", + ), + # dict[str, dict[str, int]] + "as_a_dict_value": ( + pa.large_list(pa.struct([("key", pa.large_string()), ("value", DICT)])), + [ + [{"key": "o", "value": _entries("p")}], + [ + {"key": "o", "value": _entries("p", "q")}, + {"key": "u", "value": _entries("a", "b", "a")}, + ], + [], + ], + "a", + ), + # A struct holding a dict. + "in_a_struct": ( + pa.struct([("n", pa.int64()), ("m", DICT)]), + [ + {"n": 1, "m": _entries("p")}, + {"n": 2, "m": _entries("a", "a")}, + {"n": 3, "m": _entries()}, + ], + "a", + ), + # The outer dict of a dict of dicts. + "outer_of_nested": ( + pa.large_list(pa.struct([("key", pa.large_string()), ("value", DICT)])), + [ + [{"key": "o", "value": _entries("p")}], + [ + {"key": "o", "value": _entries("p", "q")}, + {"key": "o", "value": _entries("a", "b")}, + ], + [], + ], + "o", + ), +} + + +@pytest.mark.parametrize("kind", sorted(NESTED)) +def test_a_source_refuses_a_repeated_key_at_every_depth(kind: str) -> None: + arrow_type, cells, key = NESTED[kind] + with pytest.raises(RepeatedDictKeyError) as info: + _source(_table(cells, dict_type=arrow_type)) + _refused(info, "d", key) + + +@dataclass(frozen=True) +class Measurement: + key: str + value: int + + +@dataclass +class Measurements: + events: list[Measurement] + + +_MEASUREMENTS = [Measurement("sensor", 4), Measurement("sensor", 5)] + + +@pytest.mark.parametrize( + ("annotation", "events"), + [ + (list[Measurement], _MEASUREMENTS), + (set[Measurement], set(_MEASUREMENTS)), + (list[list[Measurement]], [_MEASUREMENTS]), + (Measurements, Measurements(_MEASUREMENTS)), + ], + ids=["list", "set", "nested", "field"], +) +def test_native_containers_keep_key_value_dataclasses( + annotation: Any, events: Any +) -> None: + source = DictSource( + [{"a": "batch", "d": events}], + tag_columns=["a"], + tag_only_columns=True, + data_schema={"a": str, "d": annotation}, + ) + assert next(source.iter_data())[1].as_dict()["d"] == events + + +@dataclass +class OrderedSamples: + entries: list[dict[str, Any]] + + +class LogicalOrderedSamples(BaseLogicalType): + """An opaque type that reads key/value pairs as an ordered sequence.""" + + logical_type_name = "test.itl907.ordered_samples" + python_type = OrderedSamples + _metadata = '{"value_hash":"stored"}' + _arrow_type = make_arrow_extension_type(logical_type_name, DICT, _metadata.encode()) + _polars_type = make_polars_extension_type(logical_type_name, DICT, _metadata) + + def get_arrow_extension_type(self) -> pa.ExtensionType: + """Return the Arrow type of the stored pairs.""" + return self._arrow_type() # pyright: ignore[reportCallIssue] # Generated class takes no arguments. + + def get_polars_extension_type(self): + """Return the Polars type of the stored pairs.""" + return self._polars_type() # pyright: ignore[reportCallIssue] # Generated class takes no arguments. + + def python_to_storage(self, value: OrderedSamples, converter: Any) -> Any: + """Store the entries in their original order.""" + return value.entries + + def storage_to_python(self, storage_value: Any, converter: Any) -> OrderedSamples: + """Reconstruct the ordered entries.""" + return OrderedSamples(storage_value) + + +@dataclass +class SampleGroup: + events: list[OrderedSamples] + + +@pytest.fixture(scope="module") +def ordered_samples_type() -> None: + """Register an opaque logical type in the converter used to read data rows.""" + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + converter.register_logical_type(LogicalOrderedSamples()) + + +@pytest.mark.usefixtures("ordered_samples_type") +@pytest.mark.parametrize( + ("annotation", "wrap"), + [ + (list[OrderedSamples], lambda samples: [samples]), + (list[list[OrderedSamples]], lambda samples: [[samples]]), + (SampleGroup, lambda samples: SampleGroup([samples])), + ], + ids=["list", "nested", "field"], +) +def test_native_containers_respect_opaque_element_types( + annotation: Any, wrap: Any +) -> None: + events = wrap(OrderedSamples(_entries("sensor", "sensor"))) + source = DictSource( + [{"a": "batch", "d": events}], + tag_columns=["a"], + tag_only_columns=True, + data_schema={"a": str, "d": annotation}, + ) + assert next(source.iter_data())[1].as_dict()["d"] == events + + +@dataclass(frozen=True) +class DictAtKey: + key: dict[str, int] = field(hash=False) + value: int + + +@dataclass(frozen=True) +class DictAtValue: + key: int + value: dict[str, int] = field(hash=False) + + +@dataclass(frozen=True) +class DictAtOtherField: + identifier: int + readings: dict[str, int] = field(hash=False) + + +@pytest.mark.parametrize( + ("record_type", "dict_field", "scalar_field"), + [ + (DictAtKey, "key", "value"), + (DictAtValue, "value", "key"), + (DictAtOtherField, "readings", "identifier"), + ], +) +@pytest.mark.parametrize( + ("wrap_type", "wrap_storage"), + [ + (lambda record_type: record_type, lambda record: record), + (lambda record_type: list[record_type], lambda record: [record]), + (lambda record_type: set[record_type], lambda record: [record]), + (lambda record_type: list[list[record_type]], lambda record: [[record]]), + ], + ids=["direct", "list", "set", "nested"], +) +def test_a_source_refuses_repeated_dict_keys_inside_user_class_fields( + record_type: type, + dict_field: str, + scalar_field: str, + wrap_type: Any, + wrap_storage: Any, +) -> None: + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + annotation = wrap_type(record_type) + converter.register_python_class(annotation) + arrow_type = converter.python_type_to_arrow_type(annotation) + assert isinstance(arrow_type, pa.ExtensionType) + cell = wrap_storage({dict_field: _entries("sensor", "sensor"), scalar_field: 1}) + column = pa.ExtensionArray.from_storage( + arrow_type, pa.array([cell], type=arrow_type.storage_type) + ) + table = pa.table({"a": ["batch"], "b": [1], "d": column}) + table.validate(full=True) + with pytest.raises(RepeatedDictKeyError) as info: + _source(table) + _refused(info, "d", "sensor") + + +def test_a_forwarding_converter_refuses_repeats_inside_a_logical_type() -> None: + context = get_default_context() + assert isinstance(context.type_converter, UniversalTypeConverter) + converter = ForwardingConverter(context.type_converter) + context.type_converter.register_python_class(DictAtOtherField) + arrow_type = context.type_converter.python_type_to_arrow_type(DictAtOtherField) + assert isinstance(arrow_type, pa.ExtensionType) + column = pa.ExtensionArray.from_storage( + arrow_type, + pa.array( + [{"identifier": 1, "readings": _entries("sensor", "sensor")}], + type=arrow_type.storage_type, + ), + ) + with pytest.raises(RepeatedDictKeyError) as info: + ArrowTableSource( + pa.table({"d": column}), + data_context=replace(context, type_converter=converter), + ) + _refused(info, "d", "sensor") + + +def test_a_repeat_must_be_inside_one_cell() -> None: + """The same key in two cells, and in two dicts of one list cell, is no repeat.""" + _source(_table([_entries("a"), _entries("a"), _entries("a")])) + cells = [[_entries("a"), _entries("a")], [_entries("a", "b")], []] + _source(_table(cells, dict_type=pa.large_list(DICT))) + + +def test_a_sliced_and_chunked_column_is_scanned_as_it_is() -> None: + """Rows outside a slice do not count; a repeat in a later chunk does.""" + whole = _table( + [_entries("a", "a"), _entries("p"), _entries("q"), _entries("r")][1:] + ) + _source(whole) + padded = pa.table( + { + "a": pa.array(["w", "x", "y", "z"], pa.large_string()), + "b": pa.array([0, 1, 2, 3], pa.int64()), + "v": pa.array([0.5, 1.5, 2.5, 3.5]), + "d": pa.array( + [_entries("a", "a"), _entries("p"), _entries("q"), _entries("r")], DICT + ), + } + ) + ArrowTableSource(padded.slice(1), tag_columns=["a", "b"], tag_only_columns=True) + chunked = pa.concat_tables( + [padded.slice(1, 2), padded.slice(0, 1).set_column(1, "b", pa.array([9]))] + ) + with pytest.raises(RepeatedDictKeyError) as info: + ArrowTableSource(chunked, tag_columns=["a", "b"], tag_only_columns=True) + _refused(info, "d", "a") + + +# ── which keys are repeated: what a Python dict would lose ────────────────── + + +def _keyed(key_type: pa.DataType, cells: list[list[Any]]) -> pa.Array[Any]: + arrow_type = pa.large_list(pa.struct([("key", key_type), ("value", pa.int64())])) + return pa.array([_entries(*cell) for cell in cells], arrow_type) + + +def test_a_repeated_null_key_is_a_repeated_key() -> None: + with pytest.raises(RepeatedDictKeyError) as info: + _source(_table(_keyed(pa.large_string(), [["p"], [None, "a", None], []]))) + _refused(info, "d", None) + + +def test_one_null_key_is_kept_as_before() -> None: + source = _source(_table(_keyed(pa.large_string(), [["p"], [None, "a"], []]))) + rows = [data.as_dict()["d"] for _, data in source.iter_data()] + assert rows == [{"p": 0}, {None: 0, "a": 1}, {}] + + +def test_positive_and_negative_zero_are_one_key() -> None: + with pytest.raises(RepeatedDictKeyError) as info: + _source(_table(_keyed(pa.float64(), [[1.0], [0.0, 2.0, -0.0], []]))) + # The key named is the one that repeats an earlier key of its cell. + _refused(info, "d", -0.0) + + +@pytest.mark.parametrize("float_type", [pa.float64(), pa.float32(), pa.float16()]) +def test_two_nan_keys_are_two_keys(float_type: pa.DataType) -> None: + """A Python dict keeps both, so nothing is lost and nothing is refused.""" + nan = float("nan") + source = _source(_table(_keyed(float_type, [[1.0], [nan, 2.0, nan], []]))) + read = [data.as_dict()["d"] for _, data in source.iter_data()][1] + assert len(read) == 3 + assert sorted(read.values()) == [0, 1, 2] + assert sum(math.isnan(key) for key in read) == 2 + + +TUPLE = pa.struct([("f0", pa.float64()), ("f1", pa.large_string())]) + + +def test_a_tuple_key_is_compared_field_by_field() -> None: + def cell(*keys: tuple[float, str | None]) -> list[dict[str, Any]]: + return [{"f0": f0, "f1": f1} for f0, f1 in keys] + + with pytest.raises(RepeatedDictKeyError) as info: + _source( + _table(_keyed(TUPLE, [[], cell((0.0, "a"), (1.0, "a"), (-0.0, "a")), []])) + ) + _refused(info, "d", (-0.0, "a")) + with pytest.raises(RepeatedDictKeyError) as info: + _source(_table(_keyed(TUPLE, [[], cell((1.0, None), (1.0, None)), []]))) + _refused(info, "d", (1.0, None)) + # A NaN anywhere in a key makes it a key of its own, as in Python. + nan = float("nan") + source = _source( + _table(_keyed(TUPLE, [[], cell((nan, "a"), (nan, "a"), (1.0, "b")), []])) + ) + assert len([data.as_dict()["d"] for _, data in source.iter_data()][1]) == 3 + + +def test_a_source_refuses_a_repeated_key_in_a_dict_inside_a_tuple_key() -> None: + key_type = pa.struct([("f0", pa.int64()), ("f1", DICT)]) + nested_keys = [{"f0": 1, "f1": _entries("dup", "dup")}] + table = _table(_keyed(key_type, [[], nested_keys, []])) + with pytest.raises(RepeatedDictKeyError) as info: + _source(table) + _refused(info, "d", "dup") + + distinct_keys = [{"f0": 1, "f1": _entries("p", "q")}] + table = _table(_keyed(key_type, [[], distinct_keys, []])) + assert _source(table).as_table()["d"].to_pylist() == [ + [], + _entries(*distinct_keys), + [], + ] + with pytest.raises(TypeError, match="unhashable"): + _ = [data.as_dict() for _, data in _source(table).iter_data()] + + +def test_a_key_type_polars_has_no_rule_for_is_compared_in_python() -> None: + """About the scan itself: no source holds such a key today (the Arrow hasher + refuses an interval), so the scan is called directly.""" + converter = get_default_context().type_converter + interval = pa.month_day_nano_interval() + one = pa.scalar((1, 2, 3), interval).as_py() + two = pa.scalar((1, 2, 4), interval).as_py() + repeated = pa.chunked_array([_keyed(interval, [[one], [one, two, one], []])]) + assert dict_keys.holds_dict_type(repeated.type, converter) + with pytest.raises(RepeatedDictKeyError) as info: + dict_keys.refuse_repeated_dict_keys(repeated, converter) + assert info.value.key == one + assert info.value.column is None + dict_keys.refuse_repeated_dict_keys( + pa.chunked_array([_keyed(interval, [[one], [one, two], [one]])]), converter + ) + + +# ── other source kinds ────────────────────────────────────────────────────── + + +def test_a_delta_table_source_refuses_a_repeated_key(tmp_path: Any) -> None: + table = pa.table( + { + "a": pa.array(["x", "y"], pa.large_string()), + "b": pa.array([1, 2], pa.int64()), + "v": pa.array([1.5, 2.5]), + "d": pa.array([_entries("p", "q"), _entries("b", "a", "a")], DICT), + } + ) + path = str(tmp_path / "repeated") + write_deltalake(path, table) + with pytest.raises(RepeatedDictKeyError) as info: + DeltaTableSource( + delta_table_path=path, tag_columns=["a", "b"], tag_only_columns=True + ) + _refused(info, "d", "a") + + +class _Batches: + """Fetches a good batch, then one whose dict column repeats a key.""" + + def identity(self) -> str: + return "itl907-batches" + + def to_config(self) -> None: + return None + + @classmethod + def from_config(cls, config: Any) -> _Batches: + return cls() + + def schema(self) -> pa.Schema: + return pa.schema( + [ + pa.field("a", pa.large_string()), + pa.field("b", pa.int64()), + pa.field("v", pa.float64()), + pa.field("d", DICT), + ] + ) + + async def poll(self, cursor: Cursor[int] | None = None) -> bool: + return cursor is None or cursor.value < 2 + + async def fetch(self, cursor: Cursor[int] | None = None) -> tuple[Cursor[int], Any]: + batch = 1 if cursor is None else cursor.value + 1 + cell = _entries("p", "q") if batch == 1 else _entries("a", "b", "a") + table = pa.Table.from_pylist( + [{"a": f"x{batch}", "b": batch, "v": 1.5, "d": cell}], schema=self.schema() + ) + return Cursor(value=batch), table + + async def close(self) -> None: + return None + + +def test_a_polling_source_refuses_a_repeated_key_in_a_later_batch() -> None: + source = PollingSource( + _Batches(), + tag_columns=["a", "b"], + record_id_columns="a", + polling_config=PollingConfig(duration=0.01), + ) + first = source.as_table() + assert first.column("d").to_pylist() == [_entries("p", "q")] + with pytest.raises(RepeatedDictKeyError) as info: + source.as_table() + _refused(info, "d", "a") + + +# ── the cost: only dict-typed columns are scanned ─────────────────────────── + + +def test_only_columns_holding_a_dict_type_are_scanned( + monkeypatch: pytest.MonkeyPatch, +) -> None: + scanned: list[pa.DataType] = [] + scan = dict_keys.refuse_repeated_dict_keys + + def counted(column: Any, converter: Any) -> None: + scanned.append(column.type) + scan(column, converter) + + monkeypatch.setattr(dict_keys, "refuse_repeated_dict_keys", counted) + plain = pa.table( + { + "a": pa.array(["x", "y"], pa.large_string()), + "b": pa.array([1, 2], pa.int64()), + "v": pa.array([[1, 2], [3]], pa.large_list(pa.int64())), + "w": pa.array([{"key": "k", "n": 1}] * 2), + "pairs": pa.array( + [[{"name": "k", "value": 1}]] * 2, + pa.large_list( + pa.struct([("name", pa.string()), ("value", pa.int64())]) + ), + ), + } + ) + ArrowTableSource(plain, tag_columns=["a", "b"], tag_only_columns=True) + assert scanned == [] + _source(_table(GOOD)) + assert scanned == [DICT, DICT] + + +# ── at the read: no source in the way ─────────────────────────────────────── + + +def _stream(table: pa.Table, role: str = "data") -> ArrowTableStream: + if role == "data": + return ArrowTableStream(table, tag_columns=["b", "a"]) + return ArrowTableStream( + table, + tag_columns=["b", "d", "a"], + data_tags=("d",) if role == "data-tag" else (), + ) + + +@pytest.mark.parametrize("layout", sorted(LAYOUTS)) +@pytest.mark.parametrize("where", sorted(REPEATS)) +@pytest.mark.parametrize("role", ["tag", "data-tag", "data"]) +def test_a_raw_stream_keeps_the_stored_value_and_refuses_it_as_a_dict( + role: str, where: str, layout: str +) -> None: + stream = _stream(_table(REPEATS[where], layout=layout), role) + # No value scan when a stream is built: the stored value is what was given. + assert stream.as_table().column("d").to_pylist() == REPEATS[where] + rows = list(stream.iter_data()) + for index, (tag, data) in enumerate(rows): + holder = tag if role != "data" else data + if index != 1: + assert isinstance(holder.as_dict()["d"], dict) + continue + with pytest.raises(RepeatedDictKeyError) as info: + holder.as_dict() + _refused(info, "d", "a") + + +@pytest.mark.parametrize("kind", sorted(NESTED)) +def test_the_read_refuses_a_repeated_key_at_every_depth(kind: str) -> None: + arrow_type, cells, key = NESTED[kind] + rows = list(_stream(_table(cells, dict_type=arrow_type)).iter_data()) + with pytest.raises(RepeatedDictKeyError) as info: + rows[1][1].as_dict() + _refused(info, "d", key) + + +def test_the_read_follows_what_a_python_dict_would_lose() -> None: + nan = float("nan") + + def second(array: pa.Array[Any]) -> Any: + return list(_stream(_table(array)).iter_data())[1][1] + + with pytest.raises(RepeatedDictKeyError) as info: + second(_keyed(pa.large_string(), [["p"], [None, "a", None], []])).as_dict() + _refused(info, "d", None) + with pytest.raises(RepeatedDictKeyError) as info: + second(_keyed(pa.float64(), [[1.0], [0.0, 2.0, -0.0], []])).as_dict() + _refused(info, "d", -0.0) + assert ( + len(second(_keyed(pa.float64(), [[1.0], [nan, nan], []])).as_dict()["d"]) == 2 + ) + assert second(_keyed(pa.large_string(), [["p"], [None, "a"], []])).as_dict()[ + "d" + ] == { + None: 0, + "a": 1, + } + + +@function_pod(output_keys="size") +def _size(d: dict[str, int]) -> int: + return len(d) + + +def _pod_input(where: str) -> ArrowTableStream: + table = _table(REPEATS[where]).select(["a", "b", "d"]) + # The function takes ``dict[str, int]``, not ``dict[str, int] | None``. + table = table.cast( + table.schema.set(2, table.schema.field("d").with_nullable(False)) + ) + return ArrowTableStream(table, tag_columns=["b", "a"]) + + +@pytest.mark.parametrize("where", sorted(REPEATS)) +def test_a_function_pod_reading_the_dict_raises_on_the_sync_path(where: str) -> None: + with pytest.raises(RepeatedDictKeyError) as info: + _size.pod(_pod_input(where)).as_table() + _refused(info, "d", "a") + + +@pytest.mark.parametrize("where", sorted(REPEATS)) +def test_a_function_pod_reading_the_dict_raises_on_the_async_path(where: str) -> None: + async def run() -> None: + stream = _pod_input(where) + inputs: Channel[Any] = Channel(buffer_size=16) + output: Channel[Any] = Channel(buffer_size=16) + for row in stream.iter_data(): + await inputs.writer.send(row) + await inputs.writer.close() + await _size.pod.async_execute( + [inputs.reader], output.writer, error_policy="fail_fast" + ) + + # The pod's task group reports the row's error in a group. + with pytest.raises(ExceptionGroup) as group: + asyncio.run(run()) + (error,) = group.value.exceptions + assert isinstance(error, RepeatedDictKeyError) + assert (error.column, error.key) == ("d", "a") + + +# ── every source kind passes the door (independent review of PR 626) ──────── + + +def _one_row(keys: list[Any]) -> pa.Table: + """One row whose dict column ``d`` holds ``keys``; tags ``a`` and ``b``.""" + return pa.table( + { + "a": pa.array(["x"], pa.large_string()), + "b": pa.array([1], pa.int64()), + "d": pa.array([_entries(*keys)], DICT), + "v": pa.array([2], pa.int64()), + } + ) + + +def test_a_cached_source_refuses_a_stored_row_with_a_repeated_key() -> None: + """A cache table can hold a row written before the check existed.""" + database = InMemoryArrowDatabase() + source = ArrowTableSource( + _one_row(["good"]), tag_columns=["a", "b"], tag_only_columns=True + ) + cache = CachedSource(source, database) + assert cache.as_table().num_rows == 1 + key = cache.HASH_COLUMN_NAME + stored = database.get_all_records(cache.cache_path, record_id_column=key) + assert stored is not None + legacy = stored.set_column( + stored.schema.get_field_index("d"), + stored.schema.field("d"), + _one_row(["dup", "other", "dup"])["d"], + ).set_column( + stored.schema.get_field_index(key), + stored.schema.field(key), + pa.array([b"legacy-row"], stored.schema.field(key).type), + ) + database.add_records(cache.cache_path, legacy, record_id_column=key, flush=True) + with pytest.raises(RepeatedDictKeyError) as info: + CachedSource(source, database).as_table() + _refused(info, "d", "dup") + + +def test_a_plain_derived_source_refuses_a_stored_row_with_a_repeated_key() -> None: + stream = ArrowTableStream(_one_row(["dup", "dup"]), tag_columns=["a", "b"]) + database = InMemoryArrowDatabase() + node = OperatorJobNode( + operator=SelectDataColumns(["d"]), + input_streams=[stream], + pipeline_database=database, + cache_mode=CacheMode.LOG, + ) + node.run() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + derived = node.as_source() + with pytest.raises(RepeatedDictKeyError) as info: + derived.as_table() + _refused(info, "d", "dup") + with pytest.raises(RepeatedDictKeyError): + list(derived.iter_data()) + + # Correct the logged record. The same source should retry the read. + (path,) = database.list_table_paths() + stored = database.get_all_records(path, record_id_column=node.HASH_COLUMN_NAME) + assert stored is not None + corrected = stored.set_column( + stored.schema.get_field_index("d"), + stored.schema.field("d"), + _one_row(["ok"])["d"], + ) + database.add_records( + path, corrected, record_id_column=node.HASH_COLUMN_NAME, flush=True + ) + assert derived.as_table()["d"].to_pylist() == [_entries("ok")] + + +def test_a_plain_derived_source_validates_held_rows_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + stream = ArrowTableStream(_one_row(["ok"]), tag_columns=["a", "b"]) + node = OperatorJobNode( + operator=SelectDataColumns(["d"]), + input_streams=[stream], + pipeline_database=InMemoryArrowDatabase(), + cache_mode=CacheMode.LOG, + ) + node.run() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + derived = node.as_source() + + sizes: list[int] = [] + scan = dict_keys.refuse_repeated_dict_keys + + def count_scan(column: pa.ChunkedArray[Any], converter: Any) -> None: + sizes.append(len(column)) + scan(column, converter) + + monkeypatch.setattr(dict_keys, "refuse_repeated_dict_keys", count_scan) + assert derived.as_table()["d"].to_pylist() == [_entries("ok")] + assert derived.head(1).table["d"].to_pylist() == [_entries("ok")] + assert derived.as_table()["d"].to_pylist() == [_entries("ok")] + assert sizes == [1] + + +@pytest.mark.parametrize("cached", [False, True], ids=["direct", "fresh-cache"]) +def test_a_spiraldb_source_refuses_a_batch_with_a_repeated_key( + tmp_path: Any, cached: bool +) -> None: + with fake_spiral_sdk.install(tmp_path): + project = fake_spiral_sdk.ExternalProject("itl907") + project.create_table( + "default.items", key_schema=pa.schema([("b", pa.int64())]) + ).write(_one_row(["dup", "dup"])) + with pytest.warns(UnrecordedTableSchemaWarning): + spiral = SpiralDBTableSource( + "itl907", "items", tag_columns=["a", "b"], tag_only_columns=True + ) + source = CachedSource(spiral, InMemoryArrowDatabase()) if cached else spiral + with pytest.raises(RepeatedDictKeyError) as info: + source.as_table() + _refused(info, "d", "dup") + with pytest.raises(RepeatedDictKeyError): + list(source.iter_data()) + + +# ── the door agrees with the read, key type by key type ───────────────────── + + +NEW_YORK = pa.timestamp("s", "America/New_York") +AGREEMENT: dict[str, tuple[pa.DataType, list[Any], bool]] = { + # key type, the keys of one cell, whether the Python dict loses an entry. + "date64_one_day": (pa.date64(), [0, 1], True), + "date64_two_days": (pa.date64(), [0, 86_400_000], False), + "date32": (pa.date32(), [0, 1], False), + "time64_ns_one_microsecond": (pa.time64("ns"), [1, 2], True), + "time64_ns_two_microseconds": (pa.time64("ns"), [1000, 2000], False), + "time64_us": (pa.time64("us"), [1, 2], False), + "time32_ms_repeat": (pa.time32("ms"), [5, 5], True), + "timestamp_ms": (pa.timestamp("ms"), [1, 2], False), + "timestamp_us_utc_repeat": (pa.timestamp("us", "UTC"), [7, 7], True), + "timestamp_ns": (pa.timestamp("ns"), [1, 2], False), + "duration_ns": (pa.duration("ns"), [1, 2], False), + "duration_us_repeat": (pa.duration("us"), [3, 3], True), + "empty_tuple_two_nulls": (pa.list_(pa.int64(), 0), [None, None], True), + "empty_tuple_null_and_empty": (pa.list_(pa.int64(), 0), [None, []], True), + "tuple_of_one": (pa.list_(pa.int64(), 1), [[1], [2]], False), + "tuple_of_zeros": (pa.list_(pa.float64(), 1), [[0.0], [-0.0]], True), + "decimal128": (pa.decimal128(9, 3), [Decimal("1.5"), Decimal("2.5")], False), + "decimal128_repeat": (pa.decimal128(9, 3), [Decimal("1.5"), Decimal("1.5")], True), + "decimal256": (pa.decimal256(60, 3), [Decimal("1.5"), Decimal("2.5")], False), + "decimal256_repeat": (pa.decimal256(60, 3), [Decimal("1.5")] * 2, True), + "decimal128_negative_scale_repeat": ( + pa.decimal128(9, -3), + [Decimal("1000"), Decimal("1000")], + True, + ), + "decimal32": (pa.decimal32(9, 3), [Decimal("1.5"), Decimal("1.5")], True), + "binary_repeat": (pa.large_binary(), [b"a", b"a"], True), + "strings_of_two_forms": (pa.large_string(), ["é", "é"], False), + "zoned_one_wall_clock_time": (NEW_YORK, [1793511000, 1793514600], False), + "zoned_repeat": (NEW_YORK, [1793511000, 1793511000], True), +} + + +@pytest.mark.parametrize("case", sorted(AGREEMENT)) +def test_the_door_refuses_exactly_what_the_read_would_lose(case: str) -> None: + key_type, keys, loses = AGREEMENT[case] + table = _table(_keyed(key_type, [keys[:1], keys, []])) + data = list(_stream(table).iter_data())[1][1] + if loses: + with pytest.raises(RepeatedDictKeyError) as read: + data.as_dict() + with pytest.raises(RepeatedDictKeyError) as source: + _source(table) + _refused(source, "d", read.value.key) + else: + read_dict = data.as_dict()["d"] + assert isinstance(read_dict, dict) + assert len(read_dict) == 2 + assert [d.as_dict()["d"] for _, d in _source(table).iter_data()][1] == read_dict + + +@pytest.mark.parametrize( + ("key_type", "keys", "expected_keys"), + [ + (pa.int64(), [-1, 2], [-1, 2]), + (pa.large_string(), ["é", "é"], ["é", "é"]), + (pa.large_binary(), [b"a", b"b"], [b"a", b"b"]), + (pa.date32(), [0, 1], [date(1970, 1, 1), date(1970, 1, 2)]), + (pa.date64(), [0, 86_400_000], [date(1970, 1, 1), date(1970, 1, 2)]), + ( + pa.timestamp("us"), + [1, 2], + [datetime(1970, 1, 1) + timedelta(microseconds=n) for n in (1, 2)], + ), + *[ + ( + decimal_type(6, scale), + [Decimal("10"), Decimal("20")], + [Decimal("10"), Decimal("20")], + ) + for decimal_type in ( + pa.decimal32, + pa.decimal64, + pa.decimal128, + pa.decimal256, + ) + for scale in (-1, 0, 1) + ], + ], +) +def test_distinct_keys_keep_their_values_from_main( + key_type: pa.DataType, keys: list[Any], expected_keys: list[Any] +) -> None: + table = _table(_keyed(key_type, [[], keys, []])) + source = _source(table) + assert source.as_table()["d"].equals(table["d"]) + assert list(source.iter_data())[1][1].as_dict()["d"] == dict( + zip(expected_keys, (0, 1), strict=True) + ) + + +def test_a_cell_the_read_fails_on_for_another_reason_is_no_repeat() -> None: + """Two null tuple keys: the read raises ``TypeError`` on the first, so no entry is + lost and the door does not call it a repeat.""" + table = _table(_keyed(TUPLE, [[], [None, None], []])) + source = _source(table) + rows = list(source.iter_data()) + with pytest.raises(TypeError): + rows[1][1].as_dict() + # A list is in no dict at all. + lists = _table(_keyed(pa.large_list(pa.int64()), [[], [[1], [1]], []])) + with pytest.raises(TypeError): + list(_source(lists).iter_data())[1][1].as_dict() + + +# ── Python values can store a repeated key too ────────────────────────────── + + +def test_python_keys_that_store_as_one_key_are_refused() -> None: + """Distinct Python float keys can narrow to the same float32 in storage.""" + rows = [{"a": "x", "b": 1, "d": {1.0: 10, 1.0 + 2**-26: 20}}] + schema = pa.schema( + [ + ("a", pa.large_string()), + ("b", pa.int64()), + ( + "d", + pa.large_list( + pa.struct([("key", pa.float32()), ("value", pa.int64())]) + ), + ), + ] + ) + with pytest.raises(RepeatedDictKeyError) as info: + DictSource(rows, tag_columns=["a", "b"], data_schema=schema) + _refused(info, "d", 1.0) diff --git a/tests/test_semantic_types/test_float_narrowing.py b/tests/test_semantic_types/test_float_narrowing.py index 9249db06f..e99c51fff 100644 --- a/tests/test_semantic_types/test_float_narrowing.py +++ b/tests/test_semantic_types/test_float_narrowing.py @@ -28,6 +28,16 @@ def __init__(self, delegate: TypeConverterProtocol) -> None: def __getattr__(self, name: str) -> Any: return getattr(self.delegate, name) + def dict_entry_fields( + self, arrow_type: pa.DataType + ) -> tuple[pa.Field[Any], pa.Field[Any]] | None: + return self.delegate.dict_entry_fields(arrow_type) + + def logical_storage_fields( + self, arrow_type: pa.BaseExtensionType + ) -> tuple[pa.Field[Any], ...]: + return self.delegate.logical_storage_fields(arrow_type) + def python_dicts_to_arrow_table( self, python_dicts: list[dict[str, Any]],