From 024e3e0b874ff3ecf6f518746d89feeee1f39cc3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 17:12:35 -0800 Subject: [PATCH 01/11] fix(streams): refuse a dictionary-encoded tag column (ITL-1264) Dictionary-encoded tags are not currently supported in Orcapod (developer decision, November 18, 2026). A tag column, a data-tag included, whose Arrow type is or contains a dictionary raises InputValidationError when a source or stream is built, naming each such column, its type and its decoded type. One rule, schema_utils.require_tags_not_dictionary, called by ArrowTableStream.__init__ (every source and operator result) and first by SourceStreamBuilder.build, so a source reports the dictionary before its key columns and its hash. arrow_utils.decode_dictionaries gives the decoded type. Dictionary-encoded data columns are unchanged (ITL-1277). Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 11 + CLAUDE.md | 11 + changelog.d/ITL-1264.md | 12 + docs/concepts/sources.md | 45 ++ docs/troubleshooting.md | 13 + src/orcapod/core/sources/stream_builder.py | 8 + .../core/streams/arrow_table_stream.py | 6 + src/orcapod/utils/arrow_utils.py | 60 +++ src/orcapod/utils/schema_utils.py | 58 ++- .../sources/test_dictionary_tags_refused.py | 438 ++++++++++++++++++ tests/test_utils/test_arrow_utils.py | 80 ++++ 11 files changed, 741 insertions(+), 1 deletion(-) create mode 100644 changelog.d/ITL-1264.md create mode 100644 tests/test_core/sources/test_dictionary_tags_refused.py diff --git a/.zed/rules b/.zed/rules index e9a83842d..076a4e711 100644 --- a/.zed/rules +++ b/.zed/rules @@ -945,6 +945,17 @@ 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 tags are refused (developer, November 18, 2026, ITL-1264): "Say it is not +currently supported in orcapod. We MAY support but not immediately in the plan." A tag column +(a data-tag too) whose Arrow type is, or contains, a dictionary (list item, struct child, map +key or item, extension storage) raises InputValidationError naming each such column, its type +and its decoded type (arrow_utils.decode_dictionaries). One rule, +schema_utils.require_tags_not_dictionary, called by ArrowTableStream.__init__ (every source +and operator result) and first by SourceStreamBuilder.build (before the key columns and the +hash); never check it elsewhere. Dictionary-encoded DATA columns are accepted as before (their +Python type is Any); what to do about them is ITL-1277: change nothing for them without a +decision. + 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 diff --git a/CLAUDE.md b/CLAUDE.md index c55f8bd61..3196e518e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -987,6 +987,17 @@ 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 tags are refused (developer, November 18, 2026, ITL-1264): "Say it is not +currently supported in orcapod. We MAY support but not immediately in the plan." A tag column +(a data-tag too) whose Arrow type is, or contains, a dictionary (list item, struct child, map +key or item, extension storage) raises `InputValidationError` naming each such column, its type +and its decoded type (`arrow_utils.decode_dictionaries`). One rule, +`schema_utils.require_tags_not_dictionary`, called by `ArrowTableStream.__init__` (every source +and operator result) and first by `SourceStreamBuilder.build` (before the key columns and the +hash); never check it elsewhere. Dictionary-encoded DATA columns are accepted as before (their +Python type is `Any`); what to do about them is ITL-1277: change nothing for them without a +decision. + 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 diff --git a/changelog.d/ITL-1264.md b/changelog.d/ITL-1264.md new file mode 100644 index 000000000..b25aeba08 --- /dev/null +++ b/changelog.d/ITL-1264.md @@ -0,0 +1,12 @@ +### Changed + +- A dictionary-encoded tag column is refused (ITL-1264): dictionary-encoded tags are not + currently supported in Orcapod. A tag column, a data-tag included, whose Arrow type is a + `dictionary` or holds one inside it (a list of dictionary values, a struct with a dictionary + field) raises `InputValidationError` when a source or a stream is built. The message names + each such column, its type and the type it decodes to. Before, such a 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 ran through a job. 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 (pyarrow `column.cast(column.type.value_type)`, polars + `pl.col(name).cast(pl.String)`). Dictionary-encoded data columns are accepted as before. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index a695bd1b4..0ad8ac743 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -86,6 +86,51 @@ 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 tags are not currently supported in Orcapod. A tag 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 tag column, its type and the type it decodes to. A data-tag is a +tag, so it is refused too. 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. 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": [0.4, 0.7, 0.5], + } +) +try: + ArrowTableSource(coded, tag_columns=["session", "trial"], tag_only_columns=True) +except InputValidationError as exc: + print(str(exc).split(": tag column")[0]) +# dictionary-encoded tags are not currently supported in Orcapod + +session = coded["session"] +decoded = coded.set_column(0, "session", session.cast(session.type.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, `df.with_columns(pl.col("session").cast(pl.String))` decodes a `Categorical` or +`Enum` column. With pandas, `df["session"].astype(df["session"].cat.categories.dtype)` decodes +a `Categorical` of strings; a `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 dictionary-encoded data column is accepted as before. Its Python type is `Any`, so a +function pod with a typed parameter refuses it, and a filter or a join on a stream that holds +a dictionary of integers or floats fails; decode it the same way. + ### 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..544d2afb5 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -32,6 +32,19 @@ 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 tags are not currently supported in Orcapod: tag column '...' has type dictionary<...> (decoded: ...)` + +**Cause.** A tag column 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 tags yet; the message names every one, with the type it decodes to. + +**Fix.** Decode the column before building the source: with pyarrow, +`table.set_column(i, name, table[name].cast(table[name].type.value_type))` (for a nested +dictionary, cast to the decoded type the message gives); with polars, +`df.with_columns(pl.col(name).cast(pl.String))`. 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/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 454781a2b..7da30bcda 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 tag column's type is, or contains, a + dictionary: dictionary-encoded tags are not currently supported + (ITL-1264). """ tag_columns_tuple = tuple(tag_columns) system_tag_columns_tuple = tuple(system_tag_columns) @@ -394,6 +397,11 @@ def build( f"Available columns: {list(table.column_names)}" ) + # Dictionary-encoded tags are not currently supported (ITL-1264). The stream + # refuses them too; checking first reports the dictionary, not a key column + # error, and before anything is hashed. + schema_utils.require_tags_not_dictionary(table.schema, tag_columns_tuple) + # 3. The row identifiers (validates the key columns). identifiers = row_identifiers( table, normalize_record_id_columns(record_id_columns) or () diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 3b5e5eae3..71233dac3 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 tag column's type is, or contains, a + dictionary: dictionary-encoded tags are not currently supported + (ITL-1264). """ super().__init__(**kwargs) @@ -143,6 +146,9 @@ def __init__( raise ValueError( f"Data-tags {sorted(unknown)} are not tag columns of the stream." ) + # Dictionary-encoded tags are not currently supported (ITL-1264): every + # source and operator result becomes a stream here, so this refuses them all. + schema_utils.require_tags_not_dictionary(table.schema, self._tag_columns) # A data-tag is one column in both roles: a tag, and a data column of # the same name (tag order). self._data_tags = tuple(c for c in self._tag_columns if c in set(data_tags)) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index c138f6dde..ea9d2b05a 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -193,6 +193,66 @@ 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 struct, a map or a union 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. + """ + if isinstance(arrow_type, pa.ExtensionType): + 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) + ): + 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) + return pa.list_(decoded, arrow_type.list_size) + 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..bc15497e2 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,59 @@ def require_names_not_meta(names: Collection[str]) -> None: ) +DICTIONARY_TAGS_NOT_SUPPORTED = ( + "dictionary-encoded tags are not currently supported in Orcapod" +) +"""The start of the error for a dictionary-encoded tag (ITL-1264).""" + + +def require_tags_not_dictionary( + arrow_schema: "pa.Schema", tag_columns: Sequence[str] +) -> None: + """Raise if a tag column's Arrow type is, or contains, a dictionary (ITL-1264). + + Developer decision, November 18, 2026: dictionary-encoded tags are not currently + supported in Orcapod. A dictionary at the top level of a tag's type, or inside it + (a list item, a struct child, a map key or item, an extension type's storage), + is refused here, where a stream gets its tags, and not far from the cause (a + sort by tags, a nullability restore, ``Batch``, ``GroupBy``). This is the one + rule: ``ArrowTableStream`` calls it for every source and operator result, and + the source builder first, before its key columns and its hash. Data columns are + not checked; a data-tag is a tag, so it is. + + Args: + arrow_schema: The Arrow schema of the table the tags are in. + tag_columns: The tag column names, in tag order; names the schema does not + have are skipped (the caller reports them). + + Raises: + InputValidationError: If a tag column holds a dictionary. The message names + every such column in tag order, with its type and the type it decodes to. + """ + from orcapod.utils.arrow_utils import decode_dictionaries + + found: list[str] = [] + for name in tag_columns: + if name not in arrow_schema.names: + continue + arrow_type = arrow_schema.field(name).type + decoded = decode_dictionaries(arrow_type) + if decoded != arrow_type: + found.append( + f"tag column {name!r} has type {arrow_type} (decoded: {decoded})" + ) + if found: + raise InputValidationError( + f"{DICTIONARY_TAGS_NOT_SUPPORTED}: " + + "; ".join(found) + + ". Decode each such column to its decoded type before building the " + "source or stream: with pyarrow, column.cast(column.type.value_type) " + "decodes a dictionary column (cast a column holding a dictionary inside " + "it to its decoded type); with polars, 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/sources/test_dictionary_tags_refused.py b/tests/test_core/sources/test_dictionary_tags_refused.py new file mode 100644 index 000000000..e9f790305 --- /dev/null +++ b/tests/test_core/sources/test_dictionary_tags_refused.py @@ -0,0 +1,438 @@ +"""A dictionary-encoded tag is refused where a stream gets its tags (ITL-1264). + +Developer decision, November 18, 2026: dictionary-encoded tags are not currently +supported in Orcapod. A tag column whose Arrow type is, or contains, a dictionary is +refused with ``InputValidationError`` when a source or a stream is built, naming every +such column with its type and its decoded type, instead of failing far from the cause +(a sort, a nullability restore, ``as_table(all_info=True)``, ``Batch``, ``GroupBy``). +The rule is one function, ``schema_utils.require_tags_not_dictionary``, called 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. + +Dictionary-encoded DATA columns are not covered by the decision and are accepted as +before; a data-tag is a tag, so it is refused. +""" + +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, 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 + +NOT_SUPPORTED = "dictionary-encoded tags are not currently supported in Orcapod" + +# The values of each tag column, by kind; every kind has two distinct values per +# column so the rows stay distinct whichever columns are encoded. +VALUES: dict[str, tuple[pa.DataType, list[Any], list[Any]]] = { + "string": (pa.string(), ["x", "y", "x"], ["p", "p", "q"]), + "int": (pa.int64(), [1, 2, 1], [7, 7, 8]), + "float": (pa.float64(), [1.5, 2.5, 1.5], [0.25, 0.25, 0.75]), +} +TAG_ORDERS = [("a", "b"), ("b", "a")] +ENCODED = [("a",), ("b",), ("a", "b")] + + +def _table(kind: str, encoded: tuple[str, ...], data_first: bool = False) -> pa.Table: + """Two tag columns ``a`` and ``b`` (those in ``encoded`` dictionary-encoded) and two + data columns ``v`` and ``w``, in one of two layouts.""" + value_type, a_values, b_values = VALUES[kind] + columns: dict[str, pa.Array[Any]] = {} + for name, values in (("a", a_values), ("b", b_values)): + array = pa.array(values, value_type) + columns[name] = array.dictionary_encode() if name in encoded else array + data = { + "v": pa.array([1.0, 2.0, 3.0], pa.float64()), + "w": pa.array(["r", "s", "t"], pa.large_string()), + } + ordered = {**data, **columns} if data_first else {**columns, **data} + return pa.table(ordered) + + +def _assert_refused( + exc: BaseException, encoded_in_order: tuple[str, ...], plain: tuple[str, ...] +) -> None: + """The message says dictionary tags are not supported, names each encoded column + in tag order with its type, and names no plain tag.""" + assert isinstance(exc, InputValidationError) + assert not isinstance(exc, RowIdentifierError) + message = str(exc) + assert NOT_SUPPORTED in message + positions = [ + message.index(f"tag column {name!r} has type dictionary<") + for name in encoded_in_order + ] + assert positions == sorted(positions) + for name in plain: + assert f"tag column {name!r}" not in message + + +def _in_tag_order(tags: tuple[str, ...], encoded: tuple[str, ...]) -> tuple[str, ...]: + return tuple(t for t in tags if t in encoded) + + +# ── a raw ArrowTableStream ────────────────────────────────────────────────── + + +@pytest.mark.parametrize("data_first", [False, True]) +@pytest.mark.parametrize("data_tags", [(), ("a",), ("a", "b")]) +@pytest.mark.parametrize("encoded", ENCODED) +@pytest.mark.parametrize("tags", TAG_ORDERS) +@pytest.mark.parametrize("kind", sorted(VALUES)) +def test_a_raw_stream_refuses_dictionary_tags( + 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 + ) + plain = tuple(t for t in tags if t not in encoded) + _assert_refused(info.value, _in_tag_order(tags, encoded), plain) + + +# ── ArrowTableSource ──────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + "tag_only_columns", + [True, False, ["a"], ["b"]], + ids=["tag-only", "data-tags", "a-plain", "b-plain"], +) +@pytest.mark.parametrize("encoded", ENCODED) +@pytest.mark.parametrize("tags", TAG_ORDERS) +@pytest.mark.parametrize("kind", sorted(VALUES)) +def test_an_arrow_table_source_refuses_dictionary_tags( + kind: str, tags: tuple[str, ...], encoded: tuple[str, ...], tag_only_columns: Any +) -> None: + """Plain tags and data-tags alike: a data-tag is a tag.""" + with pytest.raises(InputValidationError) as info: + ArrowTableSource( + _table(kind, encoded), + tag_columns=list(tags), + tag_only_columns=tag_only_columns, + ) + plain = tuple(t for t in tags if t not in encoded) + _assert_refused(info.value, _in_tag_order(tags, encoded), plain) + + +@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_tag( + kind: str, record_id_columns: list[str] +) -> None: + """The builder checks the tags 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, ("a",), ("b",)) + + +def test_a_dictionary_tag_is_refused_before_anything_is_hashed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from orcapod.core.sources import stream_builder + + def _never(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("the source hashed before checking its tags") + + monkeypatch.setattr(stream_builder, "row_identifiers", _never) + with pytest.raises(InputValidationError, match=NOT_SUPPORTED): + ArrowTableSource( + _table("string", ("b",)), tag_columns=["a", "b"], tag_only_columns=True + ) + + +def test_the_message_gives_the_type_and_its_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": [1, 2], + } + ) + with pytest.raises(InputValidationError) as info: + ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + message = str(info.value) + assert ( + "tag column 'a' has type dictionary " + "(decoded: string)" in message + ) + assert ( + "tag column 'b' has type dictionary " + "(decoded: double)" in message + ) + + +# ── data frames ───────────────────────────────────────────────────────────── + + +def _pandas(encoded: tuple[str, ...]) -> pd.DataFrame: + # String categories: a pandas Categorical of integers reaches the source as its + # integers (the frame goes through polars, which has no integer Categorical). + frame = pd.DataFrame( + { + "a": ["x", "y", "x"], + "b": ["p", "p", "q"], + "v": [1.0, 2.0, 3.0], + "w": [1, 2, 3], + } + ) + for name in encoded: + frame[name] = frame[name].astype("category") + return frame + + +def _polars(encoded: tuple[str, ...], dtype: str) -> pl.DataFrame: + frame = pl.DataFrame( + { + "a": ["x", "y", "x"], + "b": ["p", "p", "q"], + "v": [1.0, 2.0, 3.0], + "w": [1, 2, 3], + } + ) + target = ( + pl.Categorical() if dtype == "Categorical" else pl.Enum(["p", "q", "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", ENCODED) +@pytest.mark.parametrize("tags", TAG_ORDERS) +@pytest.mark.parametrize("frame_kind", ["pandas", "polars-Categorical", "polars-Enum"]) +def test_a_data_frame_source_refuses_categorical_tags( + 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 + ) + plain = tuple(t for t in tags if t not in encoded) + _assert_refused(info.value, _in_tag_order(tags, encoded), plain) + + +# ── a polling source's batches, read sync and async ───────────────────────── + + +class _CategoricalImpl: + """Fetches one batch whose tag ``a`` is a polars Categorical.""" + + def identity(self) -> str: + return "categorical-impl" + + def to_config(self) -> None: + return None + + @classmethod + def from_config(cls, config: Any) -> _CategoricalImpl: + return cls() + + 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, "w": int}) + + 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], "w": [1, 2]} + ).with_columns(pl.col("a").cast(pl.Categorical())) + return Cursor(value=1), frame + + async def close(self) -> None: + return None + + +def _polling_source() -> PollingSource[int]: + return PollingSource( + _CategoricalImpl(), + tag_columns=["b", "a"], + record_id_columns="b", + polling_config=PollingConfig(duration=0.01), + ) + + +def test_a_polling_source_refuses_a_categorical_tag_on_a_sync_read() -> None: + with pytest.raises(InputValidationError) as info: + _polling_source().as_table() + _assert_refused(info.value, ("a",), ("b",)) + + +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_a_job_over_a_polling_source_refuses_a_categorical_tag( + orchestrator: type, +) -> None: + job = PipelineJob(name="itl1264", database=InMemoryArrowDatabase()) + with job: + _polling_source().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=NOT_SUPPORTED), + ): + if orchestrator is AsyncPipelineOrchestrator: + asyncio.run(job.run_async()) + else: + job.run(orchestrator=orchestrator()) + + +# ── a tag 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"] + ) + raise ValueError(kind) + + +DECODED = { + "list": "large_list", + "struct": "struct", +} + + +@pytest.mark.parametrize("build", ["source", "stream"]) +@pytest.mark.parametrize("kind", ["list", "struct"]) +def test_a_tag_containing_a_dictionary_is_refused(kind: str, build: str) -> None: + table = pa.table({"b": [1, 2, 3], "a": _nested(kind), "v": [1.0, 2.0, 3.0]}) + with pytest.raises(InputValidationError) as info: + if build == "source": + ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + else: + ArrowTableStream(table, tag_columns=["a", "b"]) + message = str(info.value) + assert NOT_SUPPORTED in message + assert re.search(r"tag column 'a' has type \S.*dictionary<", message) + if build == "source": + assert f"(decoded: {DECODED[kind]})" in message + assert "tag column 'b'" not in message + + +# ── 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, ("a", "b")) + for name in ("b", "a"): + 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 + + +@pytest.mark.parametrize("dtype", ["Categorical", "Enum"]) +def test_a_frame_decoded_with_polars_builds(dtype: str) -> None: + frame = _polars(("a", "b"), dtype).with_columns(pl.col("a", "b").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")) + for name in ("a", "b"): + 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 tag ────────────────────────────────────── + + +def _data_source() -> ArrowTableSource: + """Two plain tags; data columns ``v`` (dictionary-encoded float) and ``u`` + (dictionary-encoded string) and ``w`` plain.""" + return ArrowTableSource( + pa.table( + { + "a": ["x", "y", "x"], + "v": pa.array([1.5, 2.5, 1.5]).dictionary_encode(), + "b": [7, 7, 8], + "u": pa.array(["r", "s", "r"]).dictionary_encode(), + "w": [1, 2, 3], + } + ), + tag_columns=["a", "b"], + tag_only_columns=True, + ) + + +@pytest.mark.parametrize("columns", [["v"], ["u", "v"], ["w", "u"]]) +def test_tag_by_refuses_a_dictionary_data_column(columns: list[str]) -> None: + """``TagBy`` refuses it before any stream is built (its Python type is ``Any``).""" + with pytest.raises(InputValidationError, match="cannot be a tag"): + _data_source().tag_by(columns) + + +# ── dictionary-encoded DATA columns are accepted as before ─────────────────── + + +@pytest.mark.parametrize("tags", [["a", "b"], ["b", "a"]]) +def test_dictionary_data_columns_are_accepted_unchanged(tags: list[str]) -> None: + """Not covered by the decision: the source keeps them dictionary-encoded.""" + source = ArrowTableSource( + _data_source().as_table(), tag_columns=tags, tag_only_columns=True + ) + tag_keys, data_keys = source.keys() + assert tag_keys == tuple(tags) + assert data_keys == ("v", "u", "w") + table = source.as_table() + assert pa.types.is_dictionary(table.schema.field("v").type) + assert pa.types.is_dictionary(table.schema.field("u").type) + stream = ArrowTableStream(_data_source().as_table(), tag_columns=tags) + assert pa.types.is_dictionary(stream.as_table().schema.field("u").type) diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index ce8789e7c..6fac2e7e1 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,82 @@ 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 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.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.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()), + ], + ) + 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 From 67bd3afe66f979e13a61a098ff334eff14199766 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 18:13:05 -0800 Subject: [PATCH 02/11] refactor(group_by): drop the dictionary-encoded key branches; their tests become refusal tests (ITL-1264, ITL-1234) Every stream refuses a dictionary-encoded tag (ITL-1264), so GroupBy never sees a dictionary key: _float_storage's dictionary path and _emitted_key_row's dictionary_decode are unreachable and removed, with their docs lines. PR 441's dictionary-key tests now check the refusal (string, integer and float keys, one or both of two tags encoded, both tag orders, plain and data-tags, a source and a raw stream) and that the decoded key groups. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 5 +- CLAUDE.md | 5 +- changelog.d/ITL-1264.md | 3 + docs/concepts/operators.md | 2 +- src/orcapod/core/operators/group_by.py | 22 +- .../operators/test_group_by_nan_keys.py | 237 ++++++------------ 6 files changed, 94 insertions(+), 180 deletions(-) diff --git a/.zed/rules b/.zed/rules index e8b11db19..655947e6c 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1239,8 +1239,9 @@ data. The rules: wins), taken from the input's Arrow column, never through Python (a float32 signaling NaN comes back quiet from Python): always a value a member holds, never the first row's, never chosen by `member_order`. Bits are read only for a group whose key is zero or NaN. A logical - type stored as a float, or a dictionary-encoded float, is a float key, read through its - storage or its values (`_float_storage`). Every + type stored as a float is a float key, read through its storage (`_float_storage`); a + dictionary-encoded key never reaches GroupBy, since every stream refuses a dictionary tag + (ITL-1264). Every other key is rebuilt from its Python value, as before: equal Python values that differ in Arrow (`time64[ns]` within a microsecond) are one group with one rebuilt key; grouping by the exact value is ITL-1250. The stance on `0.0`/`-0.0` and NaN for the whole library diff --git a/CLAUDE.md b/CLAUDE.md index 0f83e3375..6122e30e0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1284,8 +1284,9 @@ data. The rules: wins), taken from the input's Arrow column, never through Python (a float32 signaling NaN comes back quiet from Python): always a value a member holds, never the first row's, never chosen by `member_order`. Bits are read only for a group whose key is zero or NaN. A logical - type stored as a float, or a dictionary-encoded float, is a float key, read through its - storage or its values (`_float_storage`). Every + type stored as a float is a float key, read through its storage (`_float_storage`); a + dictionary-encoded key never reaches GroupBy, since every stream refuses a dictionary tag + (ITL-1264). Every other key is rebuilt from its Python value, as before: equal Python values that differ in Arrow (`time64[ns]` within a microsecond) are one group with one rebuilt key; grouping by the exact value is ITL-1250. The stance on `0.0`/`-0.0` and NaN for the whole library diff --git a/changelog.d/ITL-1264.md b/changelog.d/ITL-1264.md index b25aeba08..62f274dbd 100644 --- a/changelog.d/ITL-1264.md +++ b/changelog.d/ITL-1264.md @@ -10,3 +10,6 @@ own, a pandas `Categorical` of strings and a polars `Categorical` or `Enum`; decode the column first (pyarrow `column.cast(column.type.value_type)`, polars `pl.col(name).cast(pl.String)`). Dictionary-encoded data columns are accepted as before. +- `GroupBy` no longer reads a dictionary-encoded float key by the bits of its values, as + ITL-1234 describes: such a key is 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 a03ec512c..b1cab34a3 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -322,7 +322,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/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index 46ac3dbd4..6244a9fe4 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -75,8 +75,8 @@ def _float_storage(arrow_type: "pa.DataType") -> "pa.DataType | None": """Return the float type a column is stored as, or ``None`` when it is not a float. A logical (extension) type over float storage, such as a temperature stored as - ``float64``, is stored as that float, and a dictionary-encoded column as the - float type of its values. + ``float64``, is stored as that float. A dictionary-encoded key never reaches + ``GroupBy``: every stream refuses a dictionary-encoded tag (ITL-1264). Args: arrow_type: The Arrow type of a key column. @@ -90,8 +90,6 @@ def _float_storage(arrow_type: "pa.DataType") -> "pa.DataType | None": if isinstance(arrow_type, pa.ExtensionType) else arrow_type ) - if pa.types.is_dictionary(storage): - storage = storage.value_type return storage if pa.types.is_floating(storage) else None @@ -135,9 +133,6 @@ def _emitted_key_row(column: "pa.ChunkedArray[Any]", indices: Sequence[int]) -> members = column.take(pa.array(indices, pa.int64())).combine_chunks() if isinstance(members, pa.ExtensionArray): members = members.storage - if isinstance(members, pa.DictionaryArray): - # The values each member's index points at, bits as stored. - members = members.dictionary_decode() # The unsigned integer of the float's width, to read its bits; no value of the # group is null, since a null key equals no float. unsigned = {16: pa.uint16, 32: pa.uint32, 64: pa.uint64}[storage_type.bit_width]() @@ -562,10 +557,10 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: stream.data_context.type_converter, ) - # A float key column (a float, a logical type stored as one, or a dictionary - # over floats) holds the chosen member's value as the input's Arrow column - # has it, never through Python: a conversion can change a float's bits (a - # float32 signaling NaN comes back quiet). Every other key keeps the value rebuilt from Python, + # A float key column (a float, or a logical type stored as one) holds the + # chosen member's value as the input's Arrow column has it, never through + # Python: a conversion can change a float's bits (a float32 signaling NaN + # comes back quiet). Every other key keeps the value rebuilt from Python, # as before: its members may differ in Arrow although equal in Python (two # time64[ns] values within one microsecond read as one ``datetime.time``), # and taking one member's would make the key depend on the row order. @@ -573,10 +568,7 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: for position, c in enumerate(self.by): if _float_storage(table.column(c).type) is None: continue - # A null key is taken through a null index, so it is a null at the top - # level whichever member came first: a dictionary column can hold a null - # as a null index or as an index to a null entry, and only the first is - # a null to a reader of validity (``DropNulls``). + # A null key is taken through a null index. chosen = pa.array( [ None if rows[r[position]][c] is None else r[position] 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 aa3ed4152..e9045e203 100644 --- a/tests/test_core/operators/test_group_by_nan_keys.py +++ b/tests/test_core/operators/test_group_by_nan_keys.py @@ -13,7 +13,6 @@ from __future__ import annotations -import asyncio import itertools import json import struct @@ -23,10 +22,10 @@ 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, @@ -435,171 +434,89 @@ def test_a_time64_ns_key_is_rebuilt_from_its_python_value() -> None: assert sorted(members[0]) == sorted(values) -# ── 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 decision, November 18, 2026: dictionary-encoded tags are not currently +# supported. Every stream refuses one when it is built (``ArrowTableStream`` and the +# source builder, ``schema_utils.require_tags_not_dictionary``), 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 tags 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] From 916aaed1399f0659125b3ef65c847f8186dbf1fc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 18:42:39 -0800 Subject: [PATCH 03/11] fix(arrow_utils): a dictionary inside a list-view tag is refused too (ITL-1264) decode_dictionaries did not recurse into list_view / large_list_view, so a tag holding a dictionary inside one escaped the refusal: a raw stream accepted it and a source failed later at the hasher, without the decoding guidance. Both view types now go through the list branch. A list view of plain values keeps what it had (raw stream accepts it, a source refuses it at the hasher, ITL-1129). Reported by CodeRabbit on PR 455. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 2 +- CLAUDE.md | 2 +- src/orcapod/utils/arrow_utils.py | 9 ++++- src/orcapod/utils/schema_utils.py | 3 +- .../sources/test_dictionary_tags_refused.py | 35 ++++++++++++++++++- tests/test_utils/test_arrow_utils.py | 4 +++ 6 files changed, 50 insertions(+), 5 deletions(-) diff --git a/.zed/rules b/.zed/rules index 655947e6c..a446ed7be 100644 --- a/.zed/rules +++ b/.zed/rules @@ -947,7 +947,7 @@ holds them as given (ITL-1129). Dictionary-encoded tags are refused (developer, November 18, 2026, ITL-1264): "Say it is not currently supported in orcapod. We MAY support but not immediately in the plan." A tag column -(a data-tag too) whose Arrow type is, or contains, a dictionary (list item, struct child, map +(a data-tag too) whose Arrow type is, or contains, a dictionary (list or list-view item, struct child, map key or item, extension storage) raises InputValidationError naming each such column, its type and its decoded type (arrow_utils.decode_dictionaries). One rule, schema_utils.require_tags_not_dictionary, called by ArrowTableStream.__init__ (every source diff --git a/CLAUDE.md b/CLAUDE.md index 6122e30e0..2f960063f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -989,7 +989,7 @@ holds them as given (ITL-1129). Dictionary-encoded tags are refused (developer, November 18, 2026, ITL-1264): "Say it is not currently supported in orcapod. We MAY support but not immediately in the plan." A tag column -(a data-tag too) whose Arrow type is, or contains, a dictionary (list item, struct child, map +(a data-tag too) whose Arrow type is, or contains, a dictionary (list or list-view item, struct child, map key or item, extension storage) raises `InputValidationError` naming each such column, its type and its decoded type (`arrow_utils.decode_dictionaries`). One rule, `schema_utils.require_tags_not_dictionary`, called by `ArrowTableStream.__init__` (every source diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index ea9d2b05a..7ccd7e9e7 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -197,7 +197,8 @@ 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 struct, a map or a union becomes its value type, and nested fields + inside a list (a list view included), a struct, a map or a union 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 @@ -218,6 +219,8 @@ def decode_dictionaries(arrow_type: "pa.DataType") -> "pa.DataType": 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)) @@ -227,6 +230,10 @@ def decode_dictionaries(arrow_type: "pa.DataType") -> "pa.DataType": 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_struct(arrow_type): fields = [f.with_type(decode_dictionaries(f.type)) for f in arrow_type] diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index bc15497e2..96bd6f323 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -698,7 +698,8 @@ def require_tags_not_dictionary( Developer decision, November 18, 2026: dictionary-encoded tags are not currently supported in Orcapod. A dictionary at the top level of a tag's type, or inside it - (a list item, a struct child, a map key or item, an extension type's storage), + (a list or list-view item, a struct child, a map key or item, an extension type's + storage), is refused here, where a stream gets its tags, and not far from the cause (a sort by tags, a nullability restore, ``Batch``, ``GroupBy``). This is the one rule: ``ArrowTableStream`` calls it for every source and operator result, and diff --git a/tests/test_core/sources/test_dictionary_tags_refused.py b/tests/test_core/sources/test_dictionary_tags_refused.py index e9f790305..ddb08a457 100644 --- a/tests/test_core/sources/test_dictionary_tags_refused.py +++ b/tests/test_core/sources/test_dictionary_tags_refused.py @@ -335,17 +335,27 @@ def _nested(kind: str) -> pa.Array[Any]: 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 == "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", } @pytest.mark.parametrize("build", ["source", "stream"]) -@pytest.mark.parametrize("kind", ["list", "struct"]) +@pytest.mark.parametrize("kind", ["list", "struct", "list_view", "large_list_view"]) def test_a_tag_containing_a_dictionary_is_refused(kind: str, build: str) -> None: table = pa.table({"b": [1, 2, 3], "a": _nested(kind), "v": [1.0, 2.0, 3.0]}) with pytest.raises(InputValidationError) as info: @@ -361,6 +371,29 @@ def test_a_tag_containing_a_dictionary_is_refused(kind: str, build: str) -> None assert "tag column 'b'" not in message +@pytest.mark.parametrize("kind", ["list_view", "large_list_view"]) +def test_a_list_view_tag_without_a_dictionary_is_handled_as_before(kind: 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). + """ + 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())) + ) + column = ( + 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 + table = pa.table({"b": [1, 2, 3], "a": column, "v": [1.0, 2.0, 3.0]}) + ArrowTableStream(table, tag_columns=["a", "b"]) + with pytest.raises(ValueError, match="the Arrow hasher refused") as info: + ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + assert NOT_SUPPORTED not in str(info.value) + + # ── the decoding the message suggests works ───────────────────────────────── diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 6fac2e7e1..f147c050c 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -1100,6 +1100,8 @@ class TestDecodeDictionaries: pa.int64(), pa.large_string(), pa.large_list(pa.field("item", pa.float32(), nullable=False)), + pa.list_view(pa.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(), @@ -1117,6 +1119,8 @@ def test_a_type_without_a_dictionary_is_returned_as_it_is(self, arrow_type): (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.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())]), From 6f727901a319d49b5453eb4fa905f8ff68422907 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 19:34:06 -0800 Subject: [PATCH 04/11] test(dictionary_tags): nested and list-view cases with two tags and two data columns, both tag orders, two layouts, every role (ITL-1264) CodeRabbit on PR 455: the nested-dictionary and list-view tests had one data column, a fixed tag order and layout, and plain tags only. They now run on two tags and two data columns, in both tag orders, two table layouts and the plain, data-tag and mixed roles, as a source and as a raw stream; the refusal and the dictionary-free control are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../sources/test_dictionary_tags_refused.py | 91 +++++++++++++++---- 1 file changed, 74 insertions(+), 17 deletions(-) diff --git a/tests/test_core/sources/test_dictionary_tags_refused.py b/tests/test_core/sources/test_dictionary_tags_refused.py index ddb08a457..b0faaf93b 100644 --- a/tests/test_core/sources/test_dictionary_tags_refused.py +++ b/tests/test_core/sources/test_dictionary_tags_refused.py @@ -354,15 +354,66 @@ def _nested(kind: str) -> pa.Array[Any]: } +# 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(a: pa.Array[Any], layout: str) -> pa.Table: + """Tag ``a`` (the column under test), tag ``b`` and data ``v``, ``w`` in ``layout``.""" + columns: dict[str, pa.Array[Any]] = { + "a": a, + "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()), + } + 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("build", ["source", "stream"]) @pytest.mark.parametrize("kind", ["list", "struct", "list_view", "large_list_view"]) -def test_a_tag_containing_a_dictionary_is_refused(kind: str, build: str) -> None: - table = pa.table({"b": [1, 2, 3], "a": _nested(kind), "v": [1.0, 2.0, 3.0]}) +def test_a_tag_containing_a_dictionary_is_refused( + kind: str, build: str, tag_order: tuple[str, str], layout: str, roles: str +) -> None: + table = _nested_table(_nested(kind), layout) with pytest.raises(InputValidationError) as info: - if build == "source": - ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) - else: - ArrowTableStream(table, tag_columns=["a", "b"]) + _build_nested(build, table, tag_order, roles) message = str(info.value) assert NOT_SUPPORTED in message assert re.search(r"tag column 'a' has type \S.*dictionary<", message) @@ -371,26 +422,32 @@ def test_a_tag_containing_a_dictionary_is_refused(kind: str, build: str) -> None assert "tag column 'b'" not in message -@pytest.mark.parametrize("kind", ["list_view", "large_list_view"]) -def test_a_list_view_tag_without_a_dictionary_is_handled_as_before(kind: 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). - """ +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())) ) - column = ( + 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 - table = pa.table({"b": [1, 2, 3], "a": column, "v": [1.0, 2.0, 3.0]}) - ArrowTableStream(table, tag_columns=["a", "b"]) + + +@NESTED_ARRANGEMENTS +@pytest.mark.parametrize("kind", ["list_view", "large_list_view"]) +def test_a_list_view_tag_without_a_dictionary_is_handled_as_before( + kind: 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), layout) + _build_nested("stream", table, tag_order, roles) with pytest.raises(ValueError, match="the Arrow hasher refused") as info: - ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) + _build_nested("source", table, tag_order, roles) assert NOT_SUPPORTED not in str(info.value) From 7754009810e5839254107f84bdbfbe94bf121ae4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 20:35:17 -0800 Subject: [PATCH 05/11] feat(streams)!: refuse dictionary-encoded data columns too (ITL-1264, ITL-1277) Developer, 2026-11-19 (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". Every column of a stream whose Arrow type is or contains a dictionary is refused: tags, data-tags and data, and Orcapod's own system-tag, source-info, context and meta columns (only a hand-built table can encode those). One rule: schema_utils.dictionary_columns finds them and dictionary_columns_error reports each with its role, type and decoded type, then the pyarrow and polars ways to decode; ArrowTableStream and, first, the source builder apply it. A library value in a cell (a data frame with a categorical column) is an extension column and is accepted, hashing as before (pinned). Merged main first. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 22 +- CLAUDE.md | 22 +- changelog.d/ITL-1264.md | 30 +- docs/concepts/sources.md | 41 +- docs/troubleshooting.md | 16 +- src/orcapod/core/sources/stream_builder.py | 17 +- .../core/streams/arrow_table_stream.py | 16 +- src/orcapod/utils/schema_utils.py | 135 ++-- .../operators/test_group_by_nan_keys.py | 8 +- .../test_dictionary_columns_refused.py | 639 ++++++++++++++++++ .../sources/test_dictionary_tags_refused.py | 528 --------------- 11 files changed, 833 insertions(+), 641 deletions(-) create mode 100644 tests/test_core/sources/test_dictionary_columns_refused.py delete mode 100644 tests/test_core/sources/test_dictionary_tags_refused.py diff --git a/.zed/rules b/.zed/rules index cd52624c1..bb70a1406 100644 --- a/.zed/rules +++ b/.zed/rules @@ -989,16 +989,20 @@ 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 tags are refused (developer, November 18, 2026, ITL-1264): "Say it is not -currently supported in orcapod. We MAY support but not immediately in the plan." A tag column -(a data-tag too) whose Arrow type is, or contains, a dictionary (list or list-view item, struct child, map -key or item, extension storage) raises InputValidationError naming each such column, its type -and its decoded type (arrow_utils.decode_dictionaries). One rule, -schema_utils.require_tags_not_dictionary, called by ArrowTableStream.__init__ (every source +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, 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. Dictionary-encoded DATA columns are accepted as before (their -Python type is Any); what to do about them is ITL-1277: change nothing for them without a -decision. +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 diff --git a/CLAUDE.md b/CLAUDE.md index bd84e543a..7f3857496 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1033,16 +1033,20 @@ 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 tags are refused (developer, November 18, 2026, ITL-1264): "Say it is not -currently supported in orcapod. We MAY support but not immediately in the plan." A tag column -(a data-tag too) whose Arrow type is, or contains, a dictionary (list or list-view item, struct child, map -key or item, extension storage) raises `InputValidationError` naming each such column, its type -and its decoded type (`arrow_utils.decode_dictionaries`). One rule, -`schema_utils.require_tags_not_dictionary`, called by `ArrowTableStream.__init__` (every source +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, 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. Dictionary-encoded DATA columns are accepted as before (their -Python type is `Any`); what to do about them is ITL-1277: change nothing for them without a -decision. +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 diff --git a/changelog.d/ITL-1264.md b/changelog.d/ITL-1264.md index 62f274dbd..cc01fada1 100644 --- a/changelog.d/ITL-1264.md +++ b/changelog.d/ITL-1264.md @@ -1,15 +1,23 @@ +### 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 + `column.cast(column.type.value_type)` or polars `pl.col(name).cast(pl.String)`. 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 -- A dictionary-encoded tag column is refused (ITL-1264): dictionary-encoded tags are not - currently supported in Orcapod. A tag column, a data-tag included, whose Arrow type is a - `dictionary` or holds one inside it (a list of dictionary values, a struct with a dictionary - field) raises `InputValidationError` when a source or a stream is built. The message names - each such column, its type and the type it decodes to. Before, such a 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 ran through a job. 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 (pyarrow `column.cast(column.type.value_type)`, polars - `pl.col(name).cast(pl.String)`). Dictionary-encoded data columns are accepted as before. - `GroupBy` no longer reads a dictionary-encoded float key by the bits of its values, as - ITL-1234 describes: such a key is refused when its source or stream is built, so that + 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/sources.md b/docs/concepts/sources.md index 0ad8ac743..f2aea6ca3 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -86,14 +86,14 @@ 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 tags are not currently supported in Orcapod. A tag 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 tag column, its type and the type it decodes to. A data-tag is a -tag, so it is refused too. 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. Decode the column before building the -source: +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 @@ -105,17 +105,23 @@ coded = pa.table( { "session": pa.array(["s1", "s2", "s1"]).dictionary_encode(), "trial": [1, 1, 2], - "response": [0.4, 0.7, 0.5], + "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(str(exc).split(": tag column")[0]) -# dictionary-encoded tags are not currently supported in Orcapod - -session = coded["session"] -decoded = coded.set_column(0, "session", session.cast(session.type.value_type)) + 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"): + column = decoded[name] + decoded = decoded.set_column( + decoded.schema.get_field_index(name), name, column.cast(column.type.value_type) + ) source = ArrowTableSource(decoded, tag_columns=["session", "trial"], tag_only_columns=True) print(source.as_table().schema.field("session").type) # large_string @@ -127,9 +133,10 @@ a `Categorical` of strings; a `Categorical` of integers that holds a missing val 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 dictionary-encoded data column is accepted as before. Its Python type is `Any`, so a -function pod with a typed parameter refuses it, and a filter or a join on a stream that holds -a dictionary of integers or floats fails; decode it the same way. +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 diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 544d2afb5..6ee8134bc 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -32,18 +32,20 @@ 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 tags are not currently supported in Orcapod: tag column '...' has type dictionary<...> (decoded: ...)` +### `InputValidationError: dictionary-encoded columns are not currently supported in Orcapod: - tag column '...' has type dictionary<...> (decoded: ...)` -**Cause.** A tag column 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 tags yet; the message names every one, with the type it decodes to. +**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, `table.set_column(i, name, table[name].cast(table[name].type.value_type))` (for a nested dictionary, cast to the decoded type the message gives); with polars, -`df.with_columns(pl.col(name).cast(pl.String))`. See -[Arrow types of a source](concepts/sources.md#arrow-types-of-a-source). +`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` diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 7da30bcda..3d221c012 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -359,9 +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 tag column's type is, or contains, a - dictionary: dictionary-encoded tags are not currently supported - (ITL-1264). + 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) @@ -397,10 +397,13 @@ def build( f"Available columns: {list(table.column_names)}" ) - # Dictionary-encoded tags are not currently supported (ITL-1264). The stream - # refuses them too; checking first reports the dictionary, not a key column - # error, and before anything is hashed. - schema_utils.require_tags_not_dictionary(table.schema, 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. + 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 + ) # 3. The row identifiers (validates the key columns). identifiers = row_identifiers( diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 71233dac3..0d3cf00b3 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -80,9 +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 tag column's type is, or contains, a - dictionary: dictionary-encoded tags are not currently supported - (ITL-1264). + 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) @@ -91,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] @@ -146,9 +153,6 @@ def __init__( raise ValueError( f"Data-tags {sorted(unknown)} are not tag columns of the stream." ) - # Dictionary-encoded tags are not currently supported (ITL-1264): every - # source and operator result becomes a stream here, so this refuses them all. - schema_utils.require_tags_not_dictionary(table.schema, self._tag_columns) # A data-tag is one column in both roles: a tag, and a data column of # the same name (tag order). self._data_tags = tuple(c for c in self._tag_columns if c in set(data_tags)) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 96bd6f323..98c73a922 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -685,58 +685,107 @@ def require_names_not_meta(names: Collection[str]) -> None: ) -DICTIONARY_TAGS_NOT_SUPPORTED = ( - "dictionary-encoded tags are not currently supported in Orcapod" +DICTIONARY_COLUMNS_NOT_SUPPORTED = ( + "dictionary-encoded columns are not currently supported in Orcapod" ) -"""The start of the error for a dictionary-encoded tag (ITL-1264).""" +"""The start of the error for a dictionary-encoded column (ITL-1264, ITL-1277).""" -def require_tags_not_dictionary( - arrow_schema: "pa.Schema", tag_columns: Sequence[str] -) -> None: - """Raise if a tag column's Arrow type is, or contains, a dictionary (ITL-1264). - - Developer decision, November 18, 2026: dictionary-encoded tags are not currently - supported in Orcapod. A dictionary at the top level of a tag's type, or inside it - (a list or list-view item, a struct child, a map key or item, an extension type's - storage), - is refused here, where a stream gets its tags, and not far from the cause (a - sort by tags, a nullability restore, ``Batch``, ``GroupBy``). This is the one - rule: ``ArrowTableStream`` calls it for every source and operator result, and - the source builder first, before its key columns and its hash. Data columns are - not checked; a data-tag is a tag, so it is. +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, 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 the table the tags are in. - tag_columns: The tag column names, in tag order; names the schema does not - have are skipped (the caller reports them). + arrow_schema: The Arrow schema of a table about to become a stream. - Raises: - InputValidationError: If a tag column holds a dictionary. The message names - every such column in tag order, with its type and the type it decodes to. + Returns: + ``(name, type, decoded type)`` for each such column, in schema order. """ from orcapod.utils.arrow_utils import decode_dictionaries - found: list[str] = [] - for name in tag_columns: - if name not in arrow_schema.names: - continue - arrow_type = arrow_schema.field(name).type - decoded = decode_dictionaries(arrow_type) - if decoded != arrow_type: - found.append( - f"tag column {name!r} has type {arrow_type} (decoded: {decoded})" - ) - if found: - raise InputValidationError( - f"{DICTIONARY_TAGS_NOT_SUPPORTED}: " - + "; ".join(found) - + ". Decode each such column to its decoded type before building the " - "source or stream: with pyarrow, column.cast(column.type.value_type) " - "decodes a dictionary column (cast a column holding a dictionary inside " - "it to its decoded type); with polars, pl.col(name).cast(pl.String) " - "decodes a Categorical or Enum column." - ) + 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, " + "column.cast(column.type.value_type) decodes a dictionary column (cast a " + "column holding a dictionary inside it to the decoded type shown); with " + "polars, pl.col(name).cast(pl.String) decodes a Categorical or Enum column." + ) def require_names_not_system(names: Collection[str]) -> None: 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 e9045e203..7f0ae7d0c 100644 --- a/tests/test_core/operators/test_group_by_nan_keys.py +++ b/tests/test_core/operators/test_group_by_nan_keys.py @@ -436,9 +436,9 @@ def test_a_time64_ns_key_is_rebuilt_from_its_python_value() -> None: # ── a dictionary-encoded key is refused (ITL-1264) ────────────────────────── # -# Developer decision, November 18, 2026: dictionary-encoded tags are not currently -# supported. Every stream refuses one when it is built (``ArrowTableStream`` and the -# source builder, ``schema_utils.require_tags_not_dictionary``), so a dictionary-encoded +# 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. @@ -489,7 +489,7 @@ def test_a_dictionary_encoded_key_is_refused_before_grouping( with pytest.raises(InputValidationError) as raised: build().group_by("k") message = str(raised.value) - assert "dictionary-encoded tags are not currently supported" in message + 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] 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..d7a814bfc --- /dev/null +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -0,0 +1,639 @@ +"""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 + +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 = ("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 "column.cast(column.type.value_type)" in message + assert "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) + 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) + + +# ── 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 == "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", +} +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 + + +@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_core/sources/test_dictionary_tags_refused.py b/tests/test_core/sources/test_dictionary_tags_refused.py deleted file mode 100644 index b0faaf93b..000000000 --- a/tests/test_core/sources/test_dictionary_tags_refused.py +++ /dev/null @@ -1,528 +0,0 @@ -"""A dictionary-encoded tag is refused where a stream gets its tags (ITL-1264). - -Developer decision, November 18, 2026: dictionary-encoded tags are not currently -supported in Orcapod. A tag column whose Arrow type is, or contains, a dictionary is -refused with ``InputValidationError`` when a source or a stream is built, naming every -such column with its type and its decoded type, instead of failing far from the cause -(a sort, a nullability restore, ``as_table(all_info=True)``, ``Batch``, ``GroupBy``). -The rule is one function, ``schema_utils.require_tags_not_dictionary``, called 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. - -Dictionary-encoded DATA columns are not covered by the decision and are accepted as -before; a data-tag is a tag, so it is refused. -""" - -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, 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 - -NOT_SUPPORTED = "dictionary-encoded tags are not currently supported in Orcapod" - -# The values of each tag column, by kind; every kind has two distinct values per -# column so the rows stay distinct whichever columns are encoded. -VALUES: dict[str, tuple[pa.DataType, list[Any], list[Any]]] = { - "string": (pa.string(), ["x", "y", "x"], ["p", "p", "q"]), - "int": (pa.int64(), [1, 2, 1], [7, 7, 8]), - "float": (pa.float64(), [1.5, 2.5, 1.5], [0.25, 0.25, 0.75]), -} -TAG_ORDERS = [("a", "b"), ("b", "a")] -ENCODED = [("a",), ("b",), ("a", "b")] - - -def _table(kind: str, encoded: tuple[str, ...], data_first: bool = False) -> pa.Table: - """Two tag columns ``a`` and ``b`` (those in ``encoded`` dictionary-encoded) and two - data columns ``v`` and ``w``, in one of two layouts.""" - value_type, a_values, b_values = VALUES[kind] - columns: dict[str, pa.Array[Any]] = {} - for name, values in (("a", a_values), ("b", b_values)): - array = pa.array(values, value_type) - columns[name] = array.dictionary_encode() if name in encoded else array - data = { - "v": pa.array([1.0, 2.0, 3.0], pa.float64()), - "w": pa.array(["r", "s", "t"], pa.large_string()), - } - ordered = {**data, **columns} if data_first else {**columns, **data} - return pa.table(ordered) - - -def _assert_refused( - exc: BaseException, encoded_in_order: tuple[str, ...], plain: tuple[str, ...] -) -> None: - """The message says dictionary tags are not supported, names each encoded column - in tag order with its type, and names no plain tag.""" - assert isinstance(exc, InputValidationError) - assert not isinstance(exc, RowIdentifierError) - message = str(exc) - assert NOT_SUPPORTED in message - positions = [ - message.index(f"tag column {name!r} has type dictionary<") - for name in encoded_in_order - ] - assert positions == sorted(positions) - for name in plain: - assert f"tag column {name!r}" not in message - - -def _in_tag_order(tags: tuple[str, ...], encoded: tuple[str, ...]) -> tuple[str, ...]: - return tuple(t for t in tags if t in encoded) - - -# ── a raw ArrowTableStream ────────────────────────────────────────────────── - - -@pytest.mark.parametrize("data_first", [False, True]) -@pytest.mark.parametrize("data_tags", [(), ("a",), ("a", "b")]) -@pytest.mark.parametrize("encoded", ENCODED) -@pytest.mark.parametrize("tags", TAG_ORDERS) -@pytest.mark.parametrize("kind", sorted(VALUES)) -def test_a_raw_stream_refuses_dictionary_tags( - 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 - ) - plain = tuple(t for t in tags if t not in encoded) - _assert_refused(info.value, _in_tag_order(tags, encoded), plain) - - -# ── ArrowTableSource ──────────────────────────────────────────────────────── - - -@pytest.mark.parametrize( - "tag_only_columns", - [True, False, ["a"], ["b"]], - ids=["tag-only", "data-tags", "a-plain", "b-plain"], -) -@pytest.mark.parametrize("encoded", ENCODED) -@pytest.mark.parametrize("tags", TAG_ORDERS) -@pytest.mark.parametrize("kind", sorted(VALUES)) -def test_an_arrow_table_source_refuses_dictionary_tags( - kind: str, tags: tuple[str, ...], encoded: tuple[str, ...], tag_only_columns: Any -) -> None: - """Plain tags and data-tags alike: a data-tag is a tag.""" - with pytest.raises(InputValidationError) as info: - ArrowTableSource( - _table(kind, encoded), - tag_columns=list(tags), - tag_only_columns=tag_only_columns, - ) - plain = tuple(t for t in tags if t not in encoded) - _assert_refused(info.value, _in_tag_order(tags, encoded), plain) - - -@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_tag( - kind: str, record_id_columns: list[str] -) -> None: - """The builder checks the tags 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, ("a",), ("b",)) - - -def test_a_dictionary_tag_is_refused_before_anything_is_hashed( - monkeypatch: pytest.MonkeyPatch, -) -> None: - from orcapod.core.sources import stream_builder - - def _never(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("the source hashed before checking its tags") - - monkeypatch.setattr(stream_builder, "row_identifiers", _never) - with pytest.raises(InputValidationError, match=NOT_SUPPORTED): - ArrowTableSource( - _table("string", ("b",)), tag_columns=["a", "b"], tag_only_columns=True - ) - - -def test_the_message_gives_the_type_and_its_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": [1, 2], - } - ) - with pytest.raises(InputValidationError) as info: - ArrowTableSource(table, tag_columns=["a", "b"], tag_only_columns=True) - message = str(info.value) - assert ( - "tag column 'a' has type dictionary " - "(decoded: string)" in message - ) - assert ( - "tag column 'b' has type dictionary " - "(decoded: double)" in message - ) - - -# ── data frames ───────────────────────────────────────────────────────────── - - -def _pandas(encoded: tuple[str, ...]) -> pd.DataFrame: - # String categories: a pandas Categorical of integers reaches the source as its - # integers (the frame goes through polars, which has no integer Categorical). - frame = pd.DataFrame( - { - "a": ["x", "y", "x"], - "b": ["p", "p", "q"], - "v": [1.0, 2.0, 3.0], - "w": [1, 2, 3], - } - ) - for name in encoded: - frame[name] = frame[name].astype("category") - return frame - - -def _polars(encoded: tuple[str, ...], dtype: str) -> pl.DataFrame: - frame = pl.DataFrame( - { - "a": ["x", "y", "x"], - "b": ["p", "p", "q"], - "v": [1.0, 2.0, 3.0], - "w": [1, 2, 3], - } - ) - target = ( - pl.Categorical() if dtype == "Categorical" else pl.Enum(["p", "q", "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", ENCODED) -@pytest.mark.parametrize("tags", TAG_ORDERS) -@pytest.mark.parametrize("frame_kind", ["pandas", "polars-Categorical", "polars-Enum"]) -def test_a_data_frame_source_refuses_categorical_tags( - 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 - ) - plain = tuple(t for t in tags if t not in encoded) - _assert_refused(info.value, _in_tag_order(tags, encoded), plain) - - -# ── a polling source's batches, read sync and async ───────────────────────── - - -class _CategoricalImpl: - """Fetches one batch whose tag ``a`` is a polars Categorical.""" - - def identity(self) -> str: - return "categorical-impl" - - def to_config(self) -> None: - return None - - @classmethod - def from_config(cls, config: Any) -> _CategoricalImpl: - return cls() - - 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, "w": int}) - - 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], "w": [1, 2]} - ).with_columns(pl.col("a").cast(pl.Categorical())) - return Cursor(value=1), frame - - async def close(self) -> None: - return None - - -def _polling_source() -> PollingSource[int]: - return PollingSource( - _CategoricalImpl(), - tag_columns=["b", "a"], - record_id_columns="b", - polling_config=PollingConfig(duration=0.01), - ) - - -def test_a_polling_source_refuses_a_categorical_tag_on_a_sync_read() -> None: - with pytest.raises(InputValidationError) as info: - _polling_source().as_table() - _assert_refused(info.value, ("a",), ("b",)) - - -@pytest.mark.parametrize( - "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] -) -def test_a_job_over_a_polling_source_refuses_a_categorical_tag( - orchestrator: type, -) -> None: - job = PipelineJob(name="itl1264", database=InMemoryArrowDatabase()) - with job: - _polling_source().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=NOT_SUPPORTED), - ): - if orchestrator is AsyncPipelineOrchestrator: - asyncio.run(job.run_async()) - else: - job.run(orchestrator=orchestrator()) - - -# ── a tag 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 == "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", -} - - -# 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(a: pa.Array[Any], layout: str) -> pa.Table: - """Tag ``a`` (the column under test), tag ``b`` and data ``v``, ``w`` in ``layout``.""" - columns: dict[str, pa.Array[Any]] = { - "a": a, - "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()), - } - 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("build", ["source", "stream"]) -@pytest.mark.parametrize("kind", ["list", "struct", "list_view", "large_list_view"]) -def test_a_tag_containing_a_dictionary_is_refused( - kind: str, build: str, tag_order: tuple[str, str], layout: str, roles: str -) -> None: - table = _nested_table(_nested(kind), 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(r"tag column 'a' has type \S.*dictionary<", message) - if build == "source": - assert f"(decoded: {DECODED[kind]})" in message - assert "tag column 'b'" 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("kind", ["list_view", "large_list_view"]) -def test_a_list_view_tag_without_a_dictionary_is_handled_as_before( - kind: 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), 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, ("a", "b")) - for name in ("b", "a"): - 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 - - -@pytest.mark.parametrize("dtype", ["Categorical", "Enum"]) -def test_a_frame_decoded_with_polars_builds(dtype: str) -> None: - frame = _polars(("a", "b"), dtype).with_columns(pl.col("a", "b").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")) - for name in ("a", "b"): - 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 tag ────────────────────────────────────── - - -def _data_source() -> ArrowTableSource: - """Two plain tags; data columns ``v`` (dictionary-encoded float) and ``u`` - (dictionary-encoded string) and ``w`` plain.""" - return ArrowTableSource( - pa.table( - { - "a": ["x", "y", "x"], - "v": pa.array([1.5, 2.5, 1.5]).dictionary_encode(), - "b": [7, 7, 8], - "u": pa.array(["r", "s", "r"]).dictionary_encode(), - "w": [1, 2, 3], - } - ), - tag_columns=["a", "b"], - tag_only_columns=True, - ) - - -@pytest.mark.parametrize("columns", [["v"], ["u", "v"], ["w", "u"]]) -def test_tag_by_refuses_a_dictionary_data_column(columns: list[str]) -> None: - """``TagBy`` refuses it before any stream is built (its Python type is ``Any``).""" - with pytest.raises(InputValidationError, match="cannot be a tag"): - _data_source().tag_by(columns) - - -# ── dictionary-encoded DATA columns are accepted as before ─────────────────── - - -@pytest.mark.parametrize("tags", [["a", "b"], ["b", "a"]]) -def test_dictionary_data_columns_are_accepted_unchanged(tags: list[str]) -> None: - """Not covered by the decision: the source keeps them dictionary-encoded.""" - source = ArrowTableSource( - _data_source().as_table(), tag_columns=tags, tag_only_columns=True - ) - tag_keys, data_keys = source.keys() - assert tag_keys == tuple(tags) - assert data_keys == ("v", "u", "w") - table = source.as_table() - assert pa.types.is_dictionary(table.schema.field("v").type) - assert pa.types.is_dictionary(table.schema.field("u").type) - stream = ArrowTableStream(_data_source().as_table(), tag_columns=tags) - assert pa.types.is_dictionary(stream.as_table().schema.field("u").type) From 153067d0755dbc2ab90ad1585cbb410a343c2e26 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 20:37:15 -0800 Subject: [PATCH 06/11] test(dictionary_columns): type the column-name tuple so the set difference type-checks (ITL-1264) Co-Authored-By: Claude Opus 5.5 --- tests/test_core/sources/test_dictionary_columns_refused.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index d7a814bfc..173c35227 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -80,7 +80,7 @@ # Tags, data, both, one of each, all. ENCODED = [("a",), ("a", "b"), ("v",), ("v", "w"), ("b", "w"), ("a", "b", "v", "w")] DATA = ("v", "w") -ALL = ("a", "b", "v", "w") +ALL: tuple[str, ...] = ("a", "b", "v", "w") def _table(kind: str, encoded: tuple[str, ...], data_first: bool = False) -> pa.Table: From 713bbdaef4f08f3783a12b1368a77db3e972cee0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 21:20:41 -0800 Subject: [PATCH 07/11] fix(dictionary_columns): a run-end-encoded column holding a dictionary is refused; decoding docs keep the field (ITL-1264) CodeRabbit on PR 455: decode_dictionaries now decodes the values of a run-end-encoded type, so such a column is refused like the other containers. The troubleshooting entry, the sources page sample and the changelog decode with the original field (nullability and metadata kept), keep the table set_column returns, and say how to decode a dictionary nested in a struct or list. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 2 +- CLAUDE.md | 2 +- changelog.d/ITL-1264.md | 16 ++++++++++++---- docs/concepts/sources.md | 8 ++++++-- docs/troubleshooting.md | 18 ++++++++++++++---- src/orcapod/utils/arrow_utils.py | 9 +++++++-- src/orcapod/utils/schema_utils.py | 7 ++++--- .../sources/test_dictionary_columns_refused.py | 5 +++++ tests/test_utils/test_arrow_utils.py | 5 +++++ 9 files changed, 55 insertions(+), 17 deletions(-) diff --git a/.zed/rules b/.zed/rules index bb70a1406..8b190b5d3 100644 --- a/.zed/rules +++ b/.zed/rules @@ -995,7 +995,7 @@ the plan"; November 19, 2026, ITL-1277: "safe default, though could be inconveni 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, extension storage) raises InputValidationError naming each such +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 diff --git a/CLAUDE.md b/CLAUDE.md index 7f3857496..f000f71ff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1039,7 +1039,7 @@ the plan"; November 19, 2026, ITL-1277: "safe default, though could be inconveni 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, extension storage) raises `InputValidationError` naming each such +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 diff --git a/changelog.d/ITL-1264.md b/changelog.d/ITL-1264.md index cc01fada1..f36bd3b65 100644 --- a/changelog.d/ITL-1264.md +++ b/changelog.d/ITL-1264.md @@ -11,10 +11,18 @@ 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 - `column.cast(column.type.value_type)` or polars `pl.col(name).cast(pl.String)`. 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. + polars `Categorical` or `Enum`. Decode the column first: + - with pyarrow, cast a top-level dictionary column to its value type, + `column.cast(column.type.value_type)`; + - with pyarrow, cast a column that holds a dictionary inside it (a struct with a + dictionary field, a list of dictionary values) to the decoded type the error message + gives, for example `column.cast(pa.struct([("k", pa.string()), ("n", pa.int64())]))`; + - with polars, `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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index f2aea6ca3..acd9c49e2 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -118,9 +118,13 @@ except InputValidationError as exc: decoded = coded for name in ("session", "response"): - column = decoded[name] + 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), name, column.cast(column.type.value_type) + 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) diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6ee8134bc..f71e7f589 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -40,10 +40,20 @@ example a list of dictionary values). This comes from an Arrow table built with 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, -`table.set_column(i, name, table[name].cast(table[name].type.value_type))` (for a nested -dictionary, cast to the decoded type the message gives); with polars, -`df.with_columns(pl.col(name).cast(pl.String))`. Or keep the data frame as a value in a cell: +**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))`. + +With polars, `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). diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 7ccd7e9e7..dfec7944c 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -197,8 +197,8 @@ 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 or a union becomes its value - type, and nested fields + 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 @@ -235,6 +235,11 @@ def decode_dictionaries(arrow_type: "pa.DataType") -> "pa.DataType": 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) if pa.types.is_struct(arrow_type): fields = [f.with_type(decode_dictionaries(f.type)) for f in arrow_type] return pa.struct(fields) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 98c73a922..32928a260 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -699,9 +699,10 @@ def dictionary_columns( 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, 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. + 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 diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index 173c35227..a1b3482e3 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -430,6 +430,10 @@ def _nested(kind: str) -> pa.Array[Any]: 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 @@ -442,6 +446,7 @@ def _nested(kind: str) -> pa.Array[Any]: "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)) diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index f147c050c..5c6729a58 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -1101,6 +1101,7 @@ class TestDecodeDictionaries: 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()), @@ -1120,6 +1121,10 @@ def test_a_type_without_a_dictionary_is_returned_as_it_is(self, arrow_type): (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), + 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())]), From 7a683f7d4c3afbe2ef1e74931e89c5a7311a93da Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 21:24:34 -0800 Subject: [PATCH 08/11] fix(arrow_utils): targeted pyright ignores for run_end_encoded's narrow stub (ITL-1264) The pyarrow stubs type run_end_encoded's value type as a basic type only; Arrow accepts any type, a dictionary included. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/utils/arrow_utils.py | 2 +- tests/test_utils/test_arrow_utils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index dfec7944c..31509a008 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -239,7 +239,7 @@ def decode_dictionaries(arrow_type: "pa.DataType") -> "pa.DataType": 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) + 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) diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 5c6729a58..b83d14dd2 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -1122,7 +1122,7 @@ def test_a_type_without_a_dictionary_is_returned_as_it_is(self, arrow_type): (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), + 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())), From 364196e491444fcdc482808e387c0ea30e8b123f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 21:32:49 -0800 Subject: [PATCH 09/11] test(dictionary_columns): every container closed, a tested nested decoding recipe, the message's recipe keeps the field (ITL-1264) decode_dictionaries is tested for a dictionary of dictionaries, a sparse union, a map key, and an extension over a list, a list view or a run-end-encoded type. A list or struct holding a dictionary, decoded as the message says (cast to the decoded type it gives, keeping the field), builds with its nullability and metadata. The error message gives the same field-keeping recipe as the docs. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/utils/schema_utils.py | 10 +++-- .../test_dictionary_columns_refused.py | 44 +++++++++++++++++++ tests/test_utils/test_arrow_utils.py | 26 +++++++++++ 3 files changed, 76 insertions(+), 4 deletions(-) diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 32928a260..424f81a23 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -782,10 +782,12 @@ def role(name: str) -> str: 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, " - "column.cast(column.type.value_type) decodes a dictionary column (cast a " - "column holding a dictionary inside it to the decoded type shown); with " - "polars, pl.col(name).cast(pl.String) decodes a Categorical or Enum column." + "column before building the source or stream. With pyarrow, cast it to its " + "decoded type (column.cast(column.type.value_type) for a dictionary column, " + "the decoded type shown for a column holding a dictionary inside it) and " + "replace it keeping its field: table.set_column(i, field.with_type(decoded), " + "column.cast(decoded)). With polars, pl.col(name).cast(pl.String) decodes a " + "Categorical or Enum column." ) diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index a1b3482e3..1266b543f 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -46,6 +46,7 @@ from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.types import Cursor, PollingConfig, Schema +from orcapod.utils.arrow_utils import decode_dictionaries NOT_SUPPORTED = "dictionary-encoded columns are not currently supported in Orcapod" @@ -125,6 +126,9 @@ def _assert_refused( if name not in named: assert f"column {name!r}" not in message assert "column.cast(column.type.value_type)" in message + assert ( + "table.set_column(i, field.with_type(decoded), column.cast(decoded))" in message + ) assert "pl.col(name).cast(pl.String)" in message @@ -573,6 +577,46 @@ def test_a_table_decoded_with_pyarrow_builds(kind: str) -> None: 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" + + @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( diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index b83d14dd2..253c5d9f0 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -1091,6 +1091,20 @@ def __arrow_ext_deserialize__(cls, storage_type, serialized): _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.""" @@ -1140,6 +1154,18 @@ def test_a_type_without_a_dictionary_is_returned_as_it_is(self, arrow_type): 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())), + (_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): From d0d5e170a96d75f3ed0d25234570f377f982b268 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Wed, 18 Nov 2026 22:06:39 -0800 Subject: [PATCH 10/11] fix(dictionary_columns): refuse before system columns are dropped; any extension type; working recipes for every kind (ITL-1264) CodeRabbit on PR 455 (a7c363b0): - The source builder checks for dictionaries before dropping system columns, so a hand-built meta, source-info or system-tag column holding one is refused, not dropped silently (dictionary-free ones are still stripped). - decode_dictionaries walks pa.BaseExtensionType (pa.opaque and the other built-in extension types too), so such a type over a dictionary is refused. - The message, the troubleshooting page and the changelog give a recipe that works for every kind: a cast to the decoded type shown, and a step first for a dictionary whose values hold one, a list view and a run-end-encoded column; each recipe is tested. The polars and pandas samples keep the returned frame and run in the doc test. - The before-hashing test also makes the Arrow hasher's hash_table raise. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1264.md | 15 +- docs/concepts/sources.md | 32 +++- docs/troubleshooting.md | 14 +- src/orcapod/core/sources/stream_builder.py | 18 ++- src/orcapod/utils/arrow_utils.py | 4 +- src/orcapod/utils/schema_utils.py | 16 +- .../test_dictionary_columns_refused.py | 143 +++++++++++++++++- tests/test_utils/test_arrow_utils.py | 9 ++ 8 files changed, 222 insertions(+), 29 deletions(-) diff --git a/changelog.d/ITL-1264.md b/changelog.d/ITL-1264.md index f36bd3b65..a4a88a89f 100644 --- a/changelog.d/ITL-1264.md +++ b/changelog.d/ITL-1264.md @@ -12,12 +12,15 @@ 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 a top-level dictionary column to its value type, - `column.cast(column.type.value_type)`; - - with pyarrow, cast a column that holds a dictionary inside it (a struct with a - dictionary field, a list of dictionary values) to the decoded type the error message - gives, for example `column.cast(pa.struct([("k", pa.string()), ("n", pa.int64())]))`; - - with polars, `pl.col(name).cast(pl.String)`. + - 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 diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index acd9c49e2..ee8965c69 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -131,11 +131,33 @@ print(source.as_table().schema.field("session").type) # large_string ``` -With polars, `df.with_columns(pl.col("session").cast(pl.String))` decodes a `Categorical` or -`Enum` column. With pandas, `df["session"].astype(df["session"].cat.categories.dtype)` decodes -a `Categorical` of strings; a `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. +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 diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f71e7f589..690d8f6ec 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -53,7 +53,19 @@ With pyarrow, keep the field's name, nullability and metadata, and keep the tabl - Replace the column: `table = table.set_column(table.schema.get_field_index(name), field.with_type(decoded), table[name].cast(decoded))`. -With polars, `df.with_columns(pl.col(name).cast(pl.String))`. Or keep the data frame as a value in a cell: +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). diff --git a/src/orcapod/core/sources/stream_builder.py b/src/orcapod/core/sources/stream_builder.py index 3d221c012..c0406e3e6 100644 --- a/src/orcapod/core/sources/stream_builder.py +++ b/src/orcapod/core/sources/stream_builder.py @@ -378,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) @@ -397,14 +407,6 @@ def build( f"Available columns: {list(table.column_names)}" ) - # 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. - 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 - ) - # 3. The row identifiers (validates the key columns). identifiers = row_identifiers( table, normalize_record_id_columns(record_id_columns) or () diff --git a/src/orcapod/utils/arrow_utils.py b/src/orcapod/utils/arrow_utils.py index 31509a008..e2e4f4367 100644 --- a/src/orcapod/utils/arrow_utils.py +++ b/src/orcapod/utils/arrow_utils.py @@ -210,7 +210,9 @@ def decode_dictionaries(arrow_type: "pa.DataType") -> "pa.DataType": Returns: The decoded type. """ - if isinstance(arrow_type, pa.ExtensionType): + # 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): diff --git a/src/orcapod/utils/schema_utils.py b/src/orcapod/utils/schema_utils.py index 424f81a23..78a18433a 100644 --- a/src/orcapod/utils/schema_utils.py +++ b/src/orcapod/utils/schema_utils.py @@ -782,12 +782,16 @@ def role(name: str) -> str: 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 its " - "decoded type (column.cast(column.type.value_type) for a dictionary column, " - "the decoded type shown for a column holding a dictionary inside it) and " - "replace it keeping its field: table.set_column(i, field.with_type(decoded), " - "column.cast(decoded)). With polars, pl.col(name).cast(pl.String) decodes a " - "Categorical or Enum column." + "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." ) diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index 1266b543f..7d45d4cff 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -46,6 +46,8 @@ 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" @@ -125,11 +127,12 @@ def _assert_refused( for name in all_names: if name not in named: assert f"column {name!r}" not in message - assert "column.cast(column.type.value_type)" in message assert ( "table.set_column(i, field.with_type(decoded), column.cast(decoded))" in message ) - assert "pl.col(name).cast(pl.String)" 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 ────────────────────────────────────────────────── @@ -211,6 +214,8 @@ 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 @@ -276,6 +281,65 @@ def test_a_raw_stream_refuses_a_dictionary_in_orcapods_own_columns( 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 ───────────────────────────────────────────────────────────── @@ -617,6 +681,81 @@ def test_a_nested_dictionary_decoded_as_the_message_says_builds(kind: str) -> No 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( diff --git a/tests/test_utils/test_arrow_utils.py b/tests/test_utils/test_arrow_utils.py index 253c5d9f0..26bbddda1 100644 --- a/tests/test_utils/test_arrow_utils.py +++ b/tests/test_utils/test_arrow_utils.py @@ -1161,6 +1161,15 @@ def test_a_type_without_a_dictionary_is_returned_as_it_is(self, arrow_type): ), (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 From b11f247936fcef70889a1e478034a1fd3cd2cb0d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Thu, 19 Nov 2026 15:18:17 -0800 Subject: [PATCH 11/11] fix(group_by): drop GroupBy's dictionary handling, unreachable now that streams refuse dictionaries (ITL-1264) Merged main (3d3dec21: PRs 449, 451, 452, 458, 459, 460). PR 458's GroupBy decoded dictionary-encoded tags in one place (_without_dictionary, a branch in _value_type and _values_of). Every stream refuses a dictionary-encoded column, so GroupBy never sees one: the handling is removed and a dictionary is a type GroupBy has no order for, refused alike by validation and preparation. Its dictionary-over-Path test now asserts the refusal at stream construction; the agreement test lists the dictionary types among those without an order. The raw Arrow preparation tests of arrow_keys (PR 459) keep their dictionary key. Co-Authored-By: Claude Opus 5.5 --- tests/test_core/operators/test_group_by_nan_keys.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 00f72edf7..1313f99ee 100644 --- a/tests/test_core/operators/test_group_by_nan_keys.py +++ b/tests/test_core/operators/test_group_by_nan_keys.py @@ -16,7 +16,7 @@ import itertools import json import struct -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest