From 346acbdf7d69739fc6b84664cc4d7583f4011144 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 21:35:06 -0800 Subject: [PATCH 1/5] fix(sources, semantic_types): refuse a stored dict with a repeated key, at the source and when read as a dict (ITL-907) A list of key/value structs is a dict to Orcapod (one definition, UniversalTypeConverter.dict_entry_fields). A source refuses a column whose type holds a dict type when a cell repeats a key, and the conversion to a Python dict raises on a repeated key. Nothing stored or hashed changes. Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-907.md | 18 + docs/api/errors.md | 2 + docs/concepts/sources.md | 53 ++ docs/dev/design_issues/ITL-907-DK1.md | 23 + src/orcapod/core/sources/dict_keys.py | 235 ++++++++ src/orcapod/core/sources/stream_builder.py | 19 +- src/orcapod/errors.py | 49 ++ .../protocols/semantic_types_protocols.py | 6 + .../semantic_types/universal_converter.py | 127 ++-- .../sources/test_repeated_dict_keys.py | 558 ++++++++++++++++++ 10 files changed, 1053 insertions(+), 37 deletions(-) create mode 100644 changelog.d/ITL-907.md create mode 100644 docs/dev/design_issues/ITL-907-DK1.md create mode 100644 src/orcapod/core/sources/dict_keys.py create mode 100644 tests/test_core/sources/test_repeated_dict_keys.py diff --git a/changelog.d/ITL-907.md b/changelog.d/ITL-907.md new file mode 100644 index 000000000..bde6ffe32 --- /dev/null +++ b/changelog.d/ITL-907.md @@ -0,0 +1,18 @@ +### Breaking changes and migration + +- A source refuses a dict column that holds one key twice in a cell, when it is built + (`RepeatedDictKeyError`, an `InputValidationError`, naming the column and the key). To + Orcapod every 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. Dicts Orcapod builds from Python values never repeat a + key and are not affected; no stored value, path or hash changes (ITL-907). + +### 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 cd53180f1..0b2e1b10b 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 589c57427..6cfb93d6d 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -210,6 +210,59 @@ 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 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 every Arrow column of that shape (a list, large list or fixed-size list of +`struct`, the fields in either order) as a `dict[K, V]`: nothing else marks a dict, +so a list of key/value structs **is** a dict. 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. So a source refuses such a column when it is built, with `RepeatedDictKeyError` (an +`InputValidationError`) naming the column and the key, at any depth (a dict in a list, as a +dict value, in a struct); a polling source checks each batch. Two keys are the same key +exactly when a Python `dict` would keep one of them: `0.0` and `-0.0` are one key, two nulls +are one key, and two NaN keys are two keys. A stream built from an Arrow table of your own +(`ArrowTableStream`) is not scanned when it is built: its table keeps what you gave, and +reading such a cell as a `dict` (`as_dict()`, a function taking the column) 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..f58d52cc3 --- /dev/null +++ b/docs/dev/design_issues/ITL-907-DK1.md @@ -0,0 +1,23 @@ +## `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. Dicts Orcapod builds from Python values cannot be in this state. + +**Fix:** Both refusals (developer, November 28, 2026). Which Arrow type is a dict has one +definition, `UniversalTypeConverter.dict_entry_fields` (a list of `struct` is a +dict; nothing else marks one). The source builder refuses a column whose type holds a dict +type when a cell repeats a key (`core/sources/dict_keys.py`, on the Arrow data, only for +such columns), and the conversion to a Python `dict` raises on a repeated key, which covers +the routes that pass no source (a raw `ArrowTableStream`, rows read back from a store). +Both raise `RepeatedDictKeyError`; the caller adds the column. Two keys are repeated exactly +when the Python `dict` would keep one of them (`0.0` with `-0.0`, two nulls; not two NaN). +`ArrowTableStream.__init__` does no value scan: every operator result becomes a stream +there. Nothing stored or hashed changed. diff --git a/src/orcapod/core/sources/dict_keys.py b/src/orcapod/core/sources/dict_keys.py new file mode 100644 index 000000000..437fbd4ef --- /dev/null +++ b/src/orcapod/core/sources/dict_keys.py @@ -0,0 +1,235 @@ +"""A source refuses a stored dict that repeats a key (ITL-907). + +A ``dict[K, V]`` column is stored as a list of key/value structs, and to Orcapod every +such list is a dict: which Arrow type that is has one definition, 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. The source builder calls this module for +each column whose type holds a dict type, at any depth (a dict in a list, as a dict value, +in a struct or in a user class's storage); a table with no such column is not scanned. + +Two keys are repeated exactly when the Python ``dict`` the cell is read as would keep one +of them: ``0.0`` and ``-0.0`` are one key, two nulls are one key, and a NaN (anywhere in a +key) equals nothing, so two NaN keys are two keys. Which rows hold a repeat is decided on +the Arrow data, by Polars over the prepared keys (``arrow_keys.polars_ready``, as the +joins and ``GroupBy`` compare keys); a key type with no preparation rule is compared in +Python, cell by cell. The conversion to a ``dict`` raises on a repeated key too +(``UniversalTypeConverter``), for the routes that pass no source. +""" + +from __future__ import annotations + +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. A logical type is looked into only when the converter + reads its storage as plain values (``reads_storage_as_values``: a user class, a + native container). + + 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 isinstance(arrow_type, pa.BaseExtensionType): + if not converter.reads_storage_as_values(arrow_type): + return False + return holds_dict_type(arrow_type.storage_type, converter) + if converter.dict_entry_fields(arrow_type) is not None: + return True + if arrow_keys.is_list_kind(arrow_type): + lists = cast("pa.LargeListType[Any]", arrow_type) + return holds_dict_type(lists.value_type, converter) + if pa.types.is_struct(arrow_type): + struct = cast("pa.StructType", arrow_type) + return any( + holds_dict_type(struct.field(index).type, converter) + for index in range(struct.num_fields) + ) + return False + + +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, converter) + + +def _scan(array: pa.Array[Any], converter: TypeConverterProtocol) -> None: + """Check every dict in ``array``, at every depth, for a repeated key.""" + if len(array) == 0 or not holds_dict_type(array.type, converter): + return + if isinstance(array, pa.ExtensionArray): + _scan(array.storage, converter) + return + arrow_type = array.type + if converter.dict_entry_fields(arrow_type) is not None: + _check_dicts(cast("pa.LargeListArray[Any]", array), converter) + return + if arrow_keys.is_list_kind(arrow_type): + # ``flatten`` leaves out what a null list or a slice does not hold. + _scan(cast("pa.LargeListArray[Any]", array).flatten(), converter) + return + # A struct: each child with the struct's own nulls, so a null struct holds nothing. + for child in cast("pa.StructArray", array).flatten(): + _scan(child, 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 = converter.dict_entry_fields(dicts.type) + 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: + found = _first_repeat(cells, keys) + if found is not None: + to_python = converter.get_arrow_to_python_converter(key_field.type) + stored = keys[found].as_py() + raise RepeatedDictKeyError(None if stored is None else to_python(stored)) + _scan(flat[value_field.name], converter) + + +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``. + + 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. + """ + if arrow_keys.part_without_rule(keys.type, structs=True) is not None: + return _first_repeat_in_python(cells, keys) + # A NaN equals nothing in Python, so a key holding one 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) + nan = _holds_nan(keys) + if nan is not None and 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 _first_repeat_in_python(cells: pa.Array[Any], keys: pa.Array[Any]) -> int | None: + """``_first_repeat`` for a key type with no preparation rule: Python's own equality. + + A key Python cannot hash is in no ``dict`` at all (the read raises on it): it is + not compared here. + """ + seen: dict[Any, set[Any]] = {} + for position, (cell, key) in enumerate( + zip(cells.to_pylist(), keys.to_pylist(), strict=True) + ): + held = seen.setdefault(cell, set()) + try: + if key in held: + return position + held.add(key) + except TypeError: + continue + return None + + +def _holds_nan(array: pa.Array[Any]) -> pa.BooleanArray | None: + """Return which values hold a NaN at any depth, or ``None`` when the type has no float.""" + array = arrow_keys.values_of(array) + arrow_type = array.type + if pa.types.is_floating(arrow_type): + if pa.types.is_float16(arrow_type): + array = array.cast(pa.float32()) + return cast("pa.BooleanArray", pc.is_nan(array).fill_null(False)) + if arrow_keys.is_list_kind(arrow_type): + inner = _holds_nan(cast("pa.LargeListArray[Any]", array).flatten()) + if inner is None: + return None + rows = _parent_indices(array).filter(inner) + return cast( + "pa.BooleanArray", + pc.is_in(pa.array(np.arange(len(array), dtype=np.int64)), value_set=rows), + ) + if pa.types.is_struct(arrow_type): + found: pa.BooleanArray | None = None + for child in cast("pa.StructArray", array).flatten(): + inner = _holds_nan(child) + if inner is not None: + found = ( + inner + if found is None + else cast("pa.BooleanArray", pc.or_(found, inner)) + ) + return found + return None diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 22736f37f..2a996d229 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 ArrowTableStream -from orcapod.errors import InputValidationError, RowIdentifierError +from orcapod.errors import ( + InputValidationError, + RepeatedDictKeyError, + RowIdentifierError, +) from orcapod.logical_types.identifier import LogicalTypeIdentifierError from orcapod.system_constants import constants from orcapod.types import ContentHash @@ -580,6 +585,18 @@ def build( f"Available columns: {list(table.column_names)}" ) + # A dict holds a key once (ITL-907): a column whose type holds a dict type + # (the converter's definition) is refused when a cell repeats a key, before + # anything is hashed. Only such columns are scanned, in name order, so the + # column named does not follow the table's layout. + converter = self._data_context.type_converter + for name in sorted(table.column_names): + if dict_keys.holds_dict_type(table.schema.field(name).type, converter): + try: + dict_keys.refuse_repeated_dict_keys(table.column(name), converter) + except RepeatedDictKeyError as exc: + raise exc.in_column(name) from exc + # 3. The row identifiers (validates the key columns: a missing, null or # repeated key is refused here, before anything is hashed). identifiers = row_identifiers(table, key_columns) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 23f8dd2af..2fe2403e2 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -18,6 +18,55 @@ class RowIdentifierError(InputValidationError, ValueError): """ +class RepeatedDictKeyError(InputValidationError, ValueError): + """A stored dict holds one key more than once (ITL-907). + + To Orcapod a 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 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 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/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index b09b3b3d7..1db91f782 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -53,6 +53,12 @@ def get_arrow_to_python_converter( self, arrow_type: "pa.DataType" ) -> "Callable[[Any], Any]": ... + def dict_entry_fields( + self, arrow_type: "pa.DataType" + ) -> "tuple[pa.Field[Any], pa.Field[Any]] | None": ... + + def reads_storage_as_values(self, arrow_type: "pa.BaseExtensionType") -> bool: ... + def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: ... def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": ... diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 678270275..c0ff8cbd7 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -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,61 @@ def convert_entries(value: Any) -> dict[Any, Any]: # Default passthrough return lambda value: value + def dict_entry_fields( + self, 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. + + The one definition of which Arrow type Orcapod reads as a ``dict[K, V]``: a + list, large list or fixed-size list whose element is a struct with exactly the + two fields ``key`` and ``value``, in either order. No marker tells such a list + from a dict: a list of key/value structs IS a dict (ITL-907). An Arrow map is + not one (no ``dict`` is stored as a map). + + 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 reads_storage_as_values(self, arrow_type: pa.BaseExtensionType) -> bool: + """Return whether a logical type's stored value is read part by part. + + True for a user class (its storage struct's fields) and a native container + (``list[T]`` / ``set[T]`` of a logical type: its elements), whose parts this + converter reads by their own Arrow types, so a dict type inside the storage + is read as a dict. Any other logical type decodes its storage its own way. + + Args: + arrow_type: The Arrow extension type of a column. + + Returns: + True when a dict type inside the storage type is read as a dict. + """ + 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 + ) + return isinstance(logical_type, (UserClassLogicalType, ListLogicalType)) + 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..841e7c299 --- /dev/null +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -0,0 +1,558 @@ +"""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 every 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), 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 math +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.core.sources import ( + ArrowTableSource, + DeltaTableSource, + PollingSource, +) +from orcapod.core.sources import dict_keys +from orcapod.core.streams import ArrowTableStream +from orcapod.errors import InputValidationError, RepeatedDictKeyError +from orcapod.types import Cursor, PollingConfig + +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) + + +# ── 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("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) + + +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_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") From bd7f60f0c54ca8f03b99ab3c55084bed66be1afa Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 11:16:20 -0800 Subject: [PATCH 2/5] fix(sources): validate repeated dict keys on every source stream --- changelog.d/ITL-907.md | 9 +- docs/concepts/sources.md | 20 +- docs/dev/design_issues/ITL-907-DK1.md | 17 +- src/orcapod/core/sources/cached_source.py | 10 +- src/orcapod/core/sources/derived_source.py | 6 +- src/orcapod/core/sources/dict_keys.py | 178 +++++++------ src/orcapod/core/sources/stream_builder.py | 51 ++-- .../sources/test_repeated_dict_keys.py | 236 +++++++++++++++++- 8 files changed, 411 insertions(+), 116 deletions(-) diff --git a/changelog.d/ITL-907.md b/changelog.d/ITL-907.md index bde6ffe32..bc1c2d86c 100644 --- a/changelog.d/ITL-907.md +++ b/changelog.d/ITL-907.md @@ -1,12 +1,15 @@ ### Breaking changes and migration -- A source refuses a dict column that holds one key twice in a cell, when it is built +- 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 every 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. Dicts Orcapod builds from Python values never repeat a - key and are not affected; no stored value, path or hash changes (ITL-907). + 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). ### Fixed diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a02a70fa9..238a04fc3 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -225,15 +225,17 @@ and Orcapod reads every Arrow column of that shape (a list, large list or fixed- `struct`, the fields in either order) as a `dict[K, V]`: nothing else marks a dict, so a list of key/value structs **is** a dict. 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. So a source refuses such a column when it is built, with `RepeatedDictKeyError` (an -`InputValidationError`) naming the column and the key, at any depth (a dict in a list, as a -dict value, in a struct); a polling source checks each batch. Two keys are the same key -exactly when a Python `dict` would keep one of them: `0.0` and `-0.0` are one key, two nulls -are one key, and two NaN keys are two keys. A stream built from an Arrow table of your own -(`ArrowTableStream`) is not scanned when it is built: its table keeps what you gave, and -reading such a cell as a `dict` (`as_dict()`, a function taking the column) 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. +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, dict values and structs as well. 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 diff --git a/docs/dev/design_issues/ITL-907-DK1.md b/docs/dev/design_issues/ITL-907-DK1.md index f58d52cc3..3e234591f 100644 --- a/docs/dev/design_issues/ITL-907-DK1.md +++ b/docs/dev/design_issues/ITL-907-DK1.md @@ -9,15 +9,12 @@ A `dict[K, V]` column is stored as a list of key/value structs. A table built ou 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. Dicts Orcapod builds from Python values cannot be in this state. +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, `UniversalTypeConverter.dict_entry_fields` (a list of `struct` is a -dict; nothing else marks one). The source builder refuses a column whose type holds a dict -type when a cell repeats a key (`core/sources/dict_keys.py`, on the Arrow data, only for -such columns), and the conversion to a Python `dict` raises on a repeated key, which covers -the routes that pass no source (a raw `ArrowTableStream`, rows read back from a store). -Both raise `RepeatedDictKeyError`; the caller adds the column. Two keys are repeated exactly -when the Python `dict` would keep one of them (`0.0` with `-0.0`, two nulls; not two NaN). -`ArrowTableStream.__init__` does no value scan: every operator result becomes a stream -there. Nothing stored or hashed changed. +definition, `UniversalTypeConverter.dict_entry_fields`. Sources check dict-shaped +columns 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 15501c76c..ce3dd882e 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -14,13 +14,15 @@ from orcapod.config import OrcapodConfig from orcapod.core.sources.base import RootSource from orcapod.core.sources.source_ids import parse_source_id -from orcapod.core.sources.stream_builder import require_supported_nullable_types +from orcapod.core.sources.stream_builder import ( + require_supported_nullable_types, + source_stream, +) from orcapod.errors import ( CachedSourceIdMismatchError, InputValidationError, UnstorableColumnError, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( typed_arrow_schemas, check_head_size, @@ -49,6 +51,7 @@ from orcapod.utils import schema_utils if TYPE_CHECKING: + from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.protocols.database_protocols import DatabaseRegistryProtocol logger = logging.getLogger(__name__) @@ -633,8 +636,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 ArrowTableStream( + 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 aeef4bfd5..16b2a63c6 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -20,10 +20,10 @@ from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( require_supported_nullable_types, + source_stream, SourceStreamBuilder, normalize_record_id_columns, ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -41,6 +41,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 @@ -810,8 +811,9 @@ def _stream_over(self, table: "pa.Table") -> ArrowTableStream: if self._tags_as_data is not None: return self._derive_from(table, self._tags_as_data) require_supported_nullable_types(table.schema) - return ArrowTableStream( + return source_stream( 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 index 437fbd4ef..60ffa4cac 100644 --- a/src/orcapod/core/sources/dict_keys.py +++ b/src/orcapod/core/sources/dict_keys.py @@ -3,21 +3,17 @@ A ``dict[K, V]`` column is stored as a list of key/value structs, and to Orcapod every such list is a dict: which Arrow type that is has one definition, 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. The source builder calls this module for -each column whose type holds a dict type, at any depth (a dict in a list, as a dict value, -in a struct or in a user class's storage); a table with no such column is not scanned. - -Two keys are repeated exactly when the Python ``dict`` the cell is read as would keep one -of them: ``0.0`` and ``-0.0`` are one key, two nulls are one key, and a NaN (anywhere in a -key) equals nothing, so two NaN keys are two keys. Which rows hold a repeat is decided on -the Arrow data, by Polars over the prepared keys (``arrow_keys.polars_ready``, as the -joins and ``GroupBy`` compare keys); a key type with no preparation rule is compared in -Python, cell by cell. The conversion to a ``dict`` raises on a repeated key too -(``UniversalTypeConverter``), for the routes that pass no source. +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 @@ -120,14 +116,61 @@ def _check_dicts( flat = dict(zip((f.name for f in entries.type), entries.flatten(), strict=True)) keys = flat[key_field.name] if len(keys) > 1: - found = _first_repeat(cells, keys) - if found is not None: - to_python = converter.get_arrow_to_python_converter(key_field.type) - stored = keys[found].as_py() - raise RepeatedDictKeyError(None if stored is None else to_python(stored)) + 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(flat[value_field.name], 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): @@ -148,6 +191,9 @@ def _parent_indices(lists: pa.Array[Any]) -> pa.Array[Any]: 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. @@ -156,18 +202,18 @@ def _first_repeat(cells: pa.Array[Any], keys: pa.Array[Any]) -> int | None: The position in ``keys`` of the first key that repeats an earlier key of its cell, or ``None`` when no cell repeats a key. """ - if arrow_keys.part_without_rule(keys.type, structs=True) is not None: - return _first_repeat_in_python(cells, keys) - # A NaN equals nothing in Python, so a key holding one is never a repeat; Polars - # would match two NaN. Such keys are left out before Polars compares. + # 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) - nan = _holds_nan(keys) - if nan is not None and 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 + 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( @@ -184,52 +230,40 @@ def _first_repeat(cells: pa.Array[Any], keys: pa.Array[Any]) -> int | None: return int(positions[hits[0]]) if len(hits) else None -def _first_repeat_in_python(cells: pa.Array[Any], keys: pa.Array[Any]) -> int | None: - """``_first_repeat`` for a key type with no preparation rule: Python's own equality. +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. - A key Python cannot hash is in no ``dict`` at all (the read raises on it): it is - not compared here. + 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. """ - seen: dict[Any, set[Any]] = {} - for position, (cell, key) in enumerate( - zip(cells.to_pylist(), keys.to_pylist(), strict=True) - ): - held = seen.setdefault(cell, set()) + 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: - if key in held: - return position - held.add(key) - except TypeError: + 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 - return None - - -def _holds_nan(array: pa.Array[Any]) -> pa.BooleanArray | None: - """Return which values hold a NaN at any depth, or ``None`` when the type has no float.""" - array = arrow_keys.values_of(array) - arrow_type = array.type - if pa.types.is_floating(arrow_type): - if pa.types.is_float16(arrow_type): - array = array.cast(pa.float32()) - return cast("pa.BooleanArray", pc.is_nan(array).fill_null(False)) - if arrow_keys.is_list_kind(arrow_type): - inner = _holds_nan(cast("pa.LargeListArray[Any]", array).flatten()) - if inner is None: - return None - rows = _parent_indices(array).filter(inner) - return cast( - "pa.BooleanArray", - pc.is_in(pa.array(np.arange(len(array), dtype=np.int64)), value_set=rows), - ) - if pa.types.is_struct(arrow_type): - found: pa.BooleanArray | None = None - for child in cast("pa.StructArray", array).flatten(): - inner = _holds_nan(child) - if inner is not None: - found = ( - inner - if found is None - else cast("pa.BooleanArray", pc.or_(found, inner)) - ) - return found - return None + if repeated: + raise RepeatedDictKeyError(key) diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 2a996d229..b71320ec3 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -39,6 +39,7 @@ from orcapod.config import OrcapodConfig from orcapod.contexts import DataContext from orcapod.protocols.hashing_protocols import ArrowHasherProtocol + from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol def _contains_null_type(arrow_type: pa.DataType) -> bool: @@ -585,18 +586,6 @@ def build( f"Available columns: {list(table.column_names)}" ) - # A dict holds a key once (ITL-907): a column whose type holds a dict type - # (the converter's definition) is refused when a cell repeats a key, before - # anything is hashed. Only such columns are scanned, in name order, so the - # column named does not follow the table's layout. - converter = self._data_context.type_converter - for name in sorted(table.column_names): - if dict_keys.holds_dict_type(table.schema.field(name).type, converter): - try: - dict_keys.refuse_repeated_dict_keys(table.column(name), converter) - except RepeatedDictKeyError as exc: - raise exc.in_column(name) from exc - # 3. The row identifiers (validates the key columns: a missing, null or # repeated key is refused here, before anything is hashed). identifiers = row_identifiers(table, key_columns) @@ -731,9 +720,43 @@ def attach_provenance( row_identifiers, ) # Nullable flags are already correct — the caller set them. - return ArrowTableStream( - 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 use ArrowTableStream directly and 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 ArrowTableStream( + table, + tag_columns=tag_columns, + system_tag_columns=system_tag_columns, + data_tags=data_tags, + data_context=data_context, + ) diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py index 841e7c299..46971906b 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -7,7 +7,7 @@ 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), naming the column and the key. + 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``). @@ -19,6 +19,9 @@ import asyncio import math +import warnings +from datetime import date, datetime, timedelta +from decimal import Decimal from typing import Any import pyarrow as pa @@ -28,15 +31,27 @@ from orcapod import function_pod from orcapod.channels import Channel from orcapod.contexts import get_default_context +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.errors import InputValidationError, RepeatedDictKeyError -from orcapod.types import Cursor, PollingConfig +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ( + InputValidationError, + ProvisionalHashWarning, + RepeatedDictKeyError, + UnrecordedTableSchemaWarning, +) +from orcapod.operators import SelectDataColumns +from orcapod.types import CacheMode, Cursor, PollingConfig +from tests.test_databases import fake_spiral_sdk KV = pa.struct([("key", pa.large_string()), ("value", pa.int64())]) DICT = pa.large_list(KV) @@ -556,3 +571,218 @@ async def run() -> None: (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"]) + 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() + with pytest.raises(RepeatedDictKeyError) as info: + derived.as_table() + _refused(info, "d", "dup") + with pytest.raises(RepeatedDictKeyError): + list(derived.iter_data()) + + +@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) From 4e0e293ef7fd3a7e10d03928761eb75ce403337a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:09:35 -0800 Subject: [PATCH 3/5] fix(sources): preserve logical types when checking dict keys --- changelog.d/ITL-907.md | 4 +- docs/concepts/sources.md | 11 +- docs/dev/design_issues/ITL-907-DK1.md | 5 +- src/orcapod/core/sources/dict_keys.py | 72 ++++---- src/orcapod/errors.py | 4 +- .../logical_types/user_class_logical_type.py | 7 +- .../protocols/semantic_types_protocols.py | 4 +- .../semantic_types/universal_converter.py | 46 +++-- .../sources/test_repeated_dict_keys.py | 168 +++++++++++++++++- 9 files changed, 263 insertions(+), 58 deletions(-) diff --git a/changelog.d/ITL-907.md b/changelog.d/ITL-907.md index bc1c2d86c..4a9301d31 100644 --- a/changelog.d/ITL-907.md +++ b/changelog.d/ITL-907.md @@ -2,7 +2,7 @@ - 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 every Arrow list of `struct` is a `dict[K, V]`, so this applies 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 @@ -10,6 +10,8 @@ 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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 238a04fc3..f3208ffdc 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -218,16 +218,17 @@ 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 list of key/value structs is a dict +### 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 every Arrow column of that shape (a list, large list or fixed-size list of -`struct`, the fields in either order) as a `dict[K, V]`: nothing else marks a dict, -so a list of key/value structs **is** a dict. A dict holds each key once. An Arrow table built +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, dict values and structs as well. Polling and SpiralDB sources +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` diff --git a/docs/dev/design_issues/ITL-907-DK1.md b/docs/dev/design_issues/ITL-907-DK1.md index 3e234591f..147b73122 100644 --- a/docs/dev/design_issues/ITL-907-DK1.md +++ b/docs/dev/design_issues/ITL-907-DK1.md @@ -12,8 +12,9 @@ returned `{'a': 2}` and a function pod reading the column received a dict that h 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, `UniversalTypeConverter.dict_entry_fields`. Sources check dict-shaped -columns at the table-to-stream boundary (`source_stream`). That covers eager tables, +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` diff --git a/src/orcapod/core/sources/dict_keys.py b/src/orcapod/core/sources/dict_keys.py index 60ffa4cac..d5fafc2a0 100644 --- a/src/orcapod/core/sources/dict_keys.py +++ b/src/orcapod/core/sources/dict_keys.py @@ -1,10 +1,10 @@ """A source refuses a stored dict that repeats a key (ITL-907). -A ``dict[K, V]`` column is stored as a list of key/value structs, and to Orcapod every -such list is a dict: which Arrow type that is has one definition, 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. +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 @@ -31,9 +31,8 @@ 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. A logical type is looked into only when the converter - reads its storage as plain values (``reads_storage_as_values``: a user class, a - native container). + 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. @@ -42,22 +41,26 @@ def holds_dict_type(arrow_type: pa.DataType, converter: TypeConverterProtocol) - Returns: True when a value of the type can hold a dict. """ - if isinstance(arrow_type, pa.BaseExtensionType): - if not converter.reads_storage_as_values(arrow_type): - return False - return holds_dict_type(arrow_type.storage_type, converter) if converter.dict_entry_fields(arrow_type) is not None: return True + return any( + holds_dict_type(field.type, converter) + for field in _storage_fields(arrow_type, converter) + ) + + +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 holds_dict_type(lists.value_type, converter) + return (lists.value_field,) if pa.types.is_struct(arrow_type): - struct = cast("pa.StructType", arrow_type) - return any( - holds_dict_type(struct.field(index).type, converter) - for index in range(struct.num_fields) - ) - return False + return tuple(cast("pa.StructType", arrow_type)) + return () def refuse_repeated_dict_keys( @@ -76,27 +79,34 @@ def refuse_repeated_dict_keys( RepeatedDictKeyError: If a dict, at any depth, repeats a key. It holds the key. """ for chunk in column.chunks: - _scan(chunk, converter) + _scan(chunk, column.type, converter) -def _scan(array: pa.Array[Any], converter: TypeConverterProtocol) -> None: +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 or not holds_dict_type(array.type, converter): + if len(array) == 0: return - if isinstance(array, pa.ExtensionArray): - _scan(array.storage, converter) - return - arrow_type = array.type if converter.dict_entry_fields(arrow_type) is not None: _check_dicts(cast("pa.LargeListArray[Any]", array), converter) return - if arrow_keys.is_list_kind(arrow_type): + 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(), converter) + _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 in cast("pa.StructArray", array).flatten(): - _scan(child, converter) + for child, field in zip( + cast("pa.StructArray", array).flatten(), fields, strict=True + ): + _scan(child, field.type, converter) def _check_dicts( @@ -123,7 +133,7 @@ def _check_dicts( raise RepeatedDictKeyError(to_python(keys[found].as_py())) else: _refuse_repeat_in_python(cells, keys, to_python) - _scan(flat[value_field.name], converter) + _scan(flat[value_field.name], value_field.type, converter) def _stored_equality_is_python_equality(key_type: pa.DataType) -> bool: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 8c8dcdbe8..84ca468f8 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -21,7 +21,7 @@ class RowIdentifierError(InputValidationError, ValueError): class RepeatedDictKeyError(InputValidationError, ValueError): """A stored dict holds one key more than once (ITL-907). - To Orcapod a list of key/value structs is a ``dict[K, V]``, and a dict holds each + 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. @@ -48,7 +48,7 @@ def __init__(self, key: Any, column: str | None = None) -> None: 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 list of key/value structs is a dict (dict[K, V]) and a dict holds " + 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 " diff --git a/src/orcapod/logical_types/user_class_logical_type.py b/src/orcapod/logical_types/user_class_logical_type.py index 7f9578b3b..ff11213c7 100644 --- a/src/orcapod/logical_types/user_class_logical_type.py +++ b/src/orcapod/logical_types/user_class_logical_type.py @@ -114,7 +114,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} @@ -149,6 +149,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 1db91f782..8d0783b45 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -57,7 +57,9 @@ def dict_entry_fields( self, arrow_type: "pa.DataType" ) -> "tuple[pa.Field[Any], pa.Field[Any]] | None": ... - def reads_storage_as_values(self, arrow_type: "pa.BaseExtensionType") -> bool: ... + def logical_storage_fields( + self, arrow_type: "pa.BaseExtensionType" + ) -> "tuple[pa.Field[Any], ...]": ... def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: ... diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index c0ff8cbd7..8cb69bab3 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 @@ -2113,11 +2113,10 @@ def dict_entry_fields( ) -> tuple[pa.Field[Any], pa.Field[Any]] | None: """Return the key and value fields of a dict type, or ``None`` for any other type. - The one definition of which Arrow type Orcapod reads as a ``dict[K, V]``: a - list, large list or fixed-size list whose element is a struct with exactly the - two fields ``key`` and ``value``, in either order. No marker tells such a list - from a dict: a list of key/value structs IS a dict (ITL-907). An Arrow map is - not one (no ``dict`` is stored as a map). + 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 @@ -2141,19 +2140,21 @@ def dict_entry_fields( value_field = next(f for f in element_type if f.name == "value") return key_field, value_field - def reads_storage_as_values(self, arrow_type: pa.BaseExtensionType) -> bool: - """Return whether a logical type's stored value is read part by part. + 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. - True for a user class (its storage struct's fields) and a native container - (``list[T]`` / ``set[T]`` of a logical type: its elements), whose parts this - converter reads by their own Arrow types, so a dict type inside the storage - is read as a dict. Any other logical type decodes its storage its own way. + 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: - True when a dict type inside the storage type is read as a dict. + 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 @@ -2161,7 +2162,24 @@ def reads_storage_as_values(self, arrow_type: pa.BaseExtensionType) -> bool: logical_type = self.get_logical_type_by_arrow_extension_name( arrow_type.extension_name ) - return isinstance(logical_type, (UserClassLogicalType, ListLogicalType)) + 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 index 46971906b..88c4c1b49 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -1,7 +1,7 @@ """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 every list of ``struct`` IS a dict +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. @@ -20,6 +20,7 @@ import asyncio import math import warnings +from dataclasses import dataclass, field from datetime import date, datetime, timedelta from decimal import Decimal from typing import Any @@ -49,7 +50,10 @@ 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 tests.test_databases import fake_spiral_sdk @@ -248,6 +252,168 @@ def test_a_source_refuses_a_repeated_key_at_every_depth(kind: str) -> None: _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 + _arrow_type = make_arrow_extension_type(logical_type_name, DICT, b"v1") + _polars_type = make_polars_extension_type(logical_type_name, DICT, "v1") + + 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_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")])) From 3dda273304ae8dc7445ef48e8bd9b82be4b438b1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:38:34 -0800 Subject: [PATCH 4/5] fix(sources): close repeated dict key review gaps --- src/orcapod/core/sources/derived_source.py | 17 ++-- src/orcapod/core/sources/dict_keys.py | 24 ++++- src/orcapod/errors.py | 4 + .../protocols/semantic_types_protocols.py | 48 ++++++++-- .../semantic_types/universal_converter.py | 3 +- .../sources/test_repeated_dict_keys.py | 94 ++++++++++++++++++- 6 files changed, 166 insertions(+), 24 deletions(-) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 8403d31a2..ddf666b9b 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -692,14 +692,15 @@ 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) + if self._cached_table is not None: + 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 + return stream def _held_rows(self) -> "pa.Table | None": """The rows this source holds from its origin, or ``None`` before a read.""" diff --git a/src/orcapod/core/sources/dict_keys.py b/src/orcapod/core/sources/dict_keys.py index d5fafc2a0..be31f0b36 100644 --- a/src/orcapod/core/sources/dict_keys.py +++ b/src/orcapod/core/sources/dict_keys.py @@ -23,6 +23,8 @@ from orcapod.core.operators import arrow_keys from orcapod.errors import RepeatedDictKeyError +from orcapod.protocols.semantic_types_protocols import DictStorageConverterProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter if TYPE_CHECKING: from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol @@ -41,7 +43,7 @@ def holds_dict_type(arrow_type: pa.DataType, converter: TypeConverterProtocol) - Returns: True when a value of the type can hold a dict. """ - if converter.dict_entry_fields(arrow_type) is not None: + if _dict_entry_fields(arrow_type, converter) is not None: return True return any( holds_dict_type(field.type, converter) @@ -49,12 +51,25 @@ def holds_dict_type(arrow_type: pa.DataType, converter: TypeConverterProtocol) - ) +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 supplied.""" + if not arrow_keys.is_list_kind(arrow_type): + return None + if isinstance(converter, DictStorageConverterProtocol): + return converter.dict_entry_fields(arrow_type) + return UniversalTypeConverter.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 isinstance(converter, DictStorageConverterProtocol): + return converter.logical_storage_fields(arrow_type) + return () if arrow_keys.is_list_kind(arrow_type): lists = cast("pa.LargeListType[Any]", arrow_type) return (lists.value_field,) @@ -88,7 +103,7 @@ def _scan( """Check every dict in ``array``, at every depth, for a repeated key.""" if len(array) == 0: return - if converter.dict_entry_fields(arrow_type) is not None: + 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) @@ -113,7 +128,7 @@ 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 = converter.dict_entry_fields(dicts.type) + fields = _dict_entry_fields(dicts.type, converter) assert fields is not None key_field, value_field = fields entries = cast("pa.StructArray", dicts.flatten()) @@ -133,6 +148,7 @@ def _check_dicts( 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) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 71a9efbbf..d6a2670aa 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -55,6 +55,10 @@ def __init__(self, key: Any, column: str | None = None) -> None: 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. diff --git a/src/orcapod/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index 8d0783b45..a61c68a65 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Callable -from typing import TYPE_CHECKING, Any, Protocol +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.types import DataType, Schema, SchemaLike @@ -53,14 +53,6 @@ def get_arrow_to_python_converter( self, arrow_type: "pa.DataType" ) -> "Callable[[Any], Any]": ... - def dict_entry_fields( - self, arrow_type: "pa.DataType" - ) -> "tuple[pa.Field[Any], pa.Field[Any]] | None": ... - - def logical_storage_fields( - self, arrow_type: "pa.BaseExtensionType" - ) -> "tuple[pa.Field[Any], ...]": ... - def ensure_types_registered_for_schemas(self, *schemas: Schema) -> None: ... def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": ... @@ -68,3 +60,41 @@ def get_logical_type(self, python_type: type) -> "LogicalTypeProtocol | None": . def get_logical_type_for_python_type( self, annotation: Any ) -> "LogicalTypeProtocol | None": ... + + +@runtime_checkable +class DictStorageConverterProtocol(Protocol): + """Describe Arrow storage for the source's repeated dict key check. + + A converter can implement this protocol alongside ``TypeConverterProtocol``. + Sources otherwise use the standard bare Arrow dict layout and treat logical + extensions as opaque. + """ + + 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 8cb69bab3..bfb6b719b 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -2108,8 +2108,9 @@ def convert_entries(value: Any) -> dict[Any, Any]: # Default passthrough return lambda value: value + @staticmethod def dict_entry_fields( - self, arrow_type: pa.DataType + 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. diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py index 88c4c1b49..71e513e26 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -18,11 +18,15 @@ from __future__ import annotations import asyncio +import json import math +import pickle import warnings -from dataclasses import dataclass, field +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 @@ -32,6 +36,7 @@ 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, @@ -115,6 +120,57 @@ def _refused(info: pytest.ExceptionInfo[RepeatedDictKeyError], column: str, key: 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 ConverterWithoutDictTraversal: + """A converter adapter exposing the conversion methods available on main.""" + + def __init__(self, **kwargs: Any) -> None: + self._converter = UniversalTypeConverter(**kwargs) + + def __getattr__(self, name: str) -> Any: + if name in ("dict_entry_fields", "logical_storage_fields"): + raise AttributeError(name) + return getattr(self._converter, name) + + +@pytest.mark.parametrize("from_spec", [False, True], ids=["direct", "from-spec"]) +def test_a_custom_converter_without_dict_traversal_can_build_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__}.ConverterWithoutDictTraversal" + _ = (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=ConverterWithoutDictTraversal() + ) + + 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") + + # ── at the door: a source ─────────────────────────────────────────────────── @@ -507,6 +563,25 @@ def cell(*keys: tuple[float, str | None]) -> list[dict[str, Any]]: 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.""" @@ -782,10 +857,11 @@ def test_a_cached_source_refuses_a_stored_row_with_a_repeated_key() -> None: 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=InMemoryArrowDatabase(), + pipeline_database=database, cache_mode=CacheMode.LOG, ) node.run() @@ -798,6 +874,20 @@ def test_a_plain_derived_source_refuses_a_stored_row_with_a_repeated_key() -> No 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")] + @pytest.mark.parametrize("cached", [False, True], ids=["direct", "fresh-cache"]) def test_a_spiraldb_source_refuses_a_batch_with_a_repeated_key( From eaf08692c6c9442ed7d098d092e73899ed3ce337 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 23:01:37 -0800 Subject: [PATCH 5/5] fix(sources): validate dict storage consistently and reuse held streams --- src/orcapod/core/sources/derived_source.py | 17 ++-- src/orcapod/core/sources/dict_keys.py | 12 +-- .../protocols/semantic_types_protocols.py | 12 +-- .../sources/test_repeated_dict_keys.py | 86 ++++++++++++++++--- .../test_float_narrowing.py | 10 +++ 5 files changed, 97 insertions(+), 40 deletions(-) diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 08ef89c5c..24f5952f4 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -700,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: @@ -711,14 +711,13 @@ def _get_stream(self) -> ArrowTableStream: self._cached_stream = stream return stream - if self._cached_table is not None: - 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": @@ -776,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 @@ -811,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 ( diff --git a/src/orcapod/core/sources/dict_keys.py b/src/orcapod/core/sources/dict_keys.py index be31f0b36..8fa2b90a9 100644 --- a/src/orcapod/core/sources/dict_keys.py +++ b/src/orcapod/core/sources/dict_keys.py @@ -23,8 +23,6 @@ from orcapod.core.operators import arrow_keys from orcapod.errors import RepeatedDictKeyError -from orcapod.protocols.semantic_types_protocols import DictStorageConverterProtocol -from orcapod.semantic_types.universal_converter import UniversalTypeConverter if TYPE_CHECKING: from orcapod.protocols.semantic_types_protocols import TypeConverterProtocol @@ -54,12 +52,10 @@ def holds_dict_type(arrow_type: pa.DataType, converter: TypeConverterProtocol) - 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 supplied.""" + """Identify a bare Arrow dict using the converter's storage rules.""" if not arrow_keys.is_list_kind(arrow_type): return None - if isinstance(converter, DictStorageConverterProtocol): - return converter.dict_entry_fields(arrow_type) - return UniversalTypeConverter.dict_entry_fields(arrow_type) + return converter.dict_entry_fields(arrow_type) def _storage_fields( @@ -67,9 +63,7 @@ def _storage_fields( ) -> tuple[pa.Field[Any], ...]: """Return the fields read individually, preserving nested logical types.""" if isinstance(arrow_type, pa.BaseExtensionType): - if isinstance(converter, DictStorageConverterProtocol): - return converter.logical_storage_fields(arrow_type) - return () + 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,) diff --git a/src/orcapod/protocols/semantic_types_protocols.py b/src/orcapod/protocols/semantic_types_protocols.py index a61c68a65..3ab03e28d 100644 --- a/src/orcapod/protocols/semantic_types_protocols.py +++ b/src/orcapod/protocols/semantic_types_protocols.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections.abc import Callable -from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable +from typing import TYPE_CHECKING, Any, Protocol from orcapod.types import DataType, Schema, SchemaLike @@ -61,16 +61,6 @@ def get_logical_type_for_python_type( self, annotation: Any ) -> "LogicalTypeProtocol | None": ... - -@runtime_checkable -class DictStorageConverterProtocol(Protocol): - """Describe Arrow storage for the source's repeated dict key check. - - A converter can implement this protocol alongside ``TypeConverterProtocol``. - Sources otherwise use the standard bare Arrow dict layout and treat logical - extensions as opaque. - """ - def dict_entry_fields( self, arrow_type: "pa.DataType" ) -> "tuple[pa.Field[Any], pa.Field[Any]] | None": diff --git a/tests/test_core/sources/test_repeated_dict_keys.py b/tests/test_core/sources/test_repeated_dict_keys.py index f0c344577..1529249ec 100644 --- a/tests/test_core/sources/test_repeated_dict_keys.py +++ b/tests/test_core/sources/test_repeated_dict_keys.py @@ -135,33 +135,37 @@ def test_repeated_dict_key_error_preserves_its_diagnostic_when_pickled( ) -class ConverterWithoutDictTraversal: - """A converter adapter exposing the conversion methods available on main.""" +class ForwardingConverter: + """A converter adapter forwarding the full conversion interface.""" - def __init__(self, **kwargs: Any) -> None: - self._converter = UniversalTypeConverter(**kwargs) + def __init__( + self, delegate: UniversalTypeConverter | None = None, **kwargs: Any + ) -> None: + self._converter = delegate or UniversalTypeConverter(**kwargs) def __getattr__(self, name: str) -> Any: - if name in ("dict_entry_fields", "logical_storage_fields"): - raise AttributeError(name) 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_custom_converter_without_dict_traversal_can_build_a_source( +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__}.ConverterWithoutDictTraversal" + 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=ConverterWithoutDictTraversal() - ) + 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]} @@ -172,6 +176,15 @@ def test_a_custom_converter_without_dict_traversal_can_build_a_source( _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 ─────────────────────────────────────────────────── @@ -502,6 +515,28 @@ def test_a_source_refuses_repeated_dict_keys_inside_user_class_fields( _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")])) @@ -921,6 +956,35 @@ def test_a_plain_derived_source_refuses_a_stored_row_with_a_repeated_key() -> No 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 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]],