diff --git a/.zed/rules b/.zed/rules index ca8eb579e..791a29c85 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1012,6 +1012,21 @@ polars, torch) keeps its library's own distinction. list_view and large_list_vie supported: a source refuses them (the Arrow hasher cannot hash them) and a raw ArrowTableStream holds them as given (ITL-1129). +Dictionary-encoded columns are refused, tags and data alike (developer, November 18, 2026, +ITL-1264: "Say it is not currently supported in orcapod. We MAY support but not immediately in +the plan"; November 19, 2026, ITL-1277: "safe default, though could be inconvenient, is to +reject working with it"). Every column of a stream (tag, data-tag, data, and Orcapod's own +system-tag, source-info, context and meta columns, which only a hand-built table could encode) +whose Arrow type is, or contains, a dictionary (list, list-view or fixed-size list item, struct +child, map key or item, run-end-encoded values, extension storage) raises InputValidationError naming each such +column with its role, its type and its decoded type (arrow_utils.decode_dictionaries), then +the pyarrow and polars ways to decode. One rule, schema_utils.dictionary_columns with +schema_utils.dictionary_columns_error, applied by ArrowTableStream.__init__ (every source +and operator result) and first by SourceStreamBuilder.build (before the key columns and the +hash); never check it elsewhere. A library value in a cell (a pandas or polars data frame with +a categorical column) is an extension column, not a dictionary, and is accepted. Supporting +dictionary columns later is ITL-1277. + Respect the Arrow types the inputs already have, normalized to their large variants (developer, November 10, 2026: large and non-large variants hash identically, so always normalize to large for consistency). Infer an Arrow type from Python values only when no Arrow type is known, and @@ -1310,21 +1325,20 @@ data. The rules: Python's precision (`time64[ns]` within a microsecond, `date64` on one day) are separate groups. A list-valued tag sorts through `(is_null, value)` pairs at every depth (`_sort_key`: Polars puts a null inside a list first). The sort frame only sees prepared columns - (`_polars_ready`: a logical type as its storage, a dictionary decoded in one place, - `_without_dictionary`, a temporal value as its integer, `float16` as `float32`, a view as + (`_polars_ready`: a logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, which Polars cannot read (it panics, which no caller can catch), every list kind, fixed-size lists included, as a large list over its prepared values). What may reach it is one rule, `_unorderable_part` (an integer, float, decimal, boolean, string, binary, date, time, timestamp, duration or null, through - logical storage, dictionary values and lists of every kind at every depth), checked from + logical storage and lists of every kind at every depth; no dictionary, since no stream + carries one, ITL-1264), checked from the schema at validation and from the table when grouping (the async path skips validation); anything else is refused, never passed through. The output is built from the input's Arrow table: `take()` in the sorted order and list arrays from group offsets (`arrow_utils.aggregated_list_array`, the array-based sibling of `build_aggregated_table`), so every key and list element is a value a member holds, bit for bit (`time64[ns]` keeps its nanoseconds, a float32 signaling NaN its bits; ITL-1248 for `GroupBy`). The hashes read a float's bits, so a group emits, for - each float key column (a logical type stored as a float, or a dictionary over floats, - included), its members' value with the smallest bit pattern at the column's own width + each float key column (a logical type stored as a float included), its members' value with the smallest bit pattern at the column's own width (`0.0` over `-0.0`, a positive NaN over a negative one; a signaling NaN has smaller bits than the canonical quiet NaN, so it wins): never the first row's, never chosen by `member_order`. Every other key is the group's first member's (equal values are identical). diff --git a/CLAUDE.md b/CLAUDE.md index 9f686af4d..d832dbf62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1056,6 +1056,21 @@ polars, torch) keeps its library's own distinction. `list_view` and `large_list_ supported: a source refuses them (the Arrow hasher cannot hash them) and a raw `ArrowTableStream` holds them as given (ITL-1129). +Dictionary-encoded columns are refused, tags and data alike (developer, November 18, 2026, +ITL-1264: "Say it is not currently supported in orcapod. We MAY support but not immediately in +the plan"; November 19, 2026, ITL-1277: "safe default, though could be inconvenient, is to +reject working with it"). Every column of a stream (tag, data-tag, data, and Orcapod's own +system-tag, source-info, context and meta columns, which only a hand-built table could encode) +whose Arrow type is, or contains, a dictionary (list, list-view or fixed-size list item, struct +child, map key or item, run-end-encoded values, extension storage) raises `InputValidationError` naming each such +column with its role, its type and its decoded type (`arrow_utils.decode_dictionaries`), then +the pyarrow and polars ways to decode. One rule, `schema_utils.dictionary_columns` with +`schema_utils.dictionary_columns_error`, applied by `ArrowTableStream.__init__` (every source +and operator result) and first by `SourceStreamBuilder.build` (before the key columns and the +hash); never check it elsewhere. A library value in a cell (a pandas or polars data frame with +a categorical column) is an extension column, not a dictionary, and is accepted. Supporting +dictionary columns later is ITL-1277. + Respect the Arrow types the inputs already have, normalized to their large variants (developer, November 10, 2026: large and non-large variants hash identically, so always normalize to large for consistency). Infer an Arrow type from Python values only when no Arrow type is known, and @@ -1357,21 +1372,20 @@ data. The rules: Python's precision (`time64[ns]` within a microsecond, `date64` on one day) are separate groups. A list-valued tag sorts through `(is_null, value)` pairs at every depth (`_sort_key`: Polars puts a null inside a list first). The sort frame only sees prepared columns - (`_polars_ready`: a logical type as its storage, a dictionary decoded in one place, - `_without_dictionary`, a temporal value as its integer, `float16` as `float32`, a view as + (`_polars_ready`: a logical type as its storage, a temporal value as its integer, `float16` as `float32`, a view as its large variant, `decimal256` as four 64-bit limbs, which Polars cannot read (it panics, which no caller can catch), every list kind, fixed-size lists included, as a large list over its prepared values). What may reach it is one rule, `_unorderable_part` (an integer, float, decimal, boolean, string, binary, date, time, timestamp, duration or null, through - logical storage, dictionary values and lists of every kind at every depth), checked from + logical storage and lists of every kind at every depth; no dictionary, since no stream + carries one, ITL-1264), checked from the schema at validation and from the table when grouping (the async path skips validation); anything else is refused, never passed through. The output is built from the input's Arrow table: `take()` in the sorted order and list arrays from group offsets (`arrow_utils.aggregated_list_array`, the array-based sibling of `build_aggregated_table`), so every key and list element is a value a member holds, bit for bit (`time64[ns]` keeps its nanoseconds, a float32 signaling NaN its bits; ITL-1248 for `GroupBy`). The hashes read a float's bits, so a group emits, for - each float key column (a logical type stored as a float, or a dictionary over floats, - included), its members' value with the smallest bit pattern at the column's own width + each float key column (a logical type stored as a float included), its members' value with the smallest bit pattern at the column's own width (`0.0` over `-0.0`, a positive NaN over a negative one; a signaling NaN has smaller bits than the canonical quiet NaN, so it wins): never the first row's, never chosen by `member_order`. Every other key is the group's first member's (equal values are identical). diff --git a/changelog.d/ITL-1264.md b/changelog.d/ITL-1264.md new file mode 100644 index 000000000..a4a88a89f --- /dev/null +++ b/changelog.d/ITL-1264.md @@ -0,0 +1,34 @@ +### Breaking changes and migration + +- A dictionary-encoded column is refused (ITL-1264, ITL-1277). Dictionary-encoded columns are + not currently supported in Orcapod, tags and data alike. A column whose Arrow type is a + `dictionary`, or holds one inside it, raises `InputValidationError` when a source or a + stream is built. This covers a tag, a data-tag and a data column, and a dictionary inside a + list, a list view or a struct field. The message names each such column with its role, its + type and the type it decodes to, and says how to decode it. +- Before, a dictionary tag was accepted and failed later and far from the cause: in + `as_table(all_info=True)`, a filter, `Batch`, `GroupBy` or a join. Or it ran through a job. + A dictionary data column was accepted with the Python type `Any`, which a typed function + refused and some filters and joins failed on. +- Such columns come from an Arrow table of your own, a pandas `Categorical` of strings, and a + polars `Categorical` or `Enum`. Decode the column first: + - with pyarrow, cast the column to the fully decoded type the error message gives. For a + plain dictionary column that is `column.type.value_type`. For a struct with a dictionary + field it is, for example, `pa.struct([("k", pa.string()), ("n", pa.int64())])`. + - three kinds need a step first: a dictionary whose values hold a dictionary (decode the + top level of each chunk with `dictionary_decode()`, then cast), a list view (cast it to a + large list of the decoded items) and a run-end-encoded column (cast its values, then + expand the runs with `pyarrow.compute.run_end_decode`). The troubleshooting page gives + each call. + - with polars, `df = df.with_columns(pl.col(name).cast(pl.String))`. + + When you replace the column, keep its field + (`table.set_column(i, field.with_type(decoded), column)`), so its nullability and + metadata stay. Or keep a data frame whole as a value in a cell: a data frame in a cell (a + library value) is not a dictionary column and is accepted as before. + +### Changed + +- `GroupBy` no longer reads a dictionary-encoded float key by the bits of its values, as + ITL-1234 describes. Such a key is now refused when its source or stream is built, so that + branch is removed. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 16ec04a90..74cd7f1a2 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -333,7 +333,7 @@ cache keys: When the members of a group hold a float key with different bits (`0.0` and `-0.0`, or NaN with another sign or payload), the group emits the one with the smallest bit pattern at the column's own width (`float16`, `float32` or `float64`; a logical type stored as a - float is read through its storage, a dictionary-encoded float through its values), for + float is read through its storage), for each key column: `0.0` over `-0.0`, and a positive NaN over a negative one. A signaling NaN has smaller bits than the canonical quiet NaN, so when a member holds one, it is the key emitted. The emitted key is always a value a member holds, bit for bit, and neither diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4ed2b6bea..109979963 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -94,6 +94,84 @@ logical types are kept, and the two variants hash identically, so no hash depend one you gave. The Arrow `list_view` and `large_list_view` types are not supported: a source refuses a column of either type. +Dictionary-encoded columns are not currently supported in Orcapod, tags and data alike. A +column whose Arrow type is a `dictionary`, or holds one inside it (a list of dictionary values, +a struct with a dictionary field), is refused with `InputValidationError` when the source or +stream is built. The message names every such column with its role (tag, data-tag or data), its +type and the type it decodes to, then says how to decode it. Such columns come from an Arrow +table of your own, a pandas `Categorical` of strings, or a polars `Categorical` or `Enum`; CSV +files, Delta tables, database tables and Python values never give one. If keeping the encoding +is not important, decode the column before building the source: + +```python +import pyarrow as pa + +from orcapod.errors import InputValidationError +from orcapod.sources import ArrowTableSource + +coded = pa.table( + { + "session": pa.array(["s1", "s2", "s1"]).dictionary_encode(), + "trial": [1, 1, 2], + "response": pa.array([0.4, 0.7, 0.5]).dictionary_encode(), + } +) +try: + ArrowTableSource(coded, tag_columns=["session", "trial"], tag_only_columns=True) +except InputValidationError as exc: + print("\n".join(str(exc).splitlines()[:3])) +# dictionary-encoded columns are not currently supported in Orcapod: +# - tag column 'session' has type dictionary (decoded: string) +# - data column 'response' has type dictionary (decoded: double) + +decoded = coded +for name in ("session", "response"): + field = decoded.schema.field(name) + value_type = field.type.value_type + # The field keeps its name, nullability and metadata; set_column returns a new table. + decoded = decoded.set_column( + decoded.schema.get_field_index(name), + field.with_type(value_type), + decoded[name].cast(value_type), + ) +source = ArrowTableSource(decoded, tag_columns=["session", "trial"], tag_only_columns=True) +print(source.as_table().schema.field("session").type) +# large_string +``` + +With polars, `pl.col("session").cast(pl.String)` decodes a `Categorical` or `Enum` column. +With pandas, `astype` with the categories' dtype decodes a `Categorical` of strings. Both +return a new frame or column: keep it before building the source. + +```python +import pandas as pd +import polars as pl + +from orcapod.sources import DataFrameSource + +frame = pl.DataFrame({"session": ["s1", "s2", "s1"], "trial": [1, 1, 2]}).with_columns( + pl.col("session").cast(pl.Categorical()) +) +frame = frame.with_columns(pl.col("session").cast(pl.String)) +print(DataFrameSource(frame, tag_columns=["session"], tag_only_columns=True).keys()) +# (('session',), ('trial',)) + +table = pd.DataFrame({"session": ["s1", "s2", "s1"], "trial": [1, 1, 2]}) +table["session"] = table["session"].astype("category") +table["session"] = table["session"].astype(table["session"].cat.categories.dtype) +print(DataFrameSource(table, tag_columns=["session"], tag_only_columns=True).keys()) +# (('session',), ('trial',)) +``` + +A pandas `Categorical` of integers that holds a missing value cannot be cast to an integer +dtype this way (fill or drop the missing values first). A pandas `Categorical` of integers +reaches the source as plain integers, so it needs no decoding. + +A data frame kept whole as a value in a cell (a pandas or polars `DataFrame` holding a +categorical column) is not a dictionary column: it is a library value, stored and hashed as one +(see [Arrays and other library values](arrays.md)), and is accepted. Supporting +dictionary-encoded columns themselves is future work (ITL-1277). + ### SpiralDB tables `SpiralDBTableSource` exposes a table in a [SpiralDB](https://spiraldb.com) project as a diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 221c81b48..690d8f6ec 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -32,6 +32,43 @@ it an explicit schema (for example `data_schema=` on `DictSource`). **Fix.** Leave at least one column out of `tag_columns`. A stream needs something to carry. +### `InputValidationError: dictionary-encoded columns are not currently supported in Orcapod: - tag column '...' has type dictionary<...> (decoded: ...)` + +**Cause.** A column, tag or data, is dictionary-encoded, or holds a dictionary inside it (for +example a list of dictionary values). This comes from an Arrow table built with +`dictionary_encode()`, a pandas `Categorical` of strings, or a polars `Categorical` or `Enum`. +Orcapod does not support such columns yet; the message names every one, with its role and the +type it decodes to. + +**Fix.** Decode the column before building the source. + +With pyarrow, keep the field's name, nullability and metadata, and keep the table that +`set_column` returns: + +- Take the field: `field = table.schema.field(name)`. +- Take the decoded type: `decoded = field.type.value_type`. For a column that holds a + dictionary inside it (a struct with a dictionary field, a list of dictionary values), use + the decoded type the message gives instead, for example + `pa.struct([("k", pa.string()), ("n", pa.int64())])`. +- Replace the column: + `table = table.set_column(table.schema.get_field_index(name), field.with_type(decoded), table[name].cast(decoded))`. + +Three kinds of column cannot be cast to their decoded type at once, so they need a step +first (each recipe is tested in `tests/test_core/sources/test_dictionary_columns_refused.py`): + +- A dictionary whose values hold a dictionary: decode the top level of each chunk first, + `pa.chunked_array([chunk.dictionary_decode() for chunk in column.chunks]).cast(decoded)`. +- A list view: cast it to a large list of the decoded items, + `column.cast(pa.large_list())` (a source refuses list views whatever they + hold). +- A run-end-encoded column: cast its values, then expand its runs, chunk by chunk: + `pc.run_end_decode(pa.RunEndEncodedArray.from_arrays(chunk.run_ends, chunk.values.cast()))`. + +With polars, keep the frame `with_columns` returns: +`df = df.with_columns(pl.col(name).cast(pl.String))`. Or keep the data frame as a value in a cell: +a pandas or polars `DataFrame` stored whole in one column is a library value, not a dictionary +column. See [Arrow types of a source](concepts/sources.md#arrow-types-of-a-source). + ### `TypeError: 'PosixPath' object is not iterable` from `CSVSource` **Cause.** `CSVSource` was given a `pathlib.Path` and no `source_id`. The file path is diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index 18f3b847e..3a439d881 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -44,15 +44,15 @@ def _is_list_kind(arrow_type: "pa.DataType") -> bool: def _value_type(arrow_type: "pa.DataType") -> "pa.DataType": - """Return the type a column's values are read as: a logical type's storage, - a dictionary's values, at the top level.""" - while True: - if isinstance(arrow_type, pa.BaseExtensionType): - arrow_type = arrow_type.storage_type - elif pa.types.is_dictionary(arrow_type): - arrow_type = arrow_type.value_type - else: - return arrow_type + """Return the type a column's values are read as: a logical type's storage, at the + top level. + + No dictionary reaches ``GroupBy``: every stream refuses a dictionary-encoded column + (ITL-1264), so a dictionary type is no orderable type here. + """ + while isinstance(arrow_type, pa.BaseExtensionType): + arrow_type = arrow_type.storage_type + return arrow_type def _is_orderable_scalar(arrow_type: "pa.DataType") -> bool: @@ -90,7 +90,7 @@ def _unorderable_part(arrow_type: "pa.DataType") -> "pa.DataType | None": nothing reaches Polars that ``_polars_ready`` does not prepare: Polars panics on some types (``decimal256``), and a panic is not an error a caller can catch. A list, large list or fixed-size list is ordered element by element, through - logical storage and dictionary values at every depth. A struct or a map (a user + logical storage at every depth. A struct or a map (a user class, a ``dict[K, V]``) has no decided order (developer, November 19, 2026), and neither has any type not named in ``_is_orderable_scalar`` (an interval, a union, a list view). @@ -111,24 +111,6 @@ def _unorderable_part(arrow_type: "pa.DataType") -> "pa.DataType | None": return None if _is_orderable_scalar(value_type) else value_type -def _without_dictionary(array: "pa.Array[Any]") -> "pa.Array[Any]": - """Decode a dictionary-encoded column to its values; any other column as it is. - - The one place ``GroupBy`` handles a dictionary-encoded tag, a float key's - included: the values each member's index points at, bits as stored. (A stream may - stop carrying dictionary-encoded tags, ITL-1264; then this goes.) - - Args: - array: A column of the input table, or its storage. - - Returns: - The decoded array. - """ - if isinstance(array, pa.DictionaryArray): - return array.dictionary_decode() - return array - - def _storage(column: "pa.ChunkedArray[Any]") -> "pa.Array[Any]": """Return a column as one array: a logical type as its storage, decoded. @@ -142,11 +124,10 @@ def _storage(column: "pa.ChunkedArray[Any]") -> "pa.Array[Any]": def _values_of(array: "pa.Array[Any]") -> "pa.Array[Any]": - """Return an array as its values are read: through logical types and dictionaries. + """Return an array as its values are read: through logical types. - The array twin of ``_value_type``: a logical type's storage and a dictionary's - values, alternately, until neither applies, so a dictionary over a logical type - (or a logical type over a dictionary) is read as validation reads its type. + The array twin of ``_value_type``: a logical type's storage, until none applies, as + validation reads its type. Args: array: A column of the input table, or the values of one. @@ -154,13 +135,9 @@ def _values_of(array: "pa.Array[Any]") -> "pa.Array[Any]": Returns: The array of plain values. """ - while True: - if isinstance(array, pa.ExtensionArray): - array = array.storage - elif isinstance(array, pa.DictionaryArray): - array = _without_dictionary(array) - else: - return array + while isinstance(array, pa.ExtensionArray): + array = array.storage + return array def _decimal256_limbs(array: "pa.Array[Any]") -> "pa.Array[Any]": @@ -205,8 +182,8 @@ def _polars_ready(array: "pa.Array[Any]") -> "pa.Array[Any]": type ``_unorderable_part`` accepts is prepared here, and no other type reaches it (the caller refuses it first): - * a logical type is its storage and a dictionary its values, alternately until - neither applies (``_values_of``, as ``_value_type`` reads the type); + * a logical type is its storage (``_values_of``, as ``_value_type`` reads the + type); * a date, time, timestamp or duration is its integer (the column's unit and zone are its type, so the integers order and compare as the values do), so no conversion of Polars' own can change it; @@ -302,8 +279,7 @@ def null_last(expr: "pl.Expr", inner: object) -> "pl.Expr": def _float_bits(array: "pa.Array[Any]") -> "pa.Array[Any] | None": """Return a float key's bit patterns, or ``None`` when the key is not a float. - A logical type stored as a float, or a dictionary over floats, is a float key, - read through its storage or its values. + A logical type stored as a float is a float key, read through its storage. Args: array: A key column's values as stored (``_storage``). diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 454781a2b..c0406e3e6 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -359,6 +359,9 @@ def build( tag_columns or a key column are not in the table, a key column's type is not allowed, a key value is null or repeated, or if neither ``source_id`` nor ``source_kind`` is given. + InputValidationError: If a column's type is, or contains, a + dictionary: dictionary-encoded columns are not currently supported + (ITL-1264, ITL-1277). """ tag_columns_tuple = tuple(tag_columns) system_tag_columns_tuple = tuple(system_tag_columns) @@ -375,6 +378,16 @@ def build( # so say so here rather than report the tag as missing (ITL-1080). schema_utils.require_names_not_meta(tag_columns_tuple) + # Dictionary-encoded columns are not currently supported (ITL-1264, + # ITL-1277). The stream refuses them too; checking first reports the + # dictionary, not a key column error, and before anything is hashed. It runs + # before the system columns are dropped: a hand-built meta, source-info or + # system-tag column holding a dictionary is refused, not dropped silently. + if found := schema_utils.dictionary_columns(table.schema): + raise schema_utils.dictionary_columns_error( + found, tag_columns_tuple, data_tags_tuple, system_tag_columns_tuple + ) + # 1. Drop system columns from raw input. table = arrow_utils.drop_system_columns(table) diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 3b5e5eae3..0d3cf00b3 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -80,6 +80,9 @@ def __init__( Raises: ValueError: If a tag column or a data-tag is not a tag column of the table, or the stream has no data column. + InputValidationError: If a column's type is, or contains, a + dictionary: dictionary-encoded columns are not currently supported + (ITL-1264, ITL-1277). """ super().__init__(**kwargs) @@ -88,6 +91,13 @@ def __init__( # Every table Orcapod presents is in its large variants (ITL-1122). table = arrow_utils.normalize_table_to_large_types(table, keep_null=True) + # Dictionary-encoded columns are not currently supported (ITL-1264, + # ITL-1277): every source and operator result becomes a stream here, so this + # refuses them all, tags and data alike. + if found := schema_utils.dictionary_columns(table.schema): + raise schema_utils.dictionary_columns_error( + found, tag_columns, data_tags, system_tag_columns + ) data_table, data_context_table = arrow_utils.split_by_column_groups( table, [constants.CONTEXT_KEY] diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 5c55ff76a..b6b14e168 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -193,6 +193,80 @@ def _normalize_field_to_large_types( return field.with_type(normalize_to_large_types(field.type, keep_null=keep_null)) +def decode_dictionaries(arrow_type: "pa.DataType") -> "pa.DataType": + """Return ``arrow_type`` with every dictionary in it replaced by its value type. + + The type a dictionary-encoded column decodes to: a dictionary at the top level or + inside a list (a list view included), a struct, a map, a union or the values of a + run-end-encoded type becomes its value type, and nested fields + keep their names, nullability and metadata. An extension type is replaced by its + decoded storage type when that storage holds a dictionary. A type that holds no + dictionary is returned as it is, so ``decode_dictionaries(t) == t`` tells whether + ``t`` contains one. + + Args: + arrow_type: An Arrow type. + + Returns: + The decoded type. + """ + # The base class: a Python extension type and a built-in one (pa.opaque, the + # canonical JSON, UUID, tensor and boolean8 types) alike. + if isinstance(arrow_type, pa.BaseExtensionType): + storage = decode_dictionaries(arrow_type.storage_type) + return arrow_type if storage == arrow_type.storage_type else storage + if pa.types.is_dictionary(arrow_type): + return decode_dictionaries(arrow_type.value_type) + if ( + pa.types.is_list(arrow_type) + or pa.types.is_large_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + or pa.types.is_list_view(arrow_type) + or pa.types.is_large_list_view(arrow_type) + ): + value_field = arrow_type.value_field + decoded = value_field.with_type(decode_dictionaries(value_field.type)) + if decoded.equals(value_field, check_metadata=True): + return arrow_type + if pa.types.is_list(arrow_type): + return pa.list_(decoded) + if pa.types.is_large_list(arrow_type): + return pa.large_list(decoded) + if pa.types.is_list_view(arrow_type): + return pa.list_view(decoded) + if pa.types.is_large_list_view(arrow_type): + return pa.large_list_view(decoded) + return pa.list_(decoded, arrow_type.list_size) + if pa.types.is_run_end_encoded(arrow_type): + values = decode_dictionaries(arrow_type.value_type) + if values == arrow_type.value_type: + return arrow_type + return pa.run_end_encoded(arrow_type.run_end_type, values) # pyright: ignore[reportArgumentType] # the stubs accept only basic value types; Arrow takes any type here + if pa.types.is_struct(arrow_type): + fields = [f.with_type(decode_dictionaries(f.type)) for f in arrow_type] + return pa.struct(fields) + if pa.types.is_map(arrow_type): + # pyarrow accepts key and item Fields here; its stubs only list types. + return pa.map_( # pyright: ignore[reportCallIssue] + arrow_type.key_field.with_type( + decode_dictionaries(arrow_type.key_field.type) + ), + arrow_type.item_field.with_type( + decode_dictionaries(arrow_type.item_field.type) + ), + keys_sorted=arrow_type.keys_sorted, + ) + if pa.types.is_union(arrow_type): + children = [ + arrow_type.field(i).with_type(decode_dictionaries(arrow_type.field(i).type)) + for i in range(arrow_type.num_fields) + ] + if isinstance(arrow_type, pa.SparseUnionType): + return pa.sparse_union(children, arrow_type.type_codes) + return pa.dense_union(children, arrow_type.type_codes) + return arrow_type + + def normalize_schema_to_large_types( schema: "pa.Schema", *, keep_null: bool = False ) -> "pa.Schema": diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 385d1d96e..78a18433a 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -5,11 +5,14 @@ import sys from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from types import UnionType -from typing import Any, Union, get_args, get_origin, get_type_hints +from typing import TYPE_CHECKING, Any, Union, get_args, get_origin, get_type_hints from orcapod.errors import InputValidationError from orcapod.types import Schema, SchemaLike +if TYPE_CHECKING: + import pyarrow as pa + logger = logging.getLogger(__name__) @@ -682,6 +685,116 @@ def require_names_not_meta(names: Collection[str]) -> None: ) +DICTIONARY_COLUMNS_NOT_SUPPORTED = ( + "dictionary-encoded columns are not currently supported in Orcapod" +) +"""The start of the error for a dictionary-encoded column (ITL-1264, ITL-1277).""" + + +def dictionary_columns( + arrow_schema: "pa.Schema", +) -> "list[tuple[str, pa.DataType, pa.DataType]]": + """Return every column whose Arrow type is, or contains, a dictionary. + + Developer decisions, November 18 and 19, 2026 (ITL-1264, ITL-1277): dictionary-encoded + columns are not currently supported in Orcapod, tags and data alike. A dictionary at + the top level of a column's type or inside it (a list, list-view or fixed-size list + item, a struct child, a map key or item, the values of a run-end-encoded type, an + extension type's storage) counts. A library value in a cell (a pandas or polars data + frame holding a categorical column) is an extension column stored as bytes, not a + dictionary, and does not count. + + ``ArrowTableStream.__init__`` (every source and operator result becomes a stream + there) and the source builder (first, before its key columns and its hash) refuse + what this finds, with ``dictionary_columns_error``. + + Args: + arrow_schema: The Arrow schema of a table about to become a stream. + + Returns: + ``(name, type, decoded type)`` for each such column, in schema order. + """ + from orcapod.utils.arrow_utils import decode_dictionaries + + found: list[tuple[str, pa.DataType, pa.DataType]] = [] + for field in arrow_schema: + decoded = decode_dictionaries(field.type) + if decoded != field.type: + found.append((field.name, field.type, decoded)) + return found + + +def dictionary_columns_error( + found: "Sequence[tuple[str, pa.DataType, pa.DataType]]", + tag_columns: Collection[str], + data_tags: Collection[str], + system_tag_columns: Collection[str] = (), +) -> InputValidationError: + """Return the error refusing the dictionary-encoded columns ``found``. + + Its job is the report, so it takes the roles it names. A user's table can hold a + dictionary only in its own columns: Orcapod writes system tags, source info, the + data context and meta columns as plain strings, so a dictionary there comes from a + hand-built table, and is refused the same way. + + Args: + found: The columns, as ``dictionary_columns`` returns them. + tag_columns: The stream's tag columns, in tag order. + data_tags: The tags that are data-tags. + system_tag_columns: Names the stream will read as system tags beside those with + the system-tag prefix. + + Returns: + An ``InputValidationError`` naming each column (tags first, in tag order, then + the others in table order) with its role, its type and the type it decodes to, + and how to decode it. + """ + from orcapod.system_constants import constants + + tags = list(tag_columns) + refs = set(data_tags) + system = set(system_tag_columns) + + def role(name: str) -> str: + if name in refs: + return "data-tag" + if name in tags: + return "tag" + if name in system or name.startswith(constants.SYSTEM_TAG_PREFIX): + return "system-tag" + if name.startswith(constants.SOURCE_PREFIX): + return "source-info" + if name == constants.CONTEXT_KEY: + return "data context" + if name.startswith(constants.META_PREFIX): + return "meta" + return "data" + + ordered = sorted( + found, + key=lambda item: (0, tags.index(item[0])) if item[0] in tags else (1, 0), + ) + lines = [ + f" - {role(name)} column {name!r} has type {arrow_type} (decoded: {decoded})" + for name, arrow_type, decoded in ordered + ] + return InputValidationError( + f"{DICTIONARY_COLUMNS_NOT_SUPPORTED}:\n" + + "\n".join(lines) + + "\nIf keeping the dictionary encoding is not important, decode each such " + "column before building the source or stream. With pyarrow, cast it to the " + "decoded type shown and replace it keeping its field: " + "table.set_column(i, field.with_type(decoded), column.cast(decoded)). Three " + "kinds need a step first: a dictionary whose values hold a dictionary " + "(chunk.dictionary_decode() on each chunk, then the cast), a list view (cast " + "it to a large list of the decoded items) and a run-end-encoded column (cast " + "its values, then expand its runs with pyarrow.compute.run_end_decode); the " + "troubleshooting page gives each call. With polars, " + "df = df.with_columns(pl.col(name).cast(pl.String)) decodes a Categorical or " + "Enum column." + ) + + def require_names_not_system(names: Collection[str]) -> None: """Raise if a tag or data column name is one a stream reads as a system column. diff --git a/tests/test_core/operators/test_group_by_arrow_values.py b/tests/test_core/operators/test_group_by_arrow_values.py index 7dc747de7..5bafe8a2d 100644 --- a/tests/test_core/operators/test_group_by_arrow_values.py +++ b/tests/test_core/operators/test_group_by_arrow_values.py @@ -637,8 +637,9 @@ def test_every_list_and_fold_follows_one_member_order(roles: str) -> None: # # CodeRabbit, PR 458: a dictionary over a logical type passed validation but its # preparation unwrapped the logical type before decoding the dictionary, then met it -# again and raised. Both now read a type through logical storage and dictionary values -# alternately, until neither applies. +# again and raised. Since ITL-1264 no stream carries a dictionary-encoded column, so +# GroupBy reads only logical storage, and a dictionary is a type it has no order for: +# validation and preparation refuse it alike. PATH_TYPE = cast( pa.BaseExtensionType, @@ -656,8 +657,9 @@ def _dictionary(values: Column, indices: list[int | None]) -> Column: return pa.DictionaryArray.from_arrays(pa.array(indices, pa.int32()), values) -def test_a_dictionary_over_a_logical_type_orders_and_keys() -> None: - """A dictionary-encoded Path tag orders the members and keys the groups.""" +def test_a_dictionary_over_a_logical_type_never_reaches_group_by() -> None: + """A dictionary-encoded Path tag is refused when the stream is built (ITL-1264), + with the way to decode it, so GroupBy never sees it.""" columns: dict[str, Column] = { "g": pa.array([1, 1, 1, 2], pa.int64()), "t1": _dictionary(_paths(["/b", "/a"]), [0, 1, None, 1]), @@ -666,22 +668,13 @@ def test_a_dictionary_over_a_logical_type_orders_and_keys() -> None: "v": pa.array(range(4), pa.int64()), } table = _table(columns) - stream = ArrowTableStream(table, tag_columns=["g", "t1", "t2"]) - # "/a" before "/b", null last; for every key path, sync and async. - for rows in ( - list(GroupBy("g")(stream).iter_data()), - async_rows(GroupBy("g"), stream), - ): - lists = sorted( - cast(list[int], data.as_table().column("v").to_pylist()[0]) - for _, data in rows - ) - assert lists == [[1, 0, 2], [3]] - for rows in ( - list(GroupBy(["t1", "t2"])(stream).iter_data()), - async_rows(GroupBy(["t2", "t1"]), stream), - ): - assert len(rows) == 4 + for tags in (["g", "t1", "t2"], ["t2", "t1", "g"]): + with pytest.raises(InputValidationError) as raised: + _ = ArrowTableStream(table, tag_columns=tags) + message = str(raised.value) + assert "dictionary-encoded columns are not currently supported" in message + assert "tag column 't1'" in message + assert "field.with_type(decoded)" in message AGREEMENT_TYPES: dict[str, Column] = { @@ -703,6 +696,12 @@ def test_a_dictionary_over_a_logical_type_orders_and_keys() -> None: "duration[s]": _ints([1, None, 2], pa.duration("s")), "null": pa.array([None, None, None], pa.null()), "logical Path": _paths(["/b", None, "/a"]), + "fixed_size_list": _fixed([[_dec(1)], None, [_dec(2)]], DEC, 1), + "large_list>": pa.LargeListArray.from_arrays( + pa.array([0, 1, 1, 2], pa.int64()), + pa.FixedSizeListArray.from_arrays(_floats([0x3C00, 0x4000], 16), 1), + ), + # Without an order (a dictionary among them: no stream carries one, ITL-1264): "dictionary": _dictionary( pa.array(["b", "a"], pa.large_string()), [0, None, 1] ), @@ -711,12 +710,6 @@ def test_a_dictionary_over_a_logical_type_orders_and_keys() -> None: pa.array([0, 1, 1, 2], pa.int64()), _dictionary(_paths(["/b", "/a"]), [0, 1]), ), - "fixed_size_list": _fixed([[_dec(1)], None, [_dec(2)]], DEC, 1), - "large_list>": pa.LargeListArray.from_arrays( - pa.array([0, 1, 1, 2], pa.int64()), - pa.FixedSizeListArray.from_arrays(_floats([0x3C00, 0x4000], 16), 1), - ), - # Without an order: "struct": pa.StructArray.from_arrays( [pa.array([1, 2, 3], pa.int64())], names=["x"] ), @@ -732,7 +725,7 @@ def test_a_dictionary_over_a_logical_type_orders_and_keys() -> None: [0, None, 1], ), } -ORDERABLE = 23 +ORDERABLE = 20 @pytest.mark.parametrize("name", list(AGREEMENT_TYPES)) diff --git a/tests/test_core/operators/test_group_by_nan_keys.py b/tests/test_core/operators/test_group_by_nan_keys.py index b951ee65a..1313f99ee 100644 --- a/tests/test_core/operators/test_group_by_nan_keys.py +++ b/tests/test_core/operators/test_group_by_nan_keys.py @@ -13,20 +13,19 @@ from __future__ import annotations -import asyncio import itertools import json import struct -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest import orcapod as op -from orcapod.channels import Channel -from orcapod.core.operators import GroupBy +from orcapod.core.streams import ArrowTableStream from orcapod.core.streams.base import StreamBase from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError from orcapod.logical_types import make_arrow_extension_type from orcapod.pipeline import ( AsyncPipelineOrchestrator, @@ -434,171 +433,89 @@ def test_a_time64_ns_key_groups_by_its_exact_value() -> None: assert out.column("v").to_pylist() == [[1], [2]] -# ── a dictionary-encoded float key ────────────────────────────────────────── - -DICTIONARY_ROWS: list[dict[str, Any]] = [ - {"k": "nan", "rid": "r1", "v": 1}, - {"k": "-nan", "rid": "r2", "v": 2}, - {"k": "payload_nan", "rid": "r3", "v": 3}, - {"k": "-0", "rid": "r4", "v": 4}, - {"k": "0", "rid": "r5", "v": 5}, - {"k": None, "rid": "r6", "v": 6}, -] - - -def _dictionary_source(rows: list[dict[str, Any]], width: int) -> StreamBase: - values = pa.array( - [None if r["k"] is None else BITS[r["k"]][width] for r in rows], - UNSIGNED[width], - ).view(FLOAT[width]) - table = pa.table( - { - "k": values.dictionary_encode(), - "rid": [r["rid"] for r in rows], - "v": [r["v"] for r in rows], - } - ) - return op.sources.ArrowTableSource( - table, - tag_columns=["k"], - tag_only_columns=True, - source_id="s", - record_id_columns="rid", - ) - - -def _dictionary_key_bits(table: pa.Table, width: int) -> list[int | None]: - column = table.column("k").combine_chunks() - assert pa.types.is_dictionary(column.type) # the output keeps the encoding - assert column.type.value_type == FLOAT[width] - return column.cast(FLOAT[width]).view(UNSIGNED[width]).to_pylist() - - -@pytest.mark.parametrize("width", [32, 64]) -def test_a_dictionary_encoded_float_key_emits_the_smallest_bits(width: int) -> None: - """A dictionary over floats is chosen by its values' bits, in every row order.""" - seen: dict[str, Any] = {} - for rows in itertools.permutations(DICTIONARY_ROWS): - grouped = _dictionary_source(list(rows), width).group_by("k") - table = grouped.as_table() - assert table.column("v").to_pylist() == [[4, 5], [1, 2, 3], [6]] - assert _dictionary_key_bits(table, width) == [ - BITS["0"][width], - BITS["nan"][width], - None, - ] - # ``all_info`` sorts by the tags, which a dictionary tag cannot be yet - # (ITL-1264): the rows come in key order already, with every system tag and - # source token. - fingerprint = { - "rows": [ - json.dumps(_with_bits(row), sort_keys=True, default=str) - for row in grouped.as_table( - columns={"system_tags": True, "source": True} - ).to_pylist() - ], - "row_hashes": _row_identity(grouped.iter_data()), - "content_hash": grouped.content_hash().to_string(), - } - if not seen: - seen = fingerprint - assert fingerprint == seen +# ── a dictionary-encoded key is refused (ITL-1264) ────────────────────────── +# +# Developer decisions, November 18 and 19, 2026: dictionary-encoded columns (tags and +# data) are not currently supported. Every stream refuses one when it is built +# (``ArrowTableStream`` and the source builder, ``schema_utils.dictionary_columns``), so a dictionary-encoded +# key never reaches ``GroupBy``: before ITL-1264, ITL-1234 chose such a float key by +# the bits of its values. A hand-built channel fed to ``async_execute`` is not a +# supported way to make a stream and is not covered. +DICTIONARY_KEYS: dict[str, "pa.Array[Any]"] = { + "string": pa.array(["b", "a", "b", "a"], pa.large_string()), + "integer": pa.array([2, 1, 2, 1], pa.int64()), + "float": pa.array([0.0, -0.0, float("nan"), 0.0], pa.float64()), +} -async def _async_grouped_rows(source: StreamBase) -> list[Any]: - """The rows of ``GroupBy("k")``'s async path, over a channel. - A pipeline job cannot carry a dictionary-typed tag yet (its stored-table sort and - nullability restore refuse a dictionary; ITL-1264), so the operator's async path - is driven directly, as ``test_async_sync_equivalence.py`` does. - """ - channel: Channel[Any] = Channel(buffer_size=64) - output: Channel[Any] = Channel(buffer_size=64) - for row in source.iter_data(): - await channel.writer.send(row) - await channel.writer.close() - await GroupBy("k").async_execute( - [channel.reader], - output.writer, - input_pipeline_hashes=[source.pipeline_hash()], - ) - return await output.reader.collect() - - -def _row_identity(rows: Any) -> list[tuple[str, str, Any]]: - """Each row's tag hash, data hash and key bits (as hex), in row order.""" - out: list[tuple[str, str, Any]] = [] - for tag, data in rows: - key = tag.as_table().column("k").combine_chunks() - key = key.cast(key.type.value_type) - unsigned = UNSIGNED[key.type.bit_width] - out.append( - ( - tag.content_hash().to_string(), - data.content_hash().to_string(), - key.view(unsigned).to_pylist(), - ) - ) - return out +def _dictionary_table(kind: str, encoded: tuple[str, ...]) -> pa.Table: + """Key ``k`` and tag ``t`` (each dictionary-encoded when named), ``rid`` and ``v``.""" + columns: dict[str, "pa.Array[Any]"] = { + "k": DICTIONARY_KEYS[kind], + "t": pa.array([1, 1, 2, 2], pa.int64()), + } + columns = { + name: column.dictionary_encode() if name in encoded else column + for name, column in columns.items() + } + columns["rid"] = pa.array(["r1", "r2", "r3", "r4"], pa.large_string()) + columns["v"] = pa.array([1, 2, 3, 4], pa.int64()) + return pa.table(list(columns.values()), names=list(columns)) -@pytest.mark.parametrize("width", [32, 64]) -def test_a_dictionary_encoded_float_key_groups_the_same_sync_and_async( - width: int, +@pytest.mark.parametrize("encoded", [("k",), ("k", "t")], ids=["key", "key_and_tag"]) +@pytest.mark.parametrize("tag_order", [("k", "t"), ("t", "k")], ids=["k_t", "t_k"]) +@pytest.mark.parametrize("tag_only", [True, False], ids=["plain", "data_tags"]) +@pytest.mark.parametrize("kind", list(DICTIONARY_KEYS)) +def test_a_dictionary_encoded_key_is_refused_before_grouping( + kind: str, tag_order: tuple[str, str], tag_only: bool, encoded: tuple[str, ...] ) -> None: - seen: list[Any] = [] - for rows in (DICTIONARY_ROWS, DICTIONARY_ROWS[::-1]): - source = _dictionary_source(list(rows), width) - sync = _row_identity(source.group_by("k").iter_data()) - asynchronous = _row_identity(asyncio.run(_async_grouped_rows(source))) - assert sorted(asynchronous, key=repr) == sorted(sync, key=repr) - assert [bits for _, _, bits in sync] == [ - [BITS["0"][width]], - [BITS["nan"][width]], - [None], - ] - if not seen: - seen = sync - assert sync == seen - - -def _null_dictionary_source(indices: list[int | None], rids: list[str]) -> StreamBase: - """A dictionary key whose null is a null index in one row and an index to a null - entry in the other: both read as null.""" - key = pa.DictionaryArray.from_arrays( - pa.array(indices, pa.int32()), pa.array([1.0, None], pa.float64()) + """A source or stream with a dictionary key is refused; nothing reaches GroupBy.""" + table = _dictionary_table(kind, encoded) + for build in ( + lambda: op.sources.ArrowTableSource( + table, + tag_columns=list(tag_order), + tag_only_columns=tag_only, + source_id="s", + record_id_columns="rid", + ), + lambda: ArrowTableStream( + table, tag_columns=list(tag_order), data_tags=() if tag_only else tag_order + ), + ): + with pytest.raises(InputValidationError) as raised: + build().group_by("k") + message = str(raised.value) + assert "dictionary-encoded columns are not currently supported" in message + # Every encoded tag is named, in tag order. + named = [name for name in tag_order if f"tag column {name!r}" in message] + assert named == [name for name in tag_order if name in encoded] + + +@pytest.mark.parametrize("tag_order", [("k", "t"), ("t", "k")], ids=["k_t", "t_k"]) +@pytest.mark.parametrize("kind", list(DICTIONARY_KEYS)) +def test_the_decoded_key_groups(kind: str, tag_order: tuple[str, str]) -> None: + """The decoding the error names gives a key GroupBy takes, in either tag order.""" + table = _dictionary_table(kind, ("k", "t")) + decoded = pa.table( + [ + column.cast(column.type.value_type) + if pa.types.is_dictionary(column.type) + else column + for column in table.columns + ], + names=table.column_names, ) - table = pa.table({"k": key, "rid": rids, "v": [int(r[1:]) for r in rids]}) - return op.sources.ArrowTableSource( - table, - tag_columns=["k"], + grouped = op.sources.ArrowTableSource( + decoded, + tag_columns=list(tag_order), tag_only_columns=True, source_id="s", record_id_columns="rid", + ).group_by("k") + members = cast(list[list[int]], grouped.as_table().column("v").to_pylist()) + assert sorted(len(group) for group in members) == ( + [1, 3] if kind == "float" else [2, 2] ) - - -@pytest.mark.parametrize( - ("indices", "rids"), - [([None, 1], ["r1", "r2"]), ([1, None], ["r2", "r1"])], - ids=["null_index_first", "null_entry_first"], -) -def test_a_null_dictionary_key_is_emitted_as_a_null( - indices: list[int | None], rids: list[str] -) -> None: - """Whichever null comes first, the group's key is a null index. - - ``DropNulls`` reads the top-level validity, which an index to a null entry does - not carry: without this, the row order decided whether the group was dropped. - """ - source = _null_dictionary_source(indices, rids) - grouped = source.group_by("k") - key = grouped.as_table().column("k").combine_chunks() - assert isinstance(key, pa.DictionaryArray) - assert key.indices.to_pylist() == [None] - assert grouped.drop_nulls(["k"]).as_table().num_rows == 0 - for rows in (list(grouped.iter_data()), asyncio.run(_async_grouped_rows(source))): - [(tag, _)] = rows - tag_key = tag.as_table().column("k").combine_chunks() - assert isinstance(tag_key, pa.DictionaryArray) - assert tag_key.indices.to_pylist() == [None] diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py new file mode 100644 index 000000000..7d45d4cff --- /dev/null +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -0,0 +1,827 @@ +"""A dictionary-encoded column is refused when a source or stream is built (ITL-1264, ITL-1277). + +Developer decisions: dictionary-encoded tags are not currently supported (November 18, +2026), and neither are dictionary-encoded data columns, for now (November 19, 2026, on +ITL-1277: "safe default, though could be inconvenient, is to reject working with it. It'd +be useful if rejection error can suggest how to make it work if staying dict encoding +isn't critical for the user"). Every column of a stream whose Arrow type is, or contains, +a dictionary (top level, list, list-view, fixed-size list, struct child, map key or item, +extension storage) is refused with ``InputValidationError``. The message names each such +column with its role (tag, data-tag, data, or one of Orcapod's own column kinds), its +type and the type it decodes to, then how to decode it. The rule is +``schema_utils.dictionary_columns`` and ``dictionary_columns_error``, applied by +``ArrowTableStream`` (every source and operator result becomes one) and first by the +source builder, so a source reports the dictionary before its key columns and its hash. + +A library value in a cell (a pandas or polars data frame holding a categorical column) +is an extension column stored as bytes, not a dictionary: it is accepted and hashes as it +did before. +""" + +from __future__ import annotations + +import asyncio +import re +from typing import Any + +import pandas as pd +import polars as pl +import pyarrow as pa +import pytest + +from orcapod.core.sources import ( + ArrowTableSource, + DataFrameSource, + DictSource, + PollingSource, +) +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ( + InputValidationError, + RowIdentifierError, + SourceCheckFailedWarning, +) +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.types import Cursor, PollingConfig, Schema +from orcapod.contexts import get_default_context +from orcapod.utils import schema_utils +from orcapod.utils.arrow_utils import decode_dictionaries + +NOT_SUPPORTED = "dictionary-encoded columns are not currently supported in Orcapod" + +# The values of each column, by kind: tags ``a`` and ``b``, data ``v`` and ``w``. Every +# kind has two distinct values per tag column so the rows stay distinct whichever +# columns are encoded. +VALUES: dict[str, tuple[pa.DataType, dict[str, list[Any]]]] = { + "string": ( + pa.string(), + { + "a": ["x", "y", "x"], + "b": ["p", "p", "q"], + "v": ["r", "s", "r"], + "w": ["m", "n", "n"], + }, + ), + "int": ( + pa.int64(), + {"a": [1, 2, 1], "b": [7, 7, 8], "v": [3, 4, 3], "w": [5, 5, 6]}, + ), + "float": ( + pa.float64(), + { + "a": [1.5, 2.5, 1.5], + "b": [0.25, 0.25, 0.75], + "v": [3.5, 4.5, 3.5], + "w": [5.5, 5.5, 6.5], + }, + ), +} +TAG_ORDERS = [("a", "b"), ("b", "a")] +# Tags, data, both, one of each, all. +ENCODED = [("a",), ("a", "b"), ("v",), ("v", "w"), ("b", "w"), ("a", "b", "v", "w")] +DATA = ("v", "w") +ALL: tuple[str, ...] = ("a", "b", "v", "w") + + +def _table(kind: str, encoded: tuple[str, ...], data_first: bool = False) -> pa.Table: + """Tags ``a``, ``b`` and data ``v``, ``w`` (those in ``encoded`` dictionary-encoded), + in one of two layouts.""" + value_type, values = VALUES[kind] + columns: dict[str, pa.Array[Any]] = {} + for name in ALL: + array = pa.array(values[name], value_type) + columns[name] = array.dictionary_encode() if name in encoded else array + order = ["v", "w", "a", "b"] if data_first else ["a", "b", "v", "w"] + return pa.table([columns[name] for name in order], names=order) + + +def _expected( + tags: tuple[str, ...], encoded: tuple[str, ...], data_tags: tuple[str, ...] +) -> list[tuple[str, str]]: + """The ``(role, name)`` the message names, in its order: tags in tag order, then data + columns in table order (``v`` before ``w`` in both layouts).""" + out = [("data-tag" if t in data_tags else "tag", t) for t in tags if t in encoded] + out += [("data", d) for d in DATA if d in encoded] + return out + + +def _assert_refused( + exc: BaseException, expected: list[tuple[str, str]], all_names: tuple[str, ...] +) -> None: + """The message says dictionary columns are not supported, names each encoded column + with its role and type in the expected order, names no other column, and says how + to decode.""" + assert isinstance(exc, InputValidationError) + assert not isinstance(exc, RowIdentifierError) + message = str(exc) + assert message.startswith(NOT_SUPPORTED) + positions = [ + message.index(f"- {role} column {name!r} has type dictionary<") + for role, name in expected + ] + assert positions == sorted(positions) + named = {name for _, name in expected} + for name in all_names: + if name not in named: + assert f"column {name!r}" not in message + assert ( + "table.set_column(i, field.with_type(decoded), column.cast(decoded))" in message + ) + assert "chunk.dictionary_decode()" in message + assert "pyarrow.compute.run_end_decode" in message + assert "df = df.with_columns(pl.col(name).cast(pl.String))" in message + + +# ── a raw ArrowTableStream ────────────────────────────────────────────────── + + +@pytest.mark.parametrize("data_first", [False, True], ids=["tags-first", "data-first"]) +@pytest.mark.parametrize( + "data_tags", [(), ("a",), ("a", "b")], ids=["plain", "a", "ab"] +) +@pytest.mark.parametrize("encoded", ENCODED, ids="-".join) +@pytest.mark.parametrize("tags", TAG_ORDERS, ids="-".join) +@pytest.mark.parametrize("kind", sorted(VALUES)) +def test_a_raw_stream_refuses_dictionary_columns( + kind: str, + tags: tuple[str, ...], + encoded: tuple[str, ...], + data_tags: tuple[str, ...], + data_first: bool, +) -> None: + with pytest.raises(InputValidationError) as info: + ArrowTableStream( + _table(kind, encoded, data_first), tag_columns=tags, data_tags=data_tags + ) + _assert_refused(info.value, _expected(tags, encoded, data_tags), ALL) + + +# ── ArrowTableSource ──────────────────────────────────────────────────────── + + +TAG_ONLY: dict[str, tuple[Any, tuple[str, ...]]] = { + "tag-only": (True, ()), + "data-tags": (False, ("a", "b")), + "a-plain": (["a"], ("b",)), + "b-plain": (["b"], ("a",)), +} + + +@pytest.mark.parametrize("roles", sorted(TAG_ONLY)) +@pytest.mark.parametrize("encoded", ENCODED, ids="-".join) +@pytest.mark.parametrize("tags", TAG_ORDERS, ids="-".join) +@pytest.mark.parametrize("kind", sorted(VALUES)) +def test_an_arrow_table_source_refuses_dictionary_columns( + kind: str, tags: tuple[str, ...], encoded: tuple[str, ...], roles: str +) -> None: + tag_only_columns, data_tags = TAG_ONLY[roles] + with pytest.raises(InputValidationError) as info: + ArrowTableSource( + _table(kind, encoded), + tag_columns=list(tags), + tag_only_columns=tag_only_columns, + ) + _assert_refused(info.value, _expected(tags, encoded, data_tags), ALL) + + +@pytest.mark.parametrize("record_id_columns", [["a"], ["b", "a"], ["a", "b"]]) +@pytest.mark.parametrize("kind", ["string", "int"]) +def test_a_dictionary_key_column_is_reported_as_a_dictionary_column( + kind: str, record_id_columns: list[str] +) -> None: + """The builder checks first: not the key-column error, which would say a key must + hold strings or integers although the dictionary's values are.""" + with pytest.raises(InputValidationError) as info: + ArrowTableSource( + _table(kind, ("a",)), + tag_columns=["a", "b"], + tag_only_columns=True, + record_id_columns=record_id_columns, + ) + _assert_refused(info.value, [("tag", "a")], ALL) + + +@pytest.mark.parametrize("encoded", [("b",), ("w",)], ids=["tag", "data"]) +def test_a_dictionary_column_is_refused_before_anything_is_hashed( + monkeypatch: pytest.MonkeyPatch, encoded: tuple[str, ...] +) -> None: + from orcapod.core.sources import stream_builder + + def _never(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("the source hashed before checking its columns") + + monkeypatch.setattr(stream_builder, "row_identifiers", _never) + # No table or column hash either (the default source id, a key column check). + monkeypatch.setattr(get_default_context().arrow_hasher, "hash_table", _never) + with pytest.raises(InputValidationError, match=NOT_SUPPORTED): + ArrowTableSource( + _table("string", encoded), tag_columns=["a", "b"], tag_only_columns=True + ) + + +def test_the_message_gives_each_role_type_and_decoded_type() -> None: + table = pa.table( + { + "a": pa.array(["x", "y"]).dictionary_encode(), + "b": pa.array([1.5, 2.5]) + .dictionary_encode() + .cast(pa.dictionary(pa.int8(), pa.float64())), + "v": pa.array([1, 2]).dictionary_encode(), + "w": [1, 2], + } + ) + with pytest.raises(InputValidationError) as info: + ArrowTableSource(table, tag_columns=["b", "a"], tag_only_columns=["b"]) + message = str(info.value) + assert message.splitlines()[:4] == [ + f"{NOT_SUPPORTED}:", + " - tag column 'b' has type dictionary (decoded: double)", + " - data-tag column 'a' has type dictionary (decoded: string)", + " - data column 'v' has type dictionary (decoded: int64)", + ] + assert "column 'w'" not in message + + +# ── Orcapod's own column kinds in a hand-built table ───────────────────────── + + +@pytest.mark.parametrize( + ("column", "role", "kwargs"), + [ + ("rid", "system-tag", {"system_tag_columns": ["rid"]}), + ("_tag_source_id::abc", "system-tag", {}), + ("_source_v", "source-info", {}), + ("__note", "meta", {}), + ("_context_key", "data context", {}), + ], + ids=["named-system-tag", "prefixed-system-tag", "source-info", "meta", "context"], +) +def test_a_raw_stream_refuses_a_dictionary_in_orcapods_own_columns( + column: str, role: str, kwargs: dict[str, Any] +) -> None: + """Orcapod writes these as plain strings; only a hand-built table can hold a + dictionary there, and it is refused the same way, with its role.""" + table = pa.table( + { + "a": ["x", "y"], + "b": ["p", "q"], + "v": [1.0, 2.0], + "w": [3, 4], + column: pa.array(["c1", "c2"]).dictionary_encode(), + } + ) + with pytest.raises(InputValidationError) as info: + ArrowTableStream(table, tag_columns=["a", "b"], **kwargs) + assert f"- {role} column {column!r} has type dictionary<" in str(info.value) + + +OWN_COLUMNS = { + "__note": "meta", + "_source_v": "source-info", + "_tag_source_id::abc": "system-tag", +} + + +@pytest.mark.parametrize( + "own", [("__note",), ("_source_v",), ("_tag_source_id::abc",), tuple(OWN_COLUMNS)] +) +@pytest.mark.parametrize("with_user_column", [False, True], ids=["alone", "beside-v"]) +@pytest.mark.parametrize("own_first", [False, True], ids=["user-first", "own-first"]) +def test_a_source_refuses_a_dictionary_in_hand_built_system_columns( + own: tuple[str, ...], with_user_column: bool, own_first: bool +) -> None: + """The builder checks before it drops system columns (CodeRabbit on PR 455): a + dictionary-free system column is still stripped, a dictionary one is refused.""" + user: dict[str, pa.Array[Any]] = { + "a": pa.array(["x", "y"]), + "b": pa.array(["p", "q"]), + "v": pa.array(["r", "s"]).dictionary_encode() + if with_user_column + else pa.array(["r", "s"]), + "w": pa.array([3, 4]), + } + system = {name: pa.array(["c1", "c2"]).dictionary_encode() for name in own} + columns = {**system, **user} if own_first else {**user, **system} + table = pa.table(list(columns.values()), names=list(columns)) + with pytest.raises(InputValidationError) as info: + ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + message = str(info.value) + for name in own: + assert f"- {OWN_COLUMNS[name]} column {name!r} has type dictionary<" in message + assert ("- data column 'v'" in message) == with_user_column + + +def test_a_dictionary_free_system_column_is_still_stripped() -> None: + table = pa.table( + { + "a": ["x", "y"], + "__note": ["n1", "n2"], + "_source_v": ["s1", "s2"], + "v": [1, 2], + } + ) + source = ArrowTableSource(table, tag_columns=["a"], tag_only_columns=True) + assert source.keys() == (("a",), ("v",)) + + +def test_an_opaque_type_over_a_dictionary_is_refused() -> None: + """``pa.opaque`` is a built-in extension type, not a Python ``pa.ExtensionType``.""" + opaque = pa.opaque(pa.dictionary(pa.int32(), pa.string()), "label", "vendor") + storage = pa.array(["x", "y"]).dictionary_encode() + column = pa.ExtensionArray.from_storage(opaque, storage) + table = pa.table({"a": ["p", "q"], "o": column, "v": [1, 2]}) + with pytest.raises(InputValidationError, match="- data column 'o' has type"): + ArrowTableStream(table, tag_columns=["a"]) + + +# ── data frames ───────────────────────────────────────────────────────────── + + +FRAME_COLUMNS: dict[str, list[Any]] = { + "a": ["x", "y", "x"], + "b": ["p", "p", "q"], + "v": ["r", "s", "r"], + "w": [1, 2, 3], +} +# String columns only: a pandas Categorical of integers reaches the source as plain +# integers (the frame goes through polars, which has no integer Categorical). +FRAME_ENCODED = [("a",), ("v",), ("a", "b"), ("b", "v")] + + +def _pandas(encoded: tuple[str, ...]) -> pd.DataFrame: + frame = pd.DataFrame(FRAME_COLUMNS) + for name in encoded: + frame[name] = frame[name].astype("category") + return frame + + +def _polars(encoded: tuple[str, ...], dtype: str) -> pl.DataFrame: + frame = pl.DataFrame(FRAME_COLUMNS) + target = ( + pl.Categorical() + if dtype == "Categorical" + else pl.Enum(["p", "q", "r", "s", "x", "y"]) + ) + return frame.with_columns([pl.col(name).cast(target) for name in encoded]) + + +@pytest.mark.parametrize( + "tag_only_columns", [True, False], ids=["tag-only", "data-tags"] +) +@pytest.mark.parametrize("encoded", FRAME_ENCODED, ids="-".join) +@pytest.mark.parametrize("tags", TAG_ORDERS, ids="-".join) +@pytest.mark.parametrize("frame_kind", ["pandas", "polars-Categorical", "polars-Enum"]) +def test_a_data_frame_source_refuses_categorical_columns( + frame_kind: str, + tags: tuple[str, ...], + encoded: tuple[str, ...], + tag_only_columns: bool, +) -> None: + """A pandas Categorical and a polars Categorical or Enum arrive dictionary-encoded.""" + frame: Any = ( + _pandas(encoded) + if frame_kind == "pandas" + else _polars(encoded, frame_kind.split("-")[1]) + ) + with pytest.raises(InputValidationError) as info: + DataFrameSource( + frame, tag_columns=list(tags), tag_only_columns=tag_only_columns + ) + data_tags = () if tag_only_columns else tags + _assert_refused(info.value, _expected(tags, encoded, data_tags), ALL) + + +# ── a polling source's batches, read sync and async ───────────────────────── + + +class _CategoricalImpl: + """Fetches one batch whose column ``column`` is a polars Categorical.""" + + def __init__(self, column: str) -> None: + self.column = column + + def identity(self) -> str: + return f"categorical-impl-{self.column}" + + def to_config(self) -> None: + return None + + @classmethod + def from_config(cls, config: Any) -> _CategoricalImpl: + return cls("a") + + def schema(self) -> Schema: + # Declared, so building a pipeline over the source reads no batch: the job + # run reads the first one. + return Schema({"a": str, "b": str, "v": float, "s": str}) + + async def poll(self, cursor: Cursor[int] | None = None) -> bool: + return cursor is None + + async def fetch(self, cursor: Cursor[int] | None = None) -> tuple[Cursor[int], Any]: + if cursor is not None: + return Cursor(value=1), {} + frame = pl.DataFrame( + {"a": ["x", "y"], "b": ["p", "q"], "v": [1.0, 2.0], "s": ["m", "n"]} + ).with_columns(pl.col(self.column).cast(pl.Categorical())) + return Cursor(value=1), frame + + async def close(self) -> None: + return None + + +def _polling_source(column: str) -> PollingSource[int]: + return PollingSource( + _CategoricalImpl(column), + tag_columns=["b", "a"], + record_id_columns="b", + polling_config=PollingConfig(duration=0.01), + ) + + +# A polling source keeps its tags plain (ITL-1023). +POLLED = pytest.mark.parametrize( + ("column", "role"), [("a", "tag"), ("s", "data")], ids=["tag", "data"] +) + + +@POLLED +def test_a_polling_source_refuses_a_categorical_column_on_a_sync_read( + column: str, role: str +) -> None: + with pytest.raises(InputValidationError) as info: + _polling_source(column).as_table() + _assert_refused(info.value, [(role, column)], ("a", "b", "v", "s")) + + +@POLLED +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_a_job_over_a_polling_source_refuses_a_categorical_column( + orchestrator: type, column: str, role: str +) -> None: + job = PipelineJob(name="itl1264", database=InMemoryArrowDatabase()) + with job: + _polling_source(column).select_data_columns("v", label="selected") + # The run's start-of-run check warns and goes on; the read of the batch raises. + with ( + pytest.warns(SourceCheckFailedWarning, match=NOT_SUPPORTED), + pytest.raises(InputValidationError, match=f"{role} column '{column}'"), + ): + if orchestrator is AsyncPipelineOrchestrator: + asyncio.run(job.run_async()) + else: + job.run(orchestrator=orchestrator()) + + +# ── a column whose type contains a dictionary ─────────────────────────────── + + +def _nested(kind: str) -> pa.Array[Any]: + encoded = pa.array(["x", "y", "x"]).dictionary_encode() + if kind == "list": + return pa.LargeListArray.from_arrays( + pa.array([0, 1, 2, 3], pa.int64()), encoded + ) + if kind == "struct": + return pa.StructArray.from_arrays( + [encoded, pa.array([1, 2, 3])], names=["k", "n"] + ) + if kind == "list_view": + return pa.ListViewArray.from_arrays( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the pyarrow stubs omit from_arrays' sizes argument + pa.array([0, 1, 2], pa.int32()), pa.array([1, 1, 1], pa.int32()), encoded + ) + if kind == "run_end_encoded": + return pa.RunEndEncodedArray.from_arrays( + pa.array([1, 2, 3], pa.int32()), encoded + ) + if kind == "large_list_view": + return pa.LargeListViewArray.from_arrays( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the pyarrow stubs omit from_arrays' sizes argument + pa.array([0, 1, 2], pa.int64()), pa.array([1, 1, 1], pa.int64()), encoded + ) + raise ValueError(kind) + + +DECODED = { + "list": "large_list", + "struct": "struct", + "list_view": "list_view", + "large_list_view": "large_list_view", + "run_end_encoded": "run_end_encoded", +} +NESTED_KINDS = pytest.mark.parametrize("kind", sorted(DECODED)) + +# Several items (CodeRabbit on PR 455): two tags and two data columns, both tag orders, +# two table layouts, and the three roles of the tags. +NESTED_TAG_ORDERS = [("a", "b"), ("b", "a")] +NESTED_LAYOUTS = { + "tags_first": ["a", "b", "v", "w"], + "interleaved": ["v", "a", "w", "b"], +} +NESTED_ROLES = ["plain", "data_tags", "mixed"] +NESTED_ARRANGEMENTS = pytest.mark.parametrize( + ("tag_order", "layout", "roles"), + [ + (order, layout, roles) + for order in NESTED_TAG_ORDERS + for layout in NESTED_LAYOUTS + for roles in NESTED_ROLES + ], + ids=lambda value: "-".join(value) if isinstance(value, tuple) else str(value), +) + + +def _nested_table(nested: pa.Array[Any], column: str, layout: str) -> pa.Table: + """Tags ``a``, ``b`` and data ``v``, ``w`` in ``layout``; ``column`` holds ``nested``.""" + columns: dict[str, pa.Array[Any]] = { + "a": pa.array(["x", "y", "z"], pa.large_string()), + "b": pa.array([1, 2, 3], pa.int64()), + "v": pa.array([1.0, 2.0, 3.0], pa.float64()), + "w": pa.array(["p", "q", "r"], pa.large_string()), + } + columns[column] = nested + names = NESTED_LAYOUTS[layout] + return pa.table([columns[name] for name in names], names=names) + + +def _build_nested( + build: str, table: pa.Table, tag_order: tuple[str, str], roles: str +) -> None: + """Build ``table`` as a source or a raw stream with its tags in ``roles``. + + ``mixed`` keeps ``b`` plain and makes ``a`` a data-tag. + """ + if build == "source": + tag_only: bool | list[str] = { + "plain": True, + "data_tags": False, + "mixed": ["b"], + }[roles] + ArrowTableSource(table, tag_columns=list(tag_order), tag_only_columns=tag_only) + else: + data_tags = {"plain": (), "data_tags": tag_order, "mixed": ("a",)}[roles] + ArrowTableStream(table, tag_columns=list(tag_order), data_tags=data_tags) + + +@NESTED_ARRANGEMENTS +@pytest.mark.parametrize("column", ["a", "w"], ids=["in-tag", "in-data"]) +@pytest.mark.parametrize("build", ["source", "stream"]) +@NESTED_KINDS +def test_a_column_containing_a_dictionary_is_refused( + kind: str, + build: str, + column: str, + tag_order: tuple[str, str], + layout: str, + roles: str, +) -> None: + table = _nested_table(_nested(kind), column, layout) + with pytest.raises(InputValidationError) as info: + _build_nested(build, table, tag_order, roles) + message = str(info.value) + assert NOT_SUPPORTED in message + assert re.search(rf"column '{column}' has type \S.*dictionary<", message) + if column == "w": + assert "- data column 'w'" in message + if build == "source": + assert f"(decoded: {DECODED[kind]})" in message + for other in set(ALL) - {column}: + assert f"column {other!r}" not in message + + +def _plain_list_view(kind: str) -> pa.Array[Any]: + plain = pa.array(["x", "y", "x"]) + offsets, sizes = ( + (pa.array([0, 1, 2], pa.int32()), pa.array([1, 1, 1], pa.int32())) + if kind == "list_view" + else (pa.array([0, 1, 2], pa.int64()), pa.array([1, 1, 1], pa.int64())) + ) + return ( + pa.ListViewArray if kind == "list_view" else pa.LargeListViewArray + ).from_arrays(offsets, sizes, plain) # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the pyarrow stubs omit from_arrays' sizes argument + + +@NESTED_ARRANGEMENTS +@pytest.mark.parametrize("column", ["a", "w"], ids=["in-tag", "in-data"]) +@pytest.mark.parametrize("kind", ["list_view", "large_list_view"]) +def test_a_list_view_without_a_dictionary_is_handled_as_before( + kind: str, column: str, tag_order: tuple[str, str], layout: str, roles: str +) -> None: + """Only a dictionary inside a list view is refused here (CodeRabbit on PR 455). + + A list view of plain values keeps what it had: a raw stream holds it as given, + and a source refuses it because the Arrow hasher cannot hash it (ITL-1129). + """ + table = _nested_table(_plain_list_view(kind), column, layout) + _build_nested("stream", table, tag_order, roles) + with pytest.raises(ValueError, match="the Arrow hasher refused") as info: + _build_nested("source", table, tag_order, roles) + assert NOT_SUPPORTED not in str(info.value) + + +# ── the decoding the message suggests works ───────────────────────────────── + + +@pytest.mark.parametrize("kind", sorted(VALUES)) +def test_a_table_decoded_with_pyarrow_builds(kind: str) -> None: + table = _table(kind, ALL) + for name in ("b", "w", "a", "v"): + index = table.schema.get_field_index(name) + table = table.set_column( + index, name, table[name].cast(table[name].type.value_type) + ) + source = ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + assert source.as_table(all_info=True).num_rows == 3 + + +def _decoded_type(message: str, name: str) -> str: + """The decoded type the error message gives for column ``name``.""" + line = next( + text for text in message.splitlines() if f"column {name!r} has type" in text + ) + return line.rsplit("(decoded: ", 1)[1].rstrip(")") + + +@pytest.mark.parametrize("kind", ["list", "struct"]) +def test_a_nested_dictionary_decoded_as_the_message_says_builds(kind: str) -> None: + """The recipe for a column holding a dictionary inside it: cast it to the decoded type + the message gives, keeping the field (nullability and metadata). + + Lists and structs: pyarrow cannot cast a list view or a run-end-encoded column, and a + source refuses those types whatever they hold (the Arrow hasher cannot hash them). + """ + nested = _nested(kind) + table = _nested_table(nested, "w", "tags_first") + schema = table.schema.set( + table.schema.get_field_index("w"), + table.schema.field("w").with_nullable(False).with_metadata({"note": "kept"}), + ) + table = pa.Table.from_arrays(table.columns, schema=schema) + with pytest.raises(InputValidationError) as info: + ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + assert _decoded_type(str(info.value), "w") == DECODED[kind] + decoded = decode_dictionaries(table.schema.field("w").type) + assert str(decoded) == DECODED[kind] + field = table.schema.field("w") + table = table.set_column( + table.schema.get_field_index("w"), + field.with_type(decoded), + table["w"].cast(decoded), + ) + stream = ArrowTableStream(table, tag_columns=["a", "b"]) + kept = stream.as_table().schema.field("w") + assert not kept.nullable + assert (kept.metadata or {}).get(b"note") == b"kept" + + +def _replace(table: pa.Table, name: str, column: Any) -> pa.Table: + """Replace a column keeping its field: name, nullability and metadata.""" + field = table.schema.field(name) + return table.set_column( + table.schema.get_field_index(name), field.with_type(column.type), column + ) + + +def _recover(kind: str, column: Any) -> Any: + """The recipe the message and the troubleshooting page give, per kind of column.""" + import pyarrow.compute as pc + + if kind == "dictionary of a dictionary": + # The values hold a dictionary: decode the top level first, then cast. + return pa.chunked_array( + [chunk.dictionary_decode() for chunk in column.chunks] + ).cast(decode_dictionaries(column.type)) + if kind == "list_view": + # A source refuses list views; a large list of the decoded items it accepts. + return column.cast(pa.large_list(decode_dictionaries(column.type.value_type))) + if kind == "run_end_encoded": + # Decode the values, then expand the runs. + return pa.chunked_array( + [ + pc.run_end_decode( # pyright: ignore[reportAttributeAccessIssue] # a generated compute function the stubs omit + pa.RunEndEncodedArray.from_arrays( + chunk.run_ends, + chunk.values.cast(decode_dictionaries(chunk.values.type)), + ) + ) + for chunk in column.chunks + ] + ) + return column.cast(decode_dictionaries(column.type)) + + +def _special(kind: str) -> pa.Array[Any]: + encoded = pa.array(["x", "y"]).dictionary_encode() + if kind == "dictionary of a dictionary": + values = pa.StructArray.from_arrays([encoded], names=["k"]) + return pa.DictionaryArray.from_arrays(pa.array([0, 1, 0], pa.int32()), values) + if kind == "list_view": + return pa.ListViewArray.from_arrays( # pyright: ignore[reportCallIssue, reportUnknownVariableType] # the pyarrow stubs omit from_arrays' sizes argument + pa.array([0, 1, 0], pa.int32()), pa.array([1, 1, 2], pa.int32()), encoded + ) + if kind == "run_end_encoded": + return pa.RunEndEncodedArray.from_arrays(pa.array([1, 3], pa.int32()), encoded) + raise ValueError(kind) + + +@pytest.mark.parametrize( + "kind", ["dictionary of a dictionary", "list_view", "run_end_encoded"] +) +def test_the_columns_a_plain_cast_cannot_decode_have_a_recipe_that_works( + kind: str, +) -> None: + """pyarrow cannot cast these to their decoded type; the stated steps decode them.""" + table = pa.table( + { + "a": ["p", "q", "r"], + "b": [1, 2, 3], + "c": _special(kind), + "w": [0.5, 1.5, 2.5], + } + ) + with pytest.raises(InputValidationError): + ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + with pytest.raises(pa.ArrowNotImplementedError): + table["c"].cast(decode_dictionaries(table.schema.field("c").type)) + decoded = _replace(table, "c", _recover(kind, table["c"])) + assert not schema_utils.dictionary_columns(decoded.schema) + source = ArrowTableSource(decoded, tag_columns=["a", "b"], tag_only_columns=True) + assert source.as_table().num_rows == 3 + + +@pytest.mark.parametrize("dtype", ["Categorical", "Enum"]) +def test_a_frame_decoded_with_polars_builds(dtype: str) -> None: + frame = _polars(("a", "b", "v"), dtype).with_columns( + pl.col("a", "b", "v").cast(pl.String) + ) + source = DataFrameSource(frame, tag_columns=["b", "a"], tag_only_columns=True) + assert source.as_table(all_info=True).num_rows == 3 + + +def test_a_frame_decoded_with_pandas_builds() -> None: + frame = _pandas(("a", "b", "v")) + for name in ("a", "b", "v"): + frame[name] = frame[name].astype(frame[name].cat.categories.dtype) + source = DataFrameSource(frame, tag_columns=["a", "b"], tag_only_columns=True) + assert source.as_table(all_info=True).num_rows == 3 + + +# ── no operator makes a dictionary column ─────────────────────────────────── + + +def test_tag_by_never_sees_a_dictionary_data_column() -> None: + """The source holding one is refused, so ``TagBy`` cannot be applied to it.""" + with pytest.raises(InputValidationError, match="- data column 'v'"): + ArrowTableSource( + _table("float", ("v",)), tag_columns=["a", "b"], tag_only_columns=True + ) + + +# ── a library value in a cell is not a dictionary column ───────────────────── + +# The data hash of each row, computed on main (84cc52cd) before this change. +CELL_HASHES = { + "pandas": "arrow_v1:00000244fe7fa574e19c2f88db92ca42d2391aa3892d3f2f27a338d758531bae57cf46", + "polars": "arrow_v1:00000202d6fc73547e8eb457800df1c8d39b5cee3e0168b779ceb02a70e7112f7523fb", +} + + +def _frames() -> dict[str, Any]: + return { + "pandas": pd.DataFrame( + { + "c": pd.Categorical(["x", "y", "x"], categories=["y", "x", "z"]), + "n": [1, 2, 3], + } + ), + "polars": pl.DataFrame( + { + "c": pl.Series(["p", None, "q"], dtype=pl.Categorical), + "e": pl.Series(["x", "y", None], dtype=pl.Enum(["y", "x", "z"])), + } + ), + } + + +@pytest.mark.parametrize("library", sorted(CELL_HASHES)) +def test_a_data_frame_value_with_categorical_columns_is_accepted_and_hashes_as_before( + library: str, +) -> None: + """The boundary: a data frame in a cell is a library value, stored as bytes in an + extension column, so its categorical columns are not a dictionary column.""" + source = DictSource( + [{"k": "r1", "f": _frames()[library]}], + tag_columns=["k"], + tag_only_columns=True, + source_id="cells", + ) + assert not pa.types.is_dictionary(source.as_table().schema.field("f").type) + ((_, data),) = list(source.iter_data()) + assert data.content_hash().to_string() == CELL_HASHES[library] diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index ce8789e7c..26bbddda1 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -9,6 +9,7 @@ apply_column_config, column_arrow_type, concat_tables_by_name, + decode_dictionaries, infer_schema_nullable, make_schema_non_nullable, normalize_extension_columns, @@ -1069,3 +1070,126 @@ def test_data_schema_matches_the_serialized_depth(self) -> None: data = Data({"x": 1}, source_info={"x": [[], [["a"]]]}) schema = data.schema(columns={"source": True}) assert schema["_source_x"] == list[list[list[str]]] + + +class _TestDictExt(pa.ExtensionType): + """Extension type over dictionary storage, used in decode_dictionaries tests.""" + + def __init__(self): + super().__init__( + pa.dictionary(pa.int32(), pa.string()), "orcapod.test.dict_ext" + ) + + def __arrow_ext_serialize__(self): + return b"{}" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls() + + +_DICT = pa.dictionary(pa.int32(), pa.string()) + + +class _StorageExt(pa.ExtensionType): + """An extension type over any storage, for the decode_dictionaries tests.""" + + def __init__(self, storage: pa.DataType) -> None: + super().__init__(storage, "orcapod.test.storage_ext") + + def __arrow_ext_serialize__(self) -> bytes: + return b"{}" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls(storage_type) + + +class TestDecodeDictionaries: + """``decode_dictionaries`` (ITL-1264): every dictionary becomes its value type.""" + + @pytest.mark.parametrize( + "arrow_type", + [ + pa.int64(), + pa.large_string(), + pa.large_list(pa.field("item", pa.float32(), nullable=False)), + pa.list_view(pa.string()), + pa.run_end_encoded(pa.int16(), pa.large_string()), + pa.large_list_view(pa.field("item", pa.int8(), nullable=False)), + pa.struct([pa.field("a", pa.int8()), pa.field("b", pa.string())]), + pa.map_(pa.string(), pa.int64()), + _TestIntExt(), + ], + ) + def test_a_type_without_a_dictionary_is_returned_as_it_is(self, arrow_type): + assert decode_dictionaries(arrow_type) == arrow_type + + @pytest.mark.parametrize( + ("arrow_type", "decoded"), + [ + (_DICT, pa.string()), + (pa.dictionary(pa.uint8(), pa.float64(), ordered=True), pa.float64()), + (pa.dictionary(pa.int16(), pa.int32()), pa.int32()), + (pa.list_(_DICT), pa.list_(pa.string())), + (pa.large_list(_DICT), pa.large_list(pa.string())), + (pa.list_(_DICT, 2), pa.list_(pa.string(), 2)), + (pa.list_view(_DICT), pa.list_view(pa.string())), + ( + pa.run_end_encoded(pa.int32(), _DICT), # pyright: ignore[reportArgumentType] # the stubs accept only basic value types; Arrow takes a dictionary + pa.run_end_encoded(pa.int32(), pa.string()), + ), + (pa.large_list_view(_DICT), pa.large_list_view(pa.string())), + ( + pa.struct([pa.field("k", _DICT), pa.field("n", pa.int64())]), + pa.struct([pa.field("k", pa.string()), pa.field("n", pa.int64())]), + ), + (pa.map_(_DICT, _DICT), pa.map_(pa.string(), pa.string())), + ( + pa.dense_union([pa.field("s", _DICT), pa.field("i", pa.int8())]), + pa.dense_union([pa.field("s", pa.string()), pa.field("i", pa.int8())]), + ), + ( + pa.large_list(pa.large_list(_DICT)), + pa.large_list(pa.large_list(pa.string())), + ), + (_TestDictExt(), pa.string()), + (pa.dictionary(pa.int32(), _DICT), pa.string()), # pyright: ignore[reportArgumentType] # the stubs accept only basic value types; Arrow takes a dictionary + ( + pa.sparse_union([pa.field("s", _DICT), pa.field("i", pa.int8())]), + pa.sparse_union([pa.field("s", pa.string()), pa.field("i", pa.int8())]), + ), + (pa.map_(_DICT, pa.int64()), pa.map_(pa.string(), pa.int64())), + (_StorageExt(pa.large_list(_DICT)), pa.large_list(pa.string())), + (pa.opaque(_DICT, "label", "vendor"), pa.string()), + ( + pa.opaque(pa.large_list(_DICT), "label", "vendor"), + pa.large_list(pa.string()), + ), + ( + pa.struct([pa.field("o", pa.opaque(_DICT, "label", "vendor"))]), + pa.struct([pa.field("o", pa.string())]), + ), + (_StorageExt(pa.large_list_view(_DICT)), pa.large_list_view(pa.string())), + ( + _StorageExt(pa.run_end_encoded(pa.int32(), _DICT)), # pyright: ignore[reportArgumentType] # the stubs accept only basic value types; Arrow takes a dictionary + pa.run_end_encoded(pa.int32(), pa.string()), + ), + ], + ) + def test_every_dictionary_is_decoded(self, arrow_type, decoded): + assert decode_dictionaries(arrow_type) == decoded + + def test_nested_fields_keep_their_names_nullability_and_metadata(self): + child = pa.field("k", _DICT, nullable=False, metadata={"m": "1"}) + decoded = decode_dictionaries(pa.struct([child, pa.field("n", pa.int8())])) + assert isinstance(decoded, pa.StructType) + assert decoded.field("k").equals( + pa.field("k", pa.string(), nullable=False, metadata={"m": "1"}), + check_metadata=True, + ) + item = pa.field("element", _DICT, nullable=False) + decoded_list = decode_dictionaries(pa.large_list(item)) + assert isinstance(decoded_list, pa.LargeListType) + assert decoded_list.value_field.name == "element" + assert not decoded_list.value_field.nullable