diff --git a/.zed/rules b/.zed/rules index 67395d99a..397022dad 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1455,8 +1455,18 @@ data. The rules: - `-> datetime` is an instant, stored as `timestamp[us, tz=UTC]` (developer, November 21, 2026, ITL-1268; the mapping does not change in data context v1). Every Arrow timestamp type reads as `datetime`. One rule stores a Python `datetime` the type converter - converts (function outputs at any depth, `DictSource` and `ListSource` values; not a - `DataFrameSource` over a plain dict or list, ITL-1330): `universal_converter.storable_instant`. + converts (function outputs at any depth, `DictSource` and `ListSource` values): `universal_converter.storable_instant`. A + `DataFrameSource` takes data frames only (developer, November 28, 2026, ITL-1330: "we could + expand it in the future if we really need to"): a pandas or Polars `DataFrame`, or an + object exporting an Arrow C stream or C array, whose columns keep their types; a dict, a + list, any other container of Python values, a NumPy array, a `Series` and a `LazyFrame` + are refused when the source is built (`data_frame_source._require_data_frame`, a + `TypeError` naming the type and the remedy), never typed through Polars. + Pandas `object` columns require an explicit `schema=` (ITL-1330). With a schema, + the source uses the existing native frame conversion and Arrow schema cast. + Polars `Object` columns use the existing conversion with or without a schema. + Use a typed pandas datetime column to preserve + precision and timezone through frame conversion. An aware value of any zone is stored as its exact instant (an offset with a part below one second is converted to UTC first: Arrow drops that part; any other value is handed to Arrow as before, so no stored value moves); a naive value raises `NaiveDatetimeError` (strict policy); a diff --git a/CLAUDE.md b/CLAUDE.md index 3b9ba4940..76bda60f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1503,8 +1503,18 @@ data. The rules: - `-> datetime` is an instant, stored as `timestamp[us, tz=UTC]` (developer, November 21, 2026, ITL-1268; the mapping does not change in data context v1). Every Arrow timestamp type reads as `datetime`. One rule stores a Python `datetime` the type converter - converts (function outputs at any depth, `DictSource` and `ListSource` values; not a - `DataFrameSource` over a plain dict or list, ITL-1330): `universal_converter.storable_instant`. + converts (function outputs at any depth, `DictSource` and `ListSource` values): `universal_converter.storable_instant`. A + `DataFrameSource` takes data frames only (developer, November 28, 2026, ITL-1330: "we could + expand it in the future if we really need to"): a pandas or Polars `DataFrame`, or an + object exporting an Arrow C stream or C array, whose columns keep their types; a dict, a + list, any other container of Python values, a NumPy array, a `Series` and a `LazyFrame` + are refused when the source is built (`data_frame_source._require_data_frame`, a + `TypeError` naming the type and the remedy), never typed through Polars. + Pandas `object` columns require an explicit `schema=` (ITL-1330). With a schema, + the source uses the existing native frame conversion and Arrow schema cast. + Polars `Object` columns use the existing conversion with or without a schema. + Use a typed pandas datetime column to preserve + precision and timezone through frame conversion. An aware value of any zone is stored as its exact instant (an offset with a part below one second is converted to UTC first: Arrow drops that part; any other value is handed to Arrow as before, so no stored value moves); a naive value raises `NaiveDatetimeError` (strict policy); a diff --git a/changelog.d/ITL-1330.md b/changelog.d/ITL-1330.md new file mode 100644 index 000000000..04a67d124 --- /dev/null +++ b/changelog.d/ITL-1330.md @@ -0,0 +1,31 @@ +### Breaking changes and migration + +- `DataFrameSource` accepts data frames only (ITL-1330): a pandas `DataFrame`, a Polars + `DataFrame`, or an object that exports an Arrow C stream or array of structs (a pyarrow + `Table`, `RecordBatch` or `RecordBatchReader`, a frame of another library). Python + containers, NumPy arrays, pandas and Polars `Series`, Polars `LazyFrame` and non-struct + Arrow exporters raise `TypeError` with the input type and a remedy. Move Python values + to `DictSource` (rows as a list of dicts) or `ListSource` (a list of values), which + type them by Orcapod's rules. Convert a mapping of Python columns to row dictionaries + before passing it to `DictSource`. + To keep Polars' own typing, build the frame yourself: + `DataFrameSource(pl.DataFrame(data), ...)`; a `Series` takes `to_frame()`, a `LazyFrame` + `collect()`. For NumPy values, including tuples and mappings of arrays, or non-struct + Arrow data, build a `pyarrow.Table` with named columns of supported types and pass it + to `ArrowTableSource`. Typed data frames keep the same rows, types, default source id + and hashes. A `DataFrameSource` keeps its data in memory and is never saved, so a loaded + job has no data for its slot until a source is bound. +- Pandas `object` columns require an explicit `schema=`. With a schema, the source uses + the existing frame conversion and Arrow schema cast. Polars `Object` columns use the + existing conversion with or without a schema. Convert a pandas column to a typed + dtype with `astype("string")`, `pd.to_datetime`, or `convert_dtypes()`. + Use a typed datetime column to retain nanoseconds with a + `timestamp[ns]` field. + +### Fixed + +- A `DataFrameSource` given a dict or a list of Python values no longer types them through + Polars, around Orcapod's rules (ITL-1330): a `pandas.Timestamp` with nanoseconds was + stored as `timestamp[us, tz=UTC]` with the nanoseconds dropped and no error, and a naive + `datetime` as an unzoned `timestamp[us]`, although a `DictSource` refuses both. Such an + input is now refused (above). diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 3a3531e23..f007859c6 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -346,10 +346,9 @@ function: - The same rule holds for a `datetime` inside a list, a dict or a class field, and for the Python values of a `DictSource` or a `ListSource`. There it raises `NaiveDatetimeError` or `SubMicrosecondDatetimeError`, both `ValueError`s, and names the value. A - `DataFrameSource` given a plain dict or list is not covered yet: Polars converts the - values before Orcapod sees them, so a naive value is stored without a zone and - nanoseconds are dropped (ITL-1330). Over a real data frame, a `DataFrameSource` keeps - each timestamp column's unit and zone as given. + `DataFrameSource` takes data frames only: given a dict or a list of Python values it + raises `TypeError` and points to `DictSource` and `ListSource`. Over a data frame it + keeps each timestamp column's unit and zone as given. A function over a column without a zone therefore says which zone its wall times are in: diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 6da884ab0..cc1da676c 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -29,10 +29,56 @@ hashing) and produces the final immutable stream. | `ArrowTableSource` | PyArrow `Table` | Accepts an Arrow table directly | | `DictSource` | `list[dict]` | Each dict becomes one (Tag, Data) pair | | `ListSource` | `list[Any]` | Each element stored under the data column given by `name`; the tag defaults to `element_index` | -| `DataFrameSource` | Pandas or Polars `DataFrame` | Converts via Arrow | +| `DataFrameSource` | Pandas or Polars `DataFrame`, or an Arrow-exporting object | Data frames only; columns keep their types | | `CSVSource` | File path (string) | Reads CSV into Arrow | | `DeltaTableSource` | Directory path | Reads Delta Lake table | +`DataFrameSource` takes a data frame and nothing else: a pandas or Polars `DataFrame`, or an +object that exports an Arrow C stream or C array of structs (a pyarrow `Table`, `RecordBatch` or +`RecordBatchReader`, a frame of another library). Its columns keep the types they have. A +dict, a list or any other container of Python values is refused when the source is built, and +so are a NumPy array, a pandas or Polars `Series` and a Polars `LazyFrame`: Python values go +to `DictSource` or `ListSource`, which type them by Orcapod's rules (a naive `datetime` is +refused there, and nanoseconds are never dropped). Convert a mapping of Python columns to +row dictionaries for `DictSource`. For NumPy data, including tuples and mappings of +arrays, or non-struct Arrow data, build a `pyarrow.Table` with named columns of supported +types and pass it to `ArrowTableSource`. To have Polars infer the types, build a frame +yourself and pass it to `DataFrameSource`. + +Pandas `object` columns require an explicit `schema=`. With a schema, the source converts +the frame, discards auxiliary system columns, and casts the Arrow table to the schema. +Polars `Object` columns use the existing conversion with or without a schema. +For example, an object column can lose timestamp precision during frame conversion +before the cast. Use a typed datetime column from `pd.to_datetime` to retain +nanoseconds with a `timestamp[ns]` field. `astype("string")` and `convert_dtypes()` +can also give pandas columns a typed dtype before construction. + +```python +import polars as pl + +from orcapod.sources import DataFrameSource, DictSource + +columns = {"session": ["s1", "s2"], "trial": [1, 2], "rate": [0.5, 0.75]} +try: + DataFrameSource(columns, tag_columns=["session", "trial"]) +except TypeError as error: + print(str(error).split(";")[1].split(".")[0].strip()) +# got dict + +rows = [ + {"session": "s1", "trial": 1, "rate": 0.5}, + {"session": "s2", "trial": 2, "rate": 0.75}, +] +print(DictSource(rows, tag_columns=["session", "trial"], tag_only_columns=True).keys()) +# (('session', 'trial'), ('rate',)) +print( + DataFrameSource( + pl.DataFrame(columns), tag_columns=["session", "trial"], tag_only_columns=True + ).keys() +) +# (('session', 'trial'), ('rate',)) +``` + `orcapod.sources` also provides database-backed sources (`SQLiteTableSource`, `PostgreSQLTableSource`, `SpiralDBTableSource`) and `PollingSource` for data that arrives over time (provisional in this release, see [Provisional sources](#provisional-sources)); see the @@ -284,7 +330,7 @@ print(source.as_table().schema.field("session").type) ``` 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 +With pandas, `astype("string")` decodes a `Categorical` of strings to a typed column. Both return a new frame or column: keep it before building the source. ```python @@ -302,7 +348,7 @@ print(DataFrameSource(frame, tag_columns=["session"], tag_only_columns=True).key 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) +table["session"] = table["session"].astype("string") print(DataFrameSource(table, tag_columns=["session"], tag_only_columns=True).keys()) # (('session',), ('trial',)) ``` diff --git a/docs/dev/design_issues/ITL-1330-S6.md b/docs/dev/design_issues/ITL-1330-S6.md new file mode 100644 index 000000000..0c6ec1427 --- /dev/null +++ b/docs/dev/design_issues/ITL-1330-S6.md @@ -0,0 +1,44 @@ +## `src/orcapod/core/sources/` + +### S6 — A `DataFrameSource` given Python values typed them through Polars, silently lossy +**Status:** resolved +**Severity:** high +**Issue:** ITL-1330 + +`DataFrameSource` passed whatever it was given to `pl.DataFrame(data)`, so it also built from +a dict or a list of Python values, and Polars inferred the types before the data context's +type converter saw anything. The converter's rules did not apply on that path: + +- `DataFrameSource({"id": [1], "v": [pd.Timestamp("2026-01-02T03:04:05.123456789Z")]})` + stored `timestamp[us, tz=UTC]`: 789 nanoseconds dropped, no error. +- A naive `datetime` was stored as an unzoned `timestamp[us]`, while the same value in a + `DictSource` raises `NaiveDatetimeError`. + +Anything else Polars can make a frame of built too: a string (one row, a column named +`column_0`), a generator, a NumPy array, a Polars `Series`. + +**Fix:** `DataFrameSource` accepts data frames only (developer, November 28, 2026, option +(a): "we could expand it in the future if we really need to"). A data frame is a pandas +`DataFrame`, a Polars `DataFrame`, or an object that exports an Arrow C stream or C array of +a struct (a pyarrow `Table`, `RecordBatch`, `RecordBatchReader`, a struct array, a frame of +another library). Everything else is refused before frame conversion by one rule, +`data_frame_source._require_data_frame`: a `TypeError` that names the type given and its +remedy (`DictSource` / `ListSource`, or `pl.DataFrame(data)` for a +caller who wants Polars' typing, `ArrowTableSource` with named columns for NumPy inputs +including tuples and mappings of arrays, `to_frame()` for a `Series`, and `collect()` +for a `LazyFrame`). +Mixed NumPy and Python row iterators can pass `pl.DataFrame(data).to_arrow()` to +`ArrowTableSource`. Sequences and iterators of Polars Series with distinct names can +pass `pa.table({series.name: series for series in data})` to the same source when +their types are supported. Refusing an iterator leaves it available for either migration. +A Polars `Series` exports an Arrow C stream and is excluded explicitly. Every supported input +builds as before (`tests/test_core/sources/test_data_frame_source_inputs.py` pins the default +source id measured before the change). + +Pandas `object` columns require an explicit `schema=`. With a schema, the existing +frame conversion discards auxiliary system columns before the Arrow schema cast. +Polars `Object` columns use the existing conversion with or without a schema. +The native conversion can drop nanoseconds from timestamps in pandas object columns +before the cast. A typed `datetime64` column keeps its unit and zone through frame +conversion. The Arrow importer reports non-struct exports with the input type and +points to `ArrowTableSource` with named columns of supported types. diff --git a/docs/dev/scripts/itl_640/q3ii_builders.py b/docs/dev/scripts/itl_640/q3ii_builders.py index aca2c0b3b..dc25ee80c 100644 --- a/docs/dev/scripts/itl_640/q3ii_builders.py +++ b/docs/dev/scripts/itl_640/q3ii_builders.py @@ -74,7 +74,20 @@ def build(root: Path) -> dict[str, Any]: out: dict[str, Any] = {} for label, make in ( ("DictSource", lambda: DictSource(ROWS, **kw)), - ("DataFrameSource(pandas)", lambda: DataFrameSource(pd.DataFrame(ROWS), **kw)), + ( + "DataFrameSource(pandas)", + lambda: DataFrameSource( + pd.DataFrame(ROWS).astype( + { + "k": "string", + "s": "string", + "d": pd.ArrowDtype(pa.date32()), + "li": pd.ArrowDtype(pa.list_(pa.int64())), + } + ), + **kw, + ), + ), ("DataFrameSource(polars)", lambda: DataFrameSource(pl.DataFrame(ROWS), **kw)), ( "ArrowTableSource(from_pylist)", diff --git a/docs/tutorial/coming-from-pandas-or-polars.md b/docs/tutorial/coming-from-pandas-or-polars.md index 13161309d..1cfee8683 100644 --- a/docs/tutorial/coming-from-pandas-or-polars.md +++ b/docs/tutorial/coming-from-pandas-or-polars.md @@ -209,7 +209,7 @@ def total_present(counts: list[int]) -> int: list_frame = pl_units.head(1).select( "unit", pl.concat_list("n_spikes", pl.lit(None, dtype=pl.Int64)).alias("counts") ) -for frame in (list_frame, pd.DataFrame(list_frame.to_dicts())): +for frame in (list_frame, list_frame.to_pandas(use_pyarrow_extension_array=True)): source = DataFrameSource(frame, tag_columns=["unit"], tag_only_columns=True) print(source.output_schema()[1]["counts"] == list[int]) print(total_present.pod(source).as_table()["total"].to_pylist() == pl_units["n_spikes"].head(1).to_list()) diff --git a/src/orcapod/core/sources/data_frame_source.py b/src/orcapod/core/sources/data_frame_source.py index a435b32fb..e291cb1da 100644 --- a/src/orcapod/core/sources/data_frame_source.py +++ b/src/orcapod/core/sources/data_frame_source.py @@ -1,9 +1,10 @@ from __future__ import annotations import logging -from collections.abc import Collection +from collections.abc import Collection, Iterable, Mapping, Sequence from typing import TYPE_CHECKING, Any, ClassVar, cast +import numpy as np import pandas as pd import polars as pl import pyarrow as pa @@ -23,21 +24,172 @@ from orcapod.utils.schema_utils import _normalize_column_list if TYPE_CHECKING: - from polars._typing import ( - ArrowArrayExportable, - ArrowStreamExportable, - FrameInitTypes, - ) + from polars._typing import ArrowArrayExportable, ArrowStreamExportable logger = logging.getLogger(__name__) +def _exports_arrow(data: object) -> bool: + """Whether ``data`` exports an Arrow C stream or an Arrow C array.""" + return hasattr(data, "__arrow_c_stream__") or hasattr(data, "__arrow_c_array__") + + +def _type_name(kind: type) -> str: + """The name a refusal gives a type: ``dict``, ``polars.Series``, ``numpy.ndarray``. + + A builtin is its own name; any other type is its top-level package and its + qualified name, since the module a library keeps a class in changes between its + versions. + """ + package = kind.__module__.partition(".")[0] + if package == "builtins": + return kind.__qualname__ + return f"{package}.{kind.__qualname__}" + + +def _require_data_frame(data: object) -> None: + """Refuse an input that is not a data frame (ITL-1330). + + A data frame is a pandas ``DataFrame``, a Polars ``DataFrame``, or an object that + exports an Arrow C stream or array of structs (a pyarrow ``Table``, ``RecordBatch`` + or ``RecordBatchReader``, a struct array, a frame of another library). A Polars + ``Series`` is refused even when it exports a struct stream. + + The Arrow import checks the struct schema when materializing the exporter. + + Raises: + TypeError: When ``data`` is not a data frame. The message names the type given + and the remedy. + """ + if isinstance(data, (pd.DataFrame, pl.DataFrame)): + return + if not isinstance(data, pl.Series) and _exports_arrow(data): + return + raise _non_frame_error(data) + + +def _non_frame_error(data: object) -> TypeError: + """Name the rejected input and suggest a source for its shape.""" + received = f"got {_type_name(type(data))}." + arrow_remedy = ( + "Build a pyarrow.Table with named columns of supported column types " + "and pass it to ArrowTableSource." + ) + series_columns_remedy = ( + "For Polars Series with distinct names and supported Arrow types, use " + "ArrowTableSource(pa.table({series.name: series for series in data}))." + ) + if isinstance(data, (pl.Series, pd.Series)): + remedy = "Pass series.to_frame() to DataFrameSource." + elif isinstance(data, pl.LazyFrame): + remedy = "Pass frame.collect() to DataFrameSource." + elif _exports_arrow(data): + remedy = f"The exporter contains non-struct Arrow data. {arrow_remedy}" + elif isinstance(data, np.ndarray): + remedy = ( + f"{arrow_remedy} " + "Or pass pl.DataFrame(data, schema=[...]) to DataFrameSource." + ) + elif isinstance(data, Mapping): + remedy = ( + "For DictSource, convert the mapping of columns to Python row dictionaries. " + "Or pass pl.DataFrame(data) to DataFrameSource." + ) + if any(isinstance(value, np.ndarray) for value in data.values()): + remedy = f"{arrow_remedy} {remedy}" + elif isinstance(data, Sequence) and not isinstance(data, (str, bytes, bytearray)): + item_types = {type(value) for value in data} + if item_types: + names = ", ".join(sorted({_type_name(kind) for kind in item_types})) + received += f" Sequence item types: {names}." + if any(issubclass(kind, np.ndarray) for kind in item_types): + remedy = ( + f"{arrow_remedy} " + "For DictSource, give the columns names in a mapping, convert NumPy " + "arrays to Python lists with tolist(), then build one dictionary per row. " + "Or pass pl.DataFrame(data, schema=[...]) to DataFrameSource." + ) + elif item_types and all(issubclass(kind, Mapping) for kind in item_types): + remedy = "Pass list(data) to DictSource for rows given as dictionaries." + elif item_types and all( + issubclass(kind, pa.RecordBatch) for kind in item_types + ): + remedy = "Pass pyarrow.Table.from_batches(data) to ArrowTableSource." + elif item_types and all(issubclass(kind, pl.Series) for kind in item_types): + remedy = ( + f"{series_columns_remedy} Or use DataFrameSource(pl.DataFrame(data))." + ) + else: + remedy = ( + 'Use ListSource("value", list(data)) to store one value per row. ' + "Or pass pl.DataFrame(data) to DataFrameSource to infer columns." + ) + elif isinstance(data, Iterable) and not isinstance(data, (str, bytes, bytearray)): + # Describe the alternatives without inspecting or advancing the iterable. + remedy = ( + 'For one supported value per row, use ListSource("value", list(data)). ' + "For row dictionaries, use DictSource(list(data)). " + "For positional rows that Polars can infer as supported Arrow columns, " + "including mixed NumPy and Python rows, use " + "ArrowTableSource(pl.DataFrame(data).to_arrow()). " + f"{series_columns_remedy}" + ) + else: + remedy = 'To store one Python value, use ListSource("value", [data]).' + return TypeError( + "DataFrameSource accepts a data frame only (a pandas or Polars DataFrame, or " + "an object that exports an Arrow C stream or array of structs, such as a pyarrow " + f"Table); {received} {remedy}" + ) + + +def _import_arrow_frame(data: ArrowArrayExportable | ArrowStreamExportable) -> pa.Table: + """Materialize an exporter once and give an actionable error for a non-frame.""" + try: + # Like Polars, prefer the array export when both are available. + if hasattr(data, "__arrow_c_array__"): + batch = pa.record_batch(cast("ArrowArrayExportable", data)) + return pa.Table.from_batches([batch]) + return pa.table(cast("ArrowStreamExportable", data)) + except pa.ArrowInvalid as exc: + if not str(exc).startswith( + "Cannot import schema: ArrowSchema describes non-struct type " + ): + raise + raise _non_frame_error(data) from exc + + +def _refuse_undeclared_pandas_object_columns(frame: pd.DataFrame) -> None: + """Refuse pandas object columns when the caller supplies no schema.""" + for label, dtype in frame.dtypes.items(): + if pd.api.types.is_object_dtype(dtype): + raise InputValidationError( + f"Pandas column {str(label)!r} has dtype object. Declare its type with " + "schema=, convert it to a typed dtype (for example astype('string'), " + "pd.to_datetime, or convert_dtypes()), or use DictSource for Python values." + ) + + class DataFrameSource(RootSource): - """A source backed by a Polars DataFrame (or any Polars-compatible data). + """A source backed by a data frame. - The DataFrame is converted to an Arrow table and enriched by + A data frame is a pandas ``DataFrame``, a Polars ``DataFrame``, or an object that + exports an Arrow C stream or an Arrow C array of a struct (a pyarrow ``Table``, + ``RecordBatch`` or ``RecordBatchReader``, a frame of another library). Its columns + keep the types they have. It is converted to an Arrow table and enriched by ``SourceStreamBuilder`` (source-info, schema-hash, system tags). + Data frames only (ITL-1330): a dict, a list or any other container of Python + values, a NumPy array, a Polars or pandas ``Series`` and a Polars ``LazyFrame`` + are refused with a ``TypeError`` when the source is built. Python values go to + ``DictSource`` or ``ListSource``, which type them by Orcapod's rules; a caller who + wants Polars to infer the types passes ``pl.DataFrame(data)``. + + Pandas ``object`` columns require an explicit ``schema``. With a schema, native + frame conversion runs before the Arrow schema cast. Polars ``Object`` columns + use native conversion with or without a schema. For NumPy inputs, supply named + Arrow table columns to ``ArrowTableSource``. + Data-tags (ITL-1023): every declared tag column is a data-tag by default, also a data column of the same name. ``tag_only_columns`` (keyword-only) names the tags kept plain (tag only, not data, as in v0.3); ``True`` keeps all of them plain. @@ -60,7 +212,10 @@ class DataFrameSource(RootSource): def __init__( self, - data: FrameInitTypes, + data: pd.DataFrame + | pl.DataFrame + | ArrowStreamExportable + | ArrowArrayExportable, tag_columns: str | Collection[str] = (), system_tag_columns: Collection[str] = (), source_id: str | None = None, @@ -71,20 +226,18 @@ def __init__( hash_in_key_order: bool = False, **kwargs: Any, ) -> None: + # Check eligibility and declarations before the native frame can infer a type. + _require_data_frame(data) + if schema is None and isinstance(data, pd.DataFrame): + _refuse_undeclared_pandas_object_columns(data) + super().__init__(source_id=source_id, **kwargs) arrow_input_schema = None # Keep pandas and Polars on their native paths even if they export Arrow. # For Arrow inputs, materialize once before Polars drops field metadata. - if not isinstance(data, (pd.DataFrame, pl.DataFrame, pl.Series)) and ( - hasattr(data, "__arrow_c_stream__") or hasattr(data, "__arrow_c_array__") - ): - # Like Polars, prefer the array export when both are available. - if hasattr(data, "__arrow_c_array__"): - batch = pa.record_batch(cast("ArrowArrayExportable", data)) - arrow_input = pa.Table.from_batches([batch]) - else: - arrow_input = pa.table(cast("ArrowStreamExportable", data)) + if not isinstance(data, (pd.DataFrame, pl.DataFrame)): + arrow_input = _import_arrow_frame(data) if schema is None: require_custom_system_tags(arrow_input, system_tag_columns) else: diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index a2f154dec..e22f19d30 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -920,7 +920,7 @@ def _build_stream_from_df(self, df: pl.DataFrame) -> ArrowTableStream | None: skipped so that a spurious all-non-nullable schema is never recorded. """ - # Handle Object-dtype columns (same pattern as DataFrameSource) + # Handle Object-dtype columns in fetched frames. object_columns = [c for c in df.columns if df[c].dtype == pl.Object] if object_columns: sub_table = self.data_context.type_converter.python_dicts_to_arrow_table( diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a748add05..d2ce35429 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -93,8 +93,8 @@ class UnstorableDatetimeError(ValueError): ``datetime`` (``universal_converter.storable_instant``) raises a subclass for what the converter stores: a function's outputs, sync or async, at the top level or inside a list, dict or class field, and the Python values of ``DictSource`` and - ``ListSource``. A ``DataFrameSource`` given a plain dict or list is not covered - (Polars converts the values first; ITL-1330). ``reason`` and + ``ListSource``. A ``DataFrameSource`` takes no Python values: it refuses a dict or + a list when it is built (ITL-1330). ``reason`` and ``hint`` name no value, so a function's ``OutputTypeError`` shows them as they are; the message adds the value. diff --git a/src/orcapod/semantic_types/universal_converter.py b/src/orcapod/semantic_types/universal_converter.py index 678270275..346afb067 100644 --- a/src/orcapod/semantic_types/universal_converter.py +++ b/src/orcapod/semantic_types/universal_converter.py @@ -180,8 +180,9 @@ def storable_instant(value: object, timezone_policy: str) -> datetime: converter maps to an instant at microsecond precision (``timestamp[us, tz=UTC]``). It covers what the converter converts: a function's outputs at any depth, and the Python values of a source that converts them through the converter (``DictSource``, - ``ListSource``). A ``DataFrameSource`` given a plain dict or list hands the values to - Polars first and is not covered (ITL-1330). + ``ListSource``). A ``DataFrameSource`` takes data frames only and refuses a dict or a + list of Python values (ITL-1330), so no Python ``datetime`` reaches storage around + this rule. An aware value of any zone is stored as the instant it names. Arrow computes the instant from the value's UTC offset but drops the part of an offset below one diff --git a/tests/test_core/function_pod/test_datetime_outputs.py b/tests/test_core/function_pod/test_datetime_outputs.py index 27bde122b..e45cdd906 100644 --- a/tests/test_core/function_pod/test_datetime_outputs.py +++ b/tests/test_core/function_pod/test_datetime_outputs.py @@ -641,13 +641,6 @@ def test_a_data_frame_source_keeps_its_timestamp_columns_as_given() -> None: ) -@pytest.mark.xfail( - strict=True, - reason=( - "ITL-1330: DataFrameSource builds a Polars frame from plain Python values " - "before the converter sees them, so the datetime rule does not apply" - ), -) @pytest.mark.parametrize( ("value", "error"), [ @@ -659,18 +652,25 @@ def test_a_data_frame_source_keeps_its_timestamp_columns_as_given() -> None: ], ids=["naive", "sub_microsecond"], ) -def test_a_data_frame_source_over_plain_values_follows_the_rule( +def test_a_data_frame_source_refuses_plain_values_and_a_dict_source_follows_the_rule( value: Any, error: type[Exception] ) -> None: - """A DataFrameSource given a dict of plain values should refuse what a - DictSource declared ``datetime`` refuses; today it stores the value (ITL-1330).""" + """A DataFrameSource given a dict of plain values is refused (ITL-1330): Polars would + type the values before the datetime rule saw them. The rows go to a DictSource, + which applies the rule.""" from orcapod.core.sources import DataFrameSource - with pytest.raises(error): + plain: Any = {"k": [1], "a": [value], "b": [value]} + with pytest.raises(TypeError, match=r"got dict.*DictSource"): _ = DataFrameSource( - {"k": [1], "a": [value], "b": [value]}, + plain, tag_columns=["k"], tag_only_columns=True, source_id="plain" + ) + with pytest.raises(error): + _ = DictSource( + [{"k": 1, "a": value, "b": value}], tag_columns=["k"], tag_only_columns=True, + data_schema={"k": int, "a": datetime, "b": datetime}, source_id="plain", ).as_table() diff --git a/tests/test_core/large_types_cases.py b/tests/test_core/large_types_cases.py index ba0ba8b7b..628c7c1a8 100644 --- a/tests/test_core/large_types_cases.py +++ b/tests/test_core/large_types_cases.py @@ -19,6 +19,7 @@ from typing import Any import deltalake +import pandas as pd import polars as pl import pyarrow as pa import pyarrow.csv as pa_csv @@ -210,10 +211,8 @@ def _data_frame_source_polars(n_rows: int, tmp: Path) -> StreamProtocol: def _data_frame_source_pandas(n_rows: int, tmp: Path) -> StreamProtocol: - # No bytes column: an empty pandas object column has no values to tell bytes - # from str, so a zero-row frame could not give the populated frame's type. return DataFrameSource( - _table(n_rows, ["t", "k", "s", "u"]).to_pandas(), + _table(n_rows, ["t", "k", "s", "u"]).to_pandas(types_mapper=pd.ArrowDtype), tag_columns=TAGS, tag_only_columns=True, source_id="pandas", diff --git a/tests/test_core/sources/test_data_frame_source_inputs.py b/tests/test_core/sources/test_data_frame_source_inputs.py new file mode 100644 index 000000000..4509a5b06 --- /dev/null +++ b/tests/test_core/sources/test_data_frame_source_inputs.py @@ -0,0 +1,909 @@ +"""What a ``DataFrameSource`` accepts: data frames only (ITL-1330). + +A pandas DataFrame, a Polars DataFrame, or an object exporting an Arrow C stream or a C +array of a struct builds as before. Anything else (a dict, a list, a tuple, a generator, +a string, a NumPy array, a Polars or pandas Series, a Polars LazyFrame) is refused when +the source is built, with a ``TypeError`` that names the type given and the remedy. +""" + +from __future__ import annotations + +from collections import UserDict +from collections.abc import Callable +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from typing import Any, Literal + +import numpy as np +import pandas as pd +import polars as pl +import pyarrow as pa +import pytest + +from orcapod.core.sources import ( + ArrowTableSource, + DataFrameSource, + DictSource, + ListSource, +) +from orcapod.errors import ( + InputValidationError, + NaiveDatetimeError, + SubMicrosecondDatetimeError, +) + +# --------------------------------------------------------------------------- +# Refused inputs +# --------------------------------------------------------------------------- + +_COLUMNS: dict[str, list[Any]] = { + "g": ["a", "b"], + "k": [1, 2], + "x": [1.5, 2.5], + "y": ["p", "q"], +} +_ROWS = [ + {"g": "a", "k": 1, "x": 1.5, "y": "p"}, + {"g": "b", "k": 2, "x": 2.5, "y": "q"}, +] +_SCHEMA = pa.schema( + [ + pa.field("g", pa.large_string(), nullable=False), + pa.field("k", pa.int64(), nullable=False), + pa.field("x", pa.float64(), nullable=False), + pa.field("y", pa.large_string(), nullable=False), + ] +) + +# name -> (builds the refused input, its type as the error names it, text of its remedy) +REFUSED: dict[str, tuple[Callable[[], Any], str, str]] = { + "dict_of_lists": (lambda: dict(_COLUMNS), "dict", "DictSource"), + "empty_dict": (lambda: {}, "dict", "DictSource"), + "list_of_dicts": (lambda: list(_ROWS), "list", "DictSource"), + "list_of_tuples": ( + lambda: [("a", 1, 1.5, "p"), ("b", 2, 2.5, "q")], + "list", + "ListSource", + ), + "list_of_lists": (lambda: [["a", "b"], ["p", "q"]], "list", "ListSource"), + "empty_list": (lambda: [], "list", "ListSource"), + "tuple_of_dicts": (lambda: tuple(_ROWS), "tuple", "DictSource"), + "generator_of_dicts": (lambda: (row for row in _ROWS), "generator", "DictSource"), + "none": (lambda: None, "NoneType", 'ListSource("value", [data])'), + "str": (lambda: "abc", "str", 'ListSource("value", [data])'), + "set": (lambda: {1, 2}, "set", "ListSource"), + # Typed columns in a Python container are still a Python container. + "dict_of_numpy_arrays": ( + lambda: {name: np.array(values) for name, values in _COLUMNS.items()}, + "dict", + "ArrowTableSource", + ), + "dict_of_polars_series": ( + lambda: {name: pl.Series(values) for name, values in _COLUMNS.items()}, + "dict", + "pl.DataFrame(", + ), + "dict_of_pandas_series": ( + lambda: {name: pd.Series(values) for name, values in _COLUMNS.items()}, + "dict", + "pl.DataFrame(", + ), + "dict_of_arrow_arrays": ( + lambda: {name: pa.array(values) for name, values in _COLUMNS.items()}, + "dict", + "pl.DataFrame(", + ), + "list_of_polars_series": ( + lambda: [pl.Series(name, values) for name, values in _COLUMNS.items()], + "list", + "pl.DataFrame(", + ), + "list_of_arrow_record_batches": ( + lambda: pa.Table.from_pydict(_COLUMNS).to_batches(), + "list", + "ArrowTableSource", + ), + # Not a container of Python values, and not a data frame either. + "polars_series": ( + lambda: pl.Series("x", [1.5, 2.5]), + "polars.Series", + "to_frame()", + ), + "polars_struct_series": ( + lambda: pl.DataFrame(_COLUMNS).to_struct("row"), + "polars.Series", + "to_frame()", + ), + "polars_lazy_frame": ( + lambda: pl.DataFrame(_COLUMNS).lazy(), + "polars.LazyFrame", + "collect()", + ), + "pandas_series": ( + lambda: pd.Series([1.5, 2.5], name="x"), + "pandas.Series", + "to_frame()", + ), + "numpy_2d": ( + lambda: np.array([[1, 2], [3, 4]]), + "numpy.ndarray", + "ArrowTableSource", + ), + "numpy_1d": (lambda: np.array([1, 2]), "numpy.ndarray", "pl.DataFrame("), + "numpy_structured": ( + lambda: np.array([(1, 1.5), (2, 2.5)], dtype=[("k", "i8"), ("x", "f8")]), + "numpy.ndarray", + "pl.DataFrame(", + ), +} + +# Every way the other arguments may accompany the refused input. +ARGUMENTS: dict[str, dict[str, Any]] = { + "bare": {}, + "tags": {"tag_columns": ["g", "k"]}, + "tags_reversed_tag_only": {"tag_columns": ["k", "g"], "tag_only_columns": True}, + "one_tag_only": {"tag_columns": ["g", "k"], "tag_only_columns": ["k"]}, + "keys": {"tag_columns": ["g", "k"], "record_id_columns": ["k", "g"]}, + "schema": {"schema": _SCHEMA}, + "all": { + "tag_columns": ["g", "k"], + "tag_only_columns": True, + "record_id_columns": ["g", "k"], + "schema": _SCHEMA, + "source_id": "named", + }, + # Arguments that are themselves invalid: the input is refused first. + "unknown_tag": {"tag_columns": ["missing"]}, + "unknown_key": {"record_id_columns": ["missing"]}, +} + + +@pytest.mark.parametrize( + ("data", "type_name"), + [ + (np.array([[1, 2], [3, 4], [5, 6]]), "numpy.ndarray"), + ([np.array([1, 2]), np.array([3, 4]), np.array([5, 6])], "list"), + ((np.array([1, 2]), np.array([3, 4])), "tuple"), + ([np.array([1, 2]), [3, 4]], "list"), + ([[1, 2], np.array([3, 4])], "list"), + ((np.array([1, 2]), [3, 4]), "tuple"), + (([1, 2], np.array([3, 4])), "tuple"), + ({"x": np.array([1, 2]), "y": np.array([3, 4])}, "dict"), + (UserDict({"x": np.array([1, 2]), "y": [3, 4]}), "collections.UserDict"), + ], + ids=[ + "matrix", + "list_of_arrays", + "tuple_of_arrays", + "list_array_first", + "list_array_last", + "tuple_array_first", + "tuple_array_last", + "dict_of_arrays", + "mapping", + ], +) +def test_numpy_inputs_are_refused_with_a_named_source( + data: Any, type_name: str +) -> None: + with pytest.raises(TypeError) as info: + DataFrameSource(data) + message = str(info.value) + assert f"got {type_name}." in message + assert "named columns" in message + assert "ArrowTableSource" in message + assert "pl.DataFrame(" in message + if isinstance(data, (tuple, list)): + assert "Sequence item types:" in message + assert "numpy.ndarray" in message + assert "DictSource" in message + if any(isinstance(item, list) for item in data): + assert "Sequence item types: list, numpy.ndarray." in message + names = ["x", "y"] + expected = [{"x": 1, "y": 3}, {"x": 2, "y": 4}] + arrow_source = ArrowTableSource( + pa.table(dict(zip(names, data, strict=True))) + ) + assert arrow_source.as_table().select(names).to_pylist() == expected + + columns = [ + item.tolist() if isinstance(item, np.ndarray) else item for item in data + ] + rows = [ + dict(zip(names, row, strict=True)) for row in zip(*columns, strict=True) + ] + dict_source = DictSource(rows) + assert dict_source.as_table().select(names).to_pylist() == expected + + frame_source = DataFrameSource(pl.DataFrame(data, schema=names)) + assert frame_source.as_table().select(names).to_pylist() == expected + if isinstance(data, (dict, UserDict)): + assert "row dictionaries" in message + assert "DictSource" in message + + +@pytest.mark.parametrize("arguments", list(ARGUMENTS), ids=list(ARGUMENTS)) +@pytest.mark.parametrize("kind", list(REFUSED), ids=list(REFUSED)) +def test_an_input_that_is_not_a_data_frame_is_refused( + kind: str, arguments: str +) -> None: + """The error is a ``TypeError`` naming the type given and its remedy, whatever the + other arguments are (also invalid ones: the input is refused first).""" + make, type_name, remedy = REFUSED[kind] + data = make() + + with pytest.raises(TypeError) as info: + DataFrameSource(data, **ARGUMENTS[arguments]) + + message = str(info.value) + assert "DataFrameSource accepts a data frame only" in message + assert f"got {type_name}" in message + assert remedy in message + if kind == "dict_of_lists": + assert "convert the mapping of columns to Python row dictionaries" in message + + +def test_a_generator_is_refused_without_being_read() -> None: + """Refusing reads nothing: a generator given by mistake is still whole.""" + rows: Any = (row for row in _ROWS) + with pytest.raises(TypeError, match="got generator") as info: + DataFrameSource(rows, tag_columns=["g", "k"]) + assert "DictSource(list(data))" in str(info.value) + migrated = DictSource(list(rows)) + assert migrated.as_table().select(list(_COLUMNS)).to_pylist() == _ROWS + + +def test_a_value_iterator_can_migrate_to_list_source() -> None: + """The value recipe stores the remaining iterator values in order.""" + data: Any = iter([1, 2]) + with pytest.raises(TypeError, match="got list_iterator") as info: + DataFrameSource(data) + assert 'ListSource("value", list(data))' in str(info.value) + migrated = ListSource("value", list(data)) + assert migrated.as_table().select(["value"]).to_pylist() == [ + {"value": 1}, + {"value": 2}, + ] + + +@pytest.mark.parametrize("container", ["generator", "iterator"]) +@pytest.mark.parametrize( + "array_first", [True, False], ids=["array_first", "array_last"] +) +def test_mixed_row_iterators_can_migrate_to_arrow_table_source( + container: str, array_first: bool +) -> None: + """The named migration reads the original iterator and preserves its row layout.""" + rows = [np.array([1, 2]), [3, 4]] if array_first else [[1, 2], np.array([3, 4])] + data: Any = (row for row in rows) if container == "generator" else iter(rows) + type_name = "generator" if container == "generator" else "list_iterator" + with pytest.raises(TypeError, match=rf"got {type_name}\.") as info: + DataFrameSource(data) + + assert "ArrowTableSource(pl.DataFrame(data).to_arrow())" in str(info.value) + migrated = ArrowTableSource(pl.DataFrame(data).to_arrow()) + assert migrated.as_table().select(["column_0", "column_1"]).to_pylist() == [ + {"column_0": 1, "column_1": 2}, + {"column_0": 3, "column_1": 4}, + ] + + +@pytest.mark.parametrize("container", ["list", "tuple", "generator"]) +def test_named_polars_series_can_migrate_to_arrow_table_source(container: str) -> None: + """The named migration keeps the names and values of the original columns.""" + series = [pl.Series("x", [1, 2]), pl.Series("y", [3, 4])] + containers = { + "list": series, + "tuple": tuple(series), + "generator": (s for s in series), + } + data: Any = containers[container] + with pytest.raises(TypeError, match=rf"got {container}\.") as info: + DataFrameSource(data) + + assert ( + "ArrowTableSource(pa.table({series.name: series for series in data}))" + in str(info.value) + ) + expected = [{"x": 1, "y": 3}, {"x": 2, "y": 4}] + migrated = ArrowTableSource(pa.table({column.name: column for column in data})) + assert migrated.as_table().select(["x", "y"]).to_pylist() == expected + if container != "generator": + assert "DataFrameSource(pl.DataFrame(data))" in str(info.value) + frame_source = DataFrameSource(pl.DataFrame(data)) + assert frame_source.as_table().select(["x", "y"]).to_pylist() == expected + + +@pytest.mark.parametrize( + ("data", "type_name", "column_type", "expected"), + [ + (pa.array([1, 2]), "pyarrow.Int64Array", None, [1, 2]), + (pa.chunked_array([[1], [2]]), "pyarrow.ChunkedArray", None, [1, 2]), + ( + pa.array(["a", "b"]).dictionary_encode(), + "pyarrow.DictionaryArray", + pa.string(), + ["a", "b"], + ), + (pa.nulls(2), "pyarrow.NullArray", pa.int64(), [None, None]), + ], + ids=["array", "chunked_array", "dictionary_array", "null_array"], +) +def test_non_struct_arrow_exporters_are_refused_with_a_remedy( + data: pa.Array[Any] | pa.ChunkedArray[Any], + type_name: str, + column_type: pa.DataType | None, + expected: list[object], +) -> None: + """Both Arrow export routes give guidance that covers unsupported types.""" + with pytest.raises( + TypeError, match=rf"got {type_name!s}.*ArrowTableSource" + ) as info: + _ = DataFrameSource(data) + message = str(info.value) + assert "named columns" in message + assert "supported column types" in message + assert "pa.table(" not in message + column = data if column_type is None else data.cast(column_type) + migrated = ArrowTableSource(pa.Table.from_arrays([column], names=["x"])) + assert migrated.as_table().column("x").to_pylist() == expected + + +@pytest.mark.parametrize( + ("value", "error"), + [ + (datetime(2026, 1, 2, 3, 4, 5), NaiveDatetimeError), + ( + pd.Timestamp("2026-01-02T03:04:05.123456789Z"), + SubMicrosecondDatetimeError, + ), + ], + ids=["naive", "sub_microsecond"], +) +@pytest.mark.parametrize("shape", ["dict_of_lists", "list_of_dicts"]) +def test_the_reported_defect_is_refused_and_its_remedy_follows_the_rule( + shape: str, value: Any, error: type[Exception] +) -> None: + """The values of the report: no source is built from them by ``DataFrameSource``, and + the source the error points to applies the datetime rule to them.""" + rows = [{"id": 1, "v": value, "w": value}, {"id": 2, "v": value, "w": value}] + data: Any = ( + rows if shape == "list_of_dicts" else {k: [r[k] for r in rows] for k in rows[0]} + ) + with pytest.raises(TypeError, match="DictSource"): + DataFrameSource(data, tag_columns=["id"], tag_only_columns=True) + with pytest.raises(error): + DictSource( + rows, + tag_columns=["id"], + tag_only_columns=True, + data_schema={"id": int, "v": datetime, "w": datetime}, + ) + + +# --------------------------------------------------------------------------- +# Supported inputs build as before +# --------------------------------------------------------------------------- + + +class _ArrowStreamExporter: + """An object of another library that exports an Arrow C stream.""" + + def __init__(self, table: pa.Table) -> None: + self.table = table + + def __arrow_c_stream__(self, requested_schema: Any = None) -> Any: + return self.table.__arrow_c_stream__(requested_schema) + + +class _ArrowArrayExporter: + """An object of another library that exports an Arrow C array of a struct.""" + + def __init__(self, batch: pa.RecordBatch) -> None: + self.batch = batch + + def __arrow_c_array__(self, requested_schema: Any = None) -> Any: + return self.batch.__arrow_c_array__(requested_schema) + + +# Two tag columns and two data columns, in two table layouts. +LAYOUTS: dict[str, tuple[str, ...]] = { + "tags_first": ("g", "k", "x", "y"), + "mixed": ("y", "k", "x", "g"), +} +# Two declared tag orders, each in the tag-only and the data-tag role (and one of each). +ROLES: dict[str, dict[str, Any]] = { + "gk_tag_only": {"tag_columns": ["g", "k"], "tag_only_columns": True}, + "kg_tag_only": {"tag_columns": ["k", "g"], "tag_only_columns": True}, + "gk_data_tags": {"tag_columns": ["g", "k"]}, + "kg_data_tags": {"tag_columns": ["k", "g"]}, + "gk_one_of_each": {"tag_columns": ["g", "k"], "tag_only_columns": ["k"]}, +} + + +def _arrow(layout: str) -> pa.Table: + names = LAYOUTS[layout] + return pa.table( + {name: _COLUMNS[name] for name in names}, + schema=pa.schema([_SCHEMA.field(name) for name in names]), + ) + + +def _batch(layout: str) -> pa.RecordBatch: + return _arrow(layout).to_batches()[0] + + +SUPPORTED: dict[str, Callable[[str], Any]] = { + "polars": lambda layout: pl.DataFrame( + {name: _COLUMNS[name] for name in LAYOUTS[layout]} + ), + "pandas": lambda layout: pd.DataFrame( + {name: _COLUMNS[name] for name in LAYOUTS[layout]} + ).astype({"g": "string", "y": "string"}), + "pandas_arrow": lambda layout: pd.DataFrame( + {name: _COLUMNS[name] for name in LAYOUTS[layout]} + ).convert_dtypes(dtype_backend="pyarrow"), + "arrow_table": _arrow, + "arrow_record_batch": _batch, + "arrow_reader": lambda layout: _arrow(layout).to_reader(), + "arrow_struct_array": lambda layout: _batch(layout).to_struct_array(), + "c_stream_exporter": lambda layout: _ArrowStreamExporter(_arrow(layout)), + "c_array_exporter": lambda layout: _ArrowArrayExporter(_batch(layout)), +} + +# The default source id, measured before ITL-1330: one value for all supported +# inputs, both layouts and every role (the id hashes the source's table, in no column +# order, and no role enters it), so it pins what each input builds. +DEFAULT_SOURCE_ID = ( + "data_frame_v1:arrow_v1:" + "000002cbaa91da0d861f3fdd888ca2e07246810db637d95c3768f8eaf58be891669542" +) + + +@pytest.mark.parametrize("role", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("layout", list(LAYOUTS), ids=list(LAYOUTS)) +@pytest.mark.parametrize("kind", list(SUPPORTED), ids=list(SUPPORTED)) +def test_a_supported_input_builds_as_before(kind: str, layout: str, role: str) -> None: + """Rows, roles, types and the default source id of every supported input.""" + arguments = ROLES[role] + source = DataFrameSource(SUPPORTED[kind](layout), **arguments) + + tags = tuple(arguments["tag_columns"]) + tag_only = arguments.get("tag_only_columns", ()) + plain = set(tags) if tag_only is True else set(tag_only) + data_tags = tuple(name for name in tags if name not in plain) + others = tuple(name for name in LAYOUTS[layout] if name not in tags) + + tag_keys, data_keys = source.keys() + assert set(tag_keys) == set(tags) + assert data_keys == data_tags + others + + table = source.as_table() + assert table.num_rows == 2 + for name in LAYOUTS[layout]: + assert table.schema.field(name) == _SCHEMA.field(name) + assert table.column(name).to_pylist() == _COLUMNS[name] + + assert source.source_id == DEFAULT_SOURCE_ID + + +@pytest.mark.parametrize("role", list(ROLES), ids=list(ROLES)) +@pytest.mark.parametrize("kind", list(SUPPORTED), ids=list(SUPPORTED)) +def test_a_supported_input_with_keys_and_a_schema_builds(kind: str, role: str) -> None: + """With ``record_id_columns`` (two, in two orders) and a ``schema=``, the record ids + are the keys in key order, whatever the input kind.""" + for keys in (["g", "k"], ["k", "g"]): + source = DataFrameSource( + SUPPORTED[kind]("tags_first"), + schema=_SCHEMA, + record_id_columns=keys, + source_id="named", + **ROLES[role], + ) + table = source.as_table(columns={"system_tags": True}) + record_ids = next( + table.column(name).to_pylist() + for name in table.column_names + if name.startswith("_tag_record_id") + ) + rows = [{"g": "a", "k": 1}, {"g": "b", "k": 2}] + assert record_ids == [ + "{" + ",".join(_json_entry(key, row[key]) for key in keys) + "}" + for row in rows + ] + assert source.source_id == "data_frame_v1:named" + + +def _json_entry(name: str, value: object) -> str: + return f'"{name}":"{value}"' if isinstance(value, str) else f'"{name}":{value}' + + +def _frame_with_object_column(name: str, layout: str) -> tuple[pd.DataFrame, pa.Schema]: + columns = (*LAYOUTS[layout], "origin", "key") + fields = [ + *_SCHEMA, + pa.field("origin", pa.large_string(), nullable=False), + pa.field("key", pa.int64(), nullable=False), + ] + schema = pa.schema(fields) + frame = pd.DataFrame( + {**_COLUMNS, "origin": ["left", "right"], "key": [91, 92]} + ).astype({"g": "string", "y": "string", "origin": "string"}) + return frame.loc[:, list(columns)].astype({name: object}), pa.schema( + [schema.field(column) for column in columns] + ) + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize("name", ["g", "k", "x", "y", "origin", "key"]) +def test_pandas_object_column_requires_a_schema(layout: str, name: str) -> None: + """Object columns without a schema are refused in every column role.""" + frame, schema = _frame_with_object_column(name, layout) + options: dict[str, Any] = { + "tag_columns": ["g", "k"], + "tag_only_columns": ["g"], + "system_tag_columns": ["origin"], + "record_id_columns": ["key"], + } + with pytest.raises(InputValidationError, match=rf"'{name}'.*dtype object") as info: + DataFrameSource(frame, **options) + for remedy in ("schema=", "astype('string')", "pd.to_datetime", "DictSource"): + assert remedy in str(info.value) + + actual = DataFrameSource(frame, schema=schema, **options) + typed = frame.astype({"g": "string", "y": "string", "origin": "string"}) + for numeric in ("k", "x", "key"): + typed[numeric] = typed[numeric].astype("float64" if numeric == "x" else "int64") + expected = DataFrameSource(typed, schema=schema, **options) + assert actual.as_table(all_info=True).equals( + expected.as_table(all_info=True), check_metadata=True + ) + assert actual.source_id == expected.source_id + + +@pytest.mark.asyncio +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize("role", [*ROLES, "kg_other_plain"]) +@pytest.mark.parametrize("reverse_keys", [False, True]) +async def test_several_declared_pandas_object_columns( + layout: str, role: str, reverse_keys: bool +) -> None: + """Several object declarations preserve each column role and both row paths.""" + columns = { + **_COLUMNS, + "origin": ["left", "right"], + "revision": ["v1", "v2"], + "key": [91, 92], + } + names = ( + ["origin", *LAYOUTS[layout], "key", "revision"] + if layout == "tags_first" + else ["key", "revision", *LAYOUTS[layout], "origin"] + ) + fields = { + **{field.name: field for field in _SCHEMA}, + "origin": pa.field("origin", pa.large_string(), nullable=False), + "revision": pa.field("revision", pa.large_string(), nullable=False), + "key": pa.field("key", pa.int64(), nullable=False), + } + schema = pa.schema([fields[name] for name in names]) + typed = pd.DataFrame({name: columns[name] for name in names}).astype( + {name: "string" for name in ("g", "y", "origin", "revision")} + ) + keys = ["g", "key"] + system_tags = ["origin", "revision"] + if reverse_keys: + keys.reverse() + system_tags.reverse() + options = ROLES.get(role, {"tag_columns": ["k", "g"], "tag_only_columns": ["g"]}) + kwargs: dict[str, Any] = { + **options, + "schema": schema, + "system_tag_columns": system_tags, + "record_id_columns": keys, + } + actual = DataFrameSource(typed.astype(object), **kwargs) + expected = DataFrameSource(typed, **kwargs) + assert actual.keys() == expected.keys() + table = actual.as_table(all_info=True) + assert table.equals(expected.as_table(all_info=True), check_metadata=True) + assert actual.source_id == expected.source_id + assert actual.content_hash() == expected.content_hash() + assert actual.pipeline_hash() == expected.pipeline_hash() + + def row_signature(tag: Any, row: Any) -> tuple[dict[str, Any], str]: + return dict(tag.system_tags()), row.content_hash() + + sync_rows = [row_signature(tag, row) for tag, row in actual.iter_data()] + async_rows = [ + row_signature(tag, row) async for tag, row in actual.async_iter_data() + ] + assert ( + sync_rows + == async_rows + == [row_signature(tag, row) for tag, row in expected.iter_data()] + ) + assert [(tags["_tag_origin"], tags["_tag_revision"]) for tags, _ in sync_rows] == [ + ("left", "v1"), + ("right", "v2"), + ] + record_ids = next( + table.column(name).to_pylist() + for name in table.column_names + if name.startswith("_tag_record_id") + ) + assert record_ids == [ + "{" + ",".join(_json_entry(key, columns[key][index]) for key in keys) + "}" + for index in range(2) + ] + + +@pytest.mark.parametrize( + "frame", + [ + pd.DataFrame({"x": [1, 2], "_note": pd.Series(["a", "b"], dtype=object)}), + pl.DataFrame({"x": [1, 2], "_note": pl.Series(["a", "b"], dtype=pl.Object)}), + ], + ids=["pandas", "polars"], +) +def test_schema_ignores_auxiliary_object_column( + frame: pd.DataFrame | pl.DataFrame, +) -> None: + schema = pa.schema([("x", pa.int64())]) + actual = DataFrameSource(frame, schema=schema) + expected = DataFrameSource(pl.DataFrame({"x": [1, 2]}), schema=schema) + assert actual.as_table().schema == schema + assert actual.as_table().to_pylist() == [{"x": 1}, {"x": 2}] + assert actual.source_id == expected.source_id + assert actual.content_hash() == expected.content_hash() + assert actual.pipeline_hash() == expected.pipeline_hash() + + +def test_polars_object_column_without_schema_keeps_native_conversion() -> None: + frame = pl.DataFrame({"x": pl.Series([1, 2], dtype=pl.Object)}) + actual = DataFrameSource(frame) + expected = DataFrameSource(pl.DataFrame({"x": [1, 2]})) + assert actual.as_table().schema == pa.schema( + [pa.field("x", pa.int64(), nullable=False)] + ) + assert actual.as_table().to_pylist() == [{"x": 1}, {"x": 2}] + assert actual.source_id == expected.source_id + assert actual.content_hash() == expected.content_hash() + assert actual.pipeline_hash() == expected.pipeline_hash() + + +def test_pandas_all_none_object_column_requires_a_nullable_type() -> None: + frame = pd.DataFrame({"missing": pd.Series([None, None], dtype=object)}) + with pytest.raises(InputValidationError, match=r"'missing'.*dtype object"): + DataFrameSource(frame) + with pytest.raises(ValueError, match=r"'missing'.*null values.*non-nullable"): + DataFrameSource( + frame, schema=pa.schema([pa.field("missing", pa.int64(), nullable=False)]) + ) + source = DataFrameSource(frame, schema=pa.schema([("missing", pa.int64())])) + assert ( + source.as_table() + .column("missing") + .equals(pa.chunked_array([[None, None]], type=pa.int64())) + ) + + +@pytest.mark.parametrize("missing", [None, float("nan"), pd.NA, pd.NaT]) +@pytest.mark.parametrize( + ("kind", "value"), + [ + (pa.int64(), 1), + (pa.float32(), 1.5), + (pa.float64(), 1.5), + (pa.string(), "abc"), + (pa.bool_(), True), + (pa.binary(), b"abc"), + (pa.decimal128(10, 2), Decimal("1.25")), + (pa.date32(), date(2026, 1, 2)), + (pa.time64("ns"), time(3, 4, 5)), + (pa.timestamp("ns", tz="UTC"), pd.Timestamp("2026-01-02T03:04:05Z")), + (pa.duration("ns"), timedelta(seconds=1)), + ], +) +@pytest.mark.parametrize("shape", ["scalar", "list", "fixed_list", "struct"]) +def test_declared_pandas_object_columns_convert_missing_values_to_nulls( + shape: str, kind: pa.DataType, value: Any, missing: Any +) -> None: + """The declared field determines storage for pandas missing values at each depth.""" + if shape == "list": + kind = pa.list_(kind) + values = [[value, missing], []] + expected = [[value, None], []] + elif shape == "fixed_list": + kind = pa.list_(kind, 2) + values = [[value, missing], [value, value]] + expected = [[value, None], [value, value]] + elif shape == "struct": + kind = pa.struct([("a", kind), ("b", kind)]) + values = [{"a": value, "b": missing}, {"a": value, "b": value}] + expected = [{"a": value, "b": None}, {"a": value, "b": value}] + else: + values = [value, missing] + expected = [value, None] + schema = pa.schema([("x", kind)]) + frame = pd.DataFrame({"x": pd.Series(values, dtype=object)}) + actual = DataFrameSource(frame, schema=schema) + expected_frame = pd.DataFrame({"x": pd.Series(expected, dtype=object)}) + clean = DataFrameSource(expected_frame, schema=schema) + assert actual.as_table(all_info=True).equals(clean.as_table(all_info=True)) + assert actual.as_table().column("x").to_pylist() == expected + assert actual.source_id == clean.source_id + assert actual.content_hash() == clean.content_hash() + assert actual.pipeline_hash() == clean.pipeline_hash() + + +@pytest.mark.parametrize( + ("field", "values"), + [ + (pa.field("x", pa.float64(), nullable=False), [1.5, float("nan")]), + ( + pa.field("x", pa.list_(pa.field("item", pa.int64(), nullable=False))), + [[1], [pd.NA]], + ), + ], +) +def test_declared_pandas_missing_values_require_nullable_fields( + field: pa.Field[Any], values: list[Any] +) -> None: + """A missing value must fail even when it can convert to a null.""" + frame = pd.DataFrame({"x": pd.Series(values, dtype=object)}) + with pytest.raises(ValueError, match=r"'x['/].*(?:non-nullable|Non-nullable)"): + DataFrameSource(frame, schema=pa.schema([field])) + + +@pytest.mark.parametrize("zone", [None, "UTC"]) +def test_pandas_typed_timestamps_keep_nanoseconds(zone: Any) -> None: + first = pd.Timestamp("2026-01-02T03:04:05.123456000", tz=zone) + second = pd.Timestamp("2026-01-02T03:04:05.123456789", tz=zone) + frame = pd.DataFrame({"when": pd.Series([first, second])}) + schema = pa.schema([("when", pa.timestamp("ns", tz=zone))]) + column = DataFrameSource(frame, schema=schema).as_table()["when"] + assert column.type == schema.field("when").type + assert column.cast(pa.int64()).to_pylist() == [first.value, second.value] + + with pytest.raises(pa.ArrowInvalid, match="would lose data"): + DataFrameSource( + frame, schema=pa.schema([("when", pa.timestamp("us", tz=zone))]) + ) + + +@pytest.mark.parametrize("unit", ["ns", "us"]) +def test_pandas_declared_object_timestamp_uses_native_precision( + unit: Literal["ns", "us"], +) -> None: + stamp = pd.Timestamp("2026-01-02T03:04:05.123456789Z") + frame = pd.DataFrame({"when": pd.Series([stamp], dtype=object)}) + schema = pa.schema([("when", pa.timestamp(unit, tz="UTC"))]) + column = DataFrameSource(frame, schema=schema).as_table()["when"] + assert column.type == schema.field("when").type + microseconds = stamp.value // 1000 + assert column.cast(pa.int64()).to_pylist() == [ + microseconds * 1000 if unit == "ns" else microseconds + ] + + +def test_pandas_declared_object_duration_uses_native_precision() -> None: + duration = pd.Timedelta(123456789, unit="ns") + frame = pd.DataFrame({"x": pd.Series([duration], dtype=object)}) + schema = pa.schema([("x", pa.duration("ns"))]) + column = DataFrameSource(frame, schema=schema).as_table()["x"] + assert column.cast(pa.int64()).to_pylist() == [123456000] + + +@pytest.mark.parametrize( + ("kind", "values", "error"), + [ + (pa.int64(), [1.5], pa.ArrowInvalid), + (pa.int64(), ["word"], pa.ArrowInvalid), + (pa.string(), [b"\xff"], pa.ArrowInvalid), + (pa.float64(), [2**53 + 1], pa.ArrowInvalid), + (pa.decimal128(12, 2), [1], pa.ArrowInvalid), + (pa.time64("ns"), [None], pa.ArrowNotImplementedError), + (pa.duration("ns"), [None], pa.ArrowNotImplementedError), + (pa.float16(), [True], pa.ArrowNotImplementedError), + ], +) +def test_declared_pandas_object_columns_keep_native_cast_errors( + kind: pa.DataType, values: list[Any], error: type[Exception] +) -> None: + frame = pd.DataFrame({"x": pd.Series(values, dtype=object)}) + with pytest.raises(error): + DataFrameSource(frame, schema=pa.schema([("x", kind)])) + + +@pytest.mark.parametrize( + ("kind", "values", "expected"), + [ + (pa.float16(), [np.float32(1.5), np.float32(2.25)], [1.5, 2.25]), + (pa.list_(pa.float16()), [[np.float32(1.5)]], [[1.5]]), + ( + pa.struct([("item", pa.float16())]), + [{"item": np.float32(1.5)}], + [{"item": 1.5}], + ), + (pa.int64(), [True, False], [1, 0]), + (pa.int64(), ["13"], [13]), + (pa.string(), [b"ab"], ["ab"]), + (pa.binary(), ["ab"], [b"ab"]), + ( + pa.timestamp("ns", "UTC"), + [pd.Timestamp("2026-01-02T03:04:05")], + [pd.Timestamp("2026-01-02T03:04:05Z")], + ), + (pa.struct([("item", pa.int64())]), [{"item": 1, "extra": 2}], [{"item": 1}]), + ( + pa.struct([("item", pa.bool_())]), + [{"item": np.float32("nan")}], + [{"item": True}], + ), + ], +) +def test_declared_pandas_object_columns_use_native_frame_conversion( + kind: pa.DataType, values: list[Any], expected: list[Any] +) -> None: + """Keep the schema casts that the native frame path already supported.""" + frame = pd.DataFrame({"x": pd.Series(values, dtype=object)}) + column = DataFrameSource(frame, schema=pa.schema([("x", kind)])).as_table()["x"] + assert column.to_pylist() == expected + + +@pytest.mark.parametrize( + ("kind", "values"), + [ + (pa.float16(), [np.float32("nan")]), + (pa.list_(pa.float16()), [[np.float32("nan")]]), + (pa.list_(pa.float16(), 1), [[np.float32("nan")]]), + (pa.struct([("item", pa.float16())]), [{"item": np.float32("nan")}]), + ], +) +def test_declared_float16_keeps_numpy_float32_nan( + kind: pa.DataType, values: list[Any] +) -> None: + """The native conversion carries these NumPy NaNs through the schema cast.""" + frame = pd.DataFrame({"x": pd.Series(values, dtype=object)}) + column = DataFrameSource(frame, schema=pa.schema([("x", kind)])).as_table()["x"] + value = column[0].as_py() + if isinstance(value, list): + value = value[0] + elif isinstance(value, dict): + value = value["item"] + assert np.isnan(value) + + +@pytest.mark.parametrize("with_schema", [False, True]) +def test_pandas_categorical_keeps_native_conversion(with_schema: bool) -> None: + frame = pd.DataFrame( + {"x": pd.Categorical([1, 2], categories=pd.Index([1, 2], dtype=object))} + ) + schema = pa.schema([("x", pa.int64())]) if with_schema else None + column = DataFrameSource(frame, schema=schema).as_table()["x"] + assert column.type == pa.int64() + assert column.to_pylist() == [1, 2] + + +def test_declared_polars_object_column_keeps_native_conversion() -> None: + frame = pl.DataFrame({"x": pl.Series([1, 2], dtype=pl.Object)}) + source = DataFrameSource(frame, schema=pa.schema([("x", pa.string())])) + assert source.as_table()["x"].to_pylist() == ["1", "2"] + + +def test_declared_pandas_string_categorical_cast_decodes_dictionary() -> None: + frame = pd.DataFrame({"x": pd.Categorical(["a", "b"])}) + with pytest.raises(InputValidationError, match="dictionary-encoded columns"): + DataFrameSource(frame) + source = DataFrameSource(frame, schema=pa.schema([("x", pa.string())])) + assert source.as_table()["x"].to_pylist() == ["a", "b"] + + +def test_declared_polars_object_custom_system_tag_is_refused() -> None: + frame = pl.DataFrame({"origin": pl.Series(["left", "right"], dtype=pl.Object)}) + schema = pa.schema([pa.field("origin", pa.large_string(), nullable=False)]) + with pytest.raises( + InputValidationError, match=r"Custom system-tag column 'origin'" + ): + DataFrameSource(frame, schema=schema, system_tag_columns=["origin"]) diff --git a/tests/test_core/sources/test_dictionary_columns_refused.py b/tests/test_core/sources/test_dictionary_columns_refused.py index 2168d0f63..3626863cb 100644 --- a/tests/test_core/sources/test_dictionary_columns_refused.py +++ b/tests/test_core/sources/test_dictionary_columns_refused.py @@ -355,7 +355,9 @@ def test_an_opaque_type_over_a_dictionary_is_refused() -> None: def _pandas(encoded: tuple[str, ...]) -> pd.DataFrame: - frame = pd.DataFrame(FRAME_COLUMNS) + frame = pd.DataFrame(FRAME_COLUMNS).astype( + {"a": "string", "b": "string", "v": "string"} + ) for name in encoded: frame[name] = frame[name].astype("category") return frame @@ -770,7 +772,7 @@ def test_a_frame_decoded_with_polars_builds(dtype: str) -> None: 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) + frame[name] = frame[name].astype("string") source = DataFrameSource(frame, tag_columns=["a", "b"], tag_only_columns=True) assert source.as_table(all_info=True).num_rows == 3 diff --git a/tests/test_core/sources/test_key_policy_identity.py b/tests/test_core/sources/test_key_policy_identity.py index 1ea5740b4..c431a88d6 100644 --- a/tests/test_core/sources/test_key_policy_identity.py +++ b/tests/test_core/sources/test_key_policy_identity.py @@ -48,7 +48,7 @@ def _dict(_tmp: Path, key: Any) -> Any: def _data_frame(_tmp: Path, key: Any) -> Any: return DataFrameSource( - _TABLE.to_pandas(), + _TABLE.to_pandas().astype({"k": "string"}), tag_columns=["k"], record_id_columns=key, tag_only_columns=True, diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 3f69e887d..af3893d43 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -961,7 +961,11 @@ def test_dataframe_source_declares_native_custom_system_tag_required_large_strin "x": [1, 2], "extra": ["one", "two"], } - data = pd.DataFrame(values) if representation == "pandas" else pl.DataFrame(values) + data = ( + pd.DataFrame(values).astype({"g": "string", "k": "string", "extra": "string"}) + if representation == "pandas" + else pl.DataFrame(values) + ) source = DataFrameSource(data, tag_columns=TAGS, system_tag_columns=["extra"]) field = source.as_table(columns={"system_tags": True}).schema.field("_tag_extra") assert field.type == pa.large_string() @@ -983,6 +987,8 @@ def test_dataframe_source_rejects_invalid_native_custom_system_tag( } data = ( pd.DataFrame(data_values) + .astype({"g": "string", "k": "string"}) + .convert_dtypes() if representation == "pandas" else pl.DataFrame(data_values) ) diff --git a/tests/test_core/sources/test_source_builder_integration.py b/tests/test_core/sources/test_source_builder_integration.py index f01bc97ee..6c7496bb7 100644 --- a/tests/test_core/sources/test_source_builder_integration.py +++ b/tests/test_core/sources/test_source_builder_integration.py @@ -2,6 +2,7 @@ from __future__ import annotations +import polars as pl import pyarrow as pa import pytest @@ -70,7 +71,7 @@ def test_source_id_defaults(self): class TestDataFrameSourceBuilder: def test_no_arrow_source_attr(self): src = DataFrameSource( - data={"id": [1, 2], "x": [10, 20]}, + data=pl.DataFrame({"id": [1, 2], "x": [10, 20]}), tag_columns=["id"], tag_only_columns=True, ) @@ -78,7 +79,7 @@ def test_no_arrow_source_attr(self): def test_has_stream_attr(self): src = DataFrameSource( - data={"id": [1, 2], "x": [10, 20]}, + data=pl.DataFrame({"id": [1, 2], "x": [10, 20]}), tag_columns=["id"], tag_only_columns=True, ) @@ -86,7 +87,7 @@ def test_has_stream_attr(self): def test_iter_data(self): src = DataFrameSource( - data={"id": [1, 2], "x": [10, 20]}, + data=pl.DataFrame({"id": [1, 2], "x": [10, 20]}), tag_columns=["id"], tag_only_columns=True, ) @@ -94,7 +95,9 @@ def test_iter_data(self): def test_identity_starts_with_the_source_id(self): src = DataFrameSource( - data={"id": [1], "x": [10]}, tag_columns=["id"], tag_only_columns=True + data=pl.DataFrame({"id": [1], "x": [10]}), + tag_columns=["id"], + tag_only_columns=True, ) identity = src.identity_structure() assert identity[0] == src.source_id diff --git a/tests/test_core/sources/test_tag_columns_normalization.py b/tests/test_core/sources/test_tag_columns_normalization.py index 2b3f73bba..74a2ffbf7 100644 --- a/tests/test_core/sources/test_tag_columns_normalization.py +++ b/tests/test_core/sources/test_tag_columns_normalization.py @@ -13,6 +13,7 @@ from collections.abc import Iterator from typing import Any +import polars as pl import pyarrow as pa import pytest @@ -170,7 +171,7 @@ class TestDataFrameSourceTagColumns: def test_bare_string_same_as_list(self): from orcapod.core.sources import DataFrameSource - data = {"session_id": ["s1", "s2"], "value": [10, 20]} + data = pl.DataFrame({"session_id": ["s1", "s2"], "value": [10, 20]}) src_str = DataFrameSource( data=data, tag_columns="session_id", tag_only_columns=True ) @@ -185,7 +186,7 @@ def test_tuple_accepted(self): from orcapod.core.sources import DataFrameSource src = DataFrameSource( - data={"session_id": ["s1"], "value": [10]}, + data=pl.DataFrame({"session_id": ["s1"], "value": [10]}), tag_columns=("session_id",), tag_only_columns=True, ) @@ -197,7 +198,7 @@ def test_invalid_type_raises(self): with pytest.raises(TypeError): DataFrameSource( - data={"session_id": ["s1"], "value": [1]}, + data=pl.DataFrame({"session_id": ["s1"], "value": [1]}), tag_columns=42, # pyright: ignore[reportArgumentType] # an invalid type on purpose tag_only_columns=True, ) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index a745e03c9..c6496b8bb 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -6,6 +6,7 @@ import json from pathlib import Path +import polars as pl import pyarrow as pa import pytest @@ -119,9 +120,15 @@ def source(row: int, arrangement: Arrangement) -> RootSource: tag_only_columns=tag_only, source_id="shared", ) - cls = DictSource if kind == "dict" else DataFrameSource - return cls( - data=table.to_pylist(), + if kind == "dict": + return DictSource( + data=table.to_pylist(), + tag_columns=arrangement.tag_order, + tag_only_columns=tag_only, + source_id="shared", + ) + return DataFrameSource( + data=pl.from_arrow(table), tag_columns=arrangement.tag_order, tag_only_columns=tag_only, source_id="shared", diff --git a/tests/test_semantic_types/test_nested_none_guard.py b/tests/test_semantic_types/test_nested_none_guard.py index 7e185c37d..aa678ab65 100644 --- a/tests/test_semantic_types/test_nested_none_guard.py +++ b/tests/test_semantic_types/test_nested_none_guard.py @@ -13,6 +13,7 @@ from typing import Any import numpy as np +import polars as pl import pyarrow as pa import pytest @@ -284,7 +285,9 @@ def test_a_list_source_refuses(self) -> None: def test_a_data_frame_source_raises_at_read(self) -> None: # Polars keeps the null inner list; reading it to Python raises. source = DataFrameSource( - {"id": [1], "v": [[None, [1]]]}, tag_columns=["id"], tag_only_columns=True + pl.DataFrame({"id": [1], "v": [[None, [1]]]}), + tag_columns=["id"], + tag_only_columns=True, ) with pytest.raises(ValueError, match=r"(?s)Column 'v'.*ITL-1144"): _read_v(source)