diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index ef4606c7a..483be75e2 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -74,6 +74,44 @@ jobs: # fails a pull request, whose fork uploads are tokenless (ITL-1193). fail_ci_if_error: ${{ github.event_name != 'pull_request' }} + dependency-range-hashing: + name: Hashing tests (${{ matrix.resolution }}, Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - python-version: "3.11" + resolution: lowest-direct + - python-version: "3.13" + resolution: highest + + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + fetch-depth: 0 # required: hatch-vcs needs full tag history + + - name: Install uv + uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Run hashing tests with freshly resolved dependencies + # Resolve the editable project's runtime dependencies outside uv.lock. Give the + # test runner and PostgreSQL test imports their dev-group floors. The locked + # suite above exercises the optional PyTorch cases. + run: >- + uv run --no-project --python ${{ matrix.python-version }} + --resolution ${{ matrix.resolution }} --with-editable . + --with 'pytest>=8.3.5' --with 'pytest-asyncio>=1.3.0' + --with 'psycopg[binary]>=3.1.17' --with 'testcontainers[postgres]>=4.0.0' + pytest -m 'not postgres' tests/test_hashing + spiral-integration: runs-on: ubuntu-latest # Only run on push/manual trigger — not on PRs — to avoid consuming SpiralDB diff --git a/changelog.d/ITL-1151.md b/changelog.d/ITL-1151.md new file mode 100644 index 000000000..2d27f22d1 --- /dev/null +++ b/changelog.d/ITL-1151.md @@ -0,0 +1,9 @@ +### Fixed + +- Stored Polars DataFrames and Series read back on Polars 1.x and 2.x. +- pandas object-column hashes are independent of dictionary key insertion order across + PyArrow versions, including for nested dictionaries. + +### Changed + +- Raised the minimum versions of Polars to 1.40.0, NetworkX to 2.6.3 and Typer to 0.15.4. diff --git a/docs/dev/design_issues/ITL-1151-DVR1.md b/docs/dev/design_issues/ITL-1151-DVR1.md new file mode 100644 index 000000000..7e2b21889 --- /dev/null +++ b/docs/dev/design_issues/ITL-1151-DVR1.md @@ -0,0 +1,16 @@ +## Dependencies and value hashing + +### DVR1 — Dependency versions affected storage, hashing and CLI compatibility +**Status:** resolved +**Severity:** high +**Issue:** ITL-1151 + +Polars 2 removed arguments passed by the IPC value reader. Earlier Polars versions also +turned a null nested empty struct into a present empty struct. Starting with PyArrow 24, +dictionary insertion order can determine the order of inferred struct fields, which +changed pandas object-column hashes. The dependency floors also let the resolver select +an unbuildable NetworkX release and a Typer release that could not build the CLI. + +**Fix:** Rechunk after reading Polars IPC and require Polars 1.40.0 or newer. Sort inferred +pandas struct fields by name in the hash input. Require NetworkX 2.6.3 and Typer 0.15.4 +or newer. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 1867eb84b..244606737 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -376,7 +376,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label. The handler verifies custom directory hashes against the library Merkle procedure. | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir`, `hashing/semantic_hashing/builtin_handlers.py:DirectoryHandler.handle`, `hashing/directory_hashers.py:verified_directory_hash`, `hashing/directory_hashers.py:canonical_directory_hash` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | -| pandas value hash | descriptor, `\0`, `b"arrow_ordered_v1:" + D` | SHA-256, `pandas_dataframe_v1` / `pandas_series_v1` | pandas value hash | `hashing/pandas_value_hash.py:pandas_frame_content_hash`, `hashing/pandas_value_hash.py:pandas_series_content_hash`, `hashing/labelled_hash.py:labelled_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:PandasDataFrameHandler.digest`, `hashing/semantic_hashing/builtin_handlers.py:PandasSeriesHandler.digest` | +| pandas value hash | descriptor, `\0`, `b"arrow_ordered_v1:" + D`; inferred struct fields in `object` columns are sorted by name at every depth before computing `D` | SHA-256, `pandas_dataframe_v1` / `pandas_series_v1` | pandas value hash | `hashing/pandas_value_hash.py:pandas_frame_content_hash`, `hashing/pandas_value_hash.py:pandas_series_content_hash`, `hashing/labelled_hash.py:labelled_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:PandasDataFrameHandler.digest`, `hashing/semantic_hashing/builtin_handlers.py:PandasSeriesHandler.digest` | | Polars value hash | descriptor, `\0`, starfix digest called directly (a step of this algorithm) | SHA-256, `polars_dataframe_v1` / `polars_series_v1` | Polars value hash | `logical_types/polars_type.py:_digest`, `logical_types/polars_type.py:_values_digest` | | Polars expression hash | the expression's canonical tree | SHA-256 of canonical JSON, `polars_expr_v1` | `PolarsFilter` identity (an operator that is not recommended) | `hashing/semantic_hashing/polars_expr.py:polars_expr_content_hash` | | value handlers with an ignore list | wrap the value digests above | the type's label | top level, nested, Arrow cell | `logical_types/ignore_list.py:IgnoreListHandler.handle`, `logical_types/ignore_list.py:IgnoreListHandler.hash_ignoring` | @@ -2248,7 +2248,8 @@ ContentHash("pandas_dataframe_v1" | "pandas_series_v1", renamed by position, `c0 .. cN-1` for the columns in frame order, then `i0 .. iM-1` for the index levels in order. A Series is digested as its one-column frame. `D` covers the values, the Arrow types, row order, the row count, **column order, index level order and - struct field order**. + struct field order** in the prepared table. Struct fields inferred from an `object` + column are sorted by name at every depth. - `descriptor` is canonical JSON (sorted keys, `,` and `:` separators, UTF-8) in a grammar Orcapod owns, built from the pandas objects themselves. It carries what the Arrow values do not show: `attrs`, typed labels, `columns.names`, the dtype of the column axis, index @@ -2333,8 +2334,10 @@ level whose values are not strings does not read back as `object`: `[1, 2]` read Such a column is described and digested in the form it reads back in, so it hashes like the typed column it becomes. An `object` column of lists or dicts stays `object`, but its elements can change (a list `[1, None]` reads back `[1.0, nan]`), so the Arrow form of what -is read back is digested. Any other `object` column that reads back as `object` (strings, -bytes, decimals, dates) is hashed as it is. +is read back is digested. The hash sorts inferred struct fields by name at every depth, +including inside lists, so dictionary insertion order gives the same hash across PyArrow +versions. Any other `object` column that reads back as `object` (strings, bytes, decimals, +dates) is hashed as it is. **The axes are described as storage restores them.** Storage writes the name of an index level as text. The index names `1` and `"1"` are therefore one name once read back, and diff --git a/pyproject.toml b/pyproject.toml index 73b662747..d5db39436 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,10 +7,10 @@ name = "orcapod" description = "Intuitive and powerful library for highly reproducible scientific data pipeline" dynamic = ["version"] dependencies = [ - "networkx", + "networkx>=2.6.3", "pandas>=2.2.3,<3", "pyarrow>=22.0.0", - "polars>=1.36.0", + "polars>=1.40.0", "numpy>=1.26.4", "beartype>=0.21.0", "deltalake>=1.6.6", @@ -21,7 +21,7 @@ dependencies = [ "uuid-utils>=0.11.1", "s3fs>=2025.12.0", "pydantic>=2.0", - "typer>=0.12", + "typer>=0.15.4", ] readme = "README.md" requires-python = ">=3.11.0" diff --git a/src/orcapod/hashing/pandas_value_hash.py b/src/orcapod/hashing/pandas_value_hash.py index 701154c95..1a7cf34ad 100644 --- a/src/orcapod/hashing/pandas_value_hash.py +++ b/src/orcapod/hashing/pandas_value_hash.py @@ -43,8 +43,9 @@ way storage does, and when the result is no longer ``object``, that dtype is described and its Arrow form is digested. An ``object`` column of lists or dicts stays ``object``, but its elements can change (a list ``[1, None]`` reads back ``[1.0, nan]``), so the Arrow form of -what was read back is digested. Any other ``object`` column that reads back as ``object`` -(strings, bytes, decimals, dates) is hashed as it is. +what was read back is digested, with inferred struct fields sorted by name at every depth. +Any other ``object`` column that reads back as ``object`` (strings, bytes, decimals, dates) +is hashed as it is. A categorical column is described with the categories storage restores: they are read back from the Arrow dictionary, so ``object`` categories ``[1, 2]`` are described as ``int64``. @@ -563,6 +564,24 @@ def _restored_form( return restored_dtype, restored +def _inferred_struct_order(arrow_type: pa.DataType) -> pa.DataType: + """Sort inferred struct fields by name, including through inferred lists.""" + if isinstance(arrow_type, pa.StructType): + return pa.struct( + [ + field.with_type(_inferred_struct_order(field.type)) + for field in sorted(arrow_type, key=lambda field: field.name) + ] + ) + if isinstance(arrow_type, pa.ListType): + field = arrow_type.value_field + return pa.list_(field.with_type(_inferred_struct_order(field.type))) + if isinstance(arrow_type, pa.LargeListType): + field = arrow_type.value_field + return pa.large_list(field.with_type(_inferred_struct_order(field.type))) + return arrow_type + + def _restored_dtype_and_column( dtype: Any, column: pa.ChunkedArray[Any], *, index_level: bool ) -> tuple[Any, pa.ChunkedArray[Any]]: @@ -602,7 +621,12 @@ def _restored_dtype_and_column( # A list or dict cell can change inside: ``[1, None]`` reads back ``[1.0, nan]``. # Decimals read back as ``Decimal`` objects, whose Arrow precision is then taken # from the values, not from the type they were written with. - return dtype, pa.chunked_array([pa.Array.from_pandas(restored)]) + inferred = pa.Array.from_pandas(restored) + # PyArrow 24 and later can infer fields in dictionary insertion order. + canonical_type = _inferred_struct_order(inferred.type) + if canonical_type != inferred.type: + inferred = inferred.cast(canonical_type) + return dtype, pa.chunked_array([inferred]) return dtype, column diff --git a/src/orcapod/logical_types/polars_type.py b/src/orcapod/logical_types/polars_type.py index 4a7d2b125..2c7da5205 100644 --- a/src/orcapod/logical_types/polars_type.py +++ b/src/orcapod/logical_types/polars_type.py @@ -533,8 +533,7 @@ def _frame_to_ipc_bytes(df: pl.DataFrame) -> bytes: Returns: The bytes ``df.write_ipc`` writes (Arrow IPC file format) with Polars' default compression and compatibility level, both pinned here. ``record_batch_size`` is - left at its default without being named: the oldest supported Polars (1.36) has - no such parameter. + left at its default without being named for compatibility with Polars 1.x. Raises: ValueError: If a column's dtype cannot be stored and hashed exactly (see @@ -562,14 +561,7 @@ def _ipc_bytes_to_frame(storage_value: Any) -> pl.DataFrame: Returns: The frame, with the schema it was stored with, in one chunk. """ - return pl.read_ipc( - io.BytesIO(bytes(storage_value)), - columns=None, - n_rows=None, - use_pyarrow=False, - memory_map=False, - rechunk=True, - ) + return pl.read_ipc(io.BytesIO(bytes(storage_value)), use_pyarrow=False).rechunk() class LogicalPolarsDataFrame(IgnoreListLogicalType): diff --git a/tests/test_hashing/test_pandas_value_identity.py b/tests/test_hashing/test_pandas_value_identity.py index e2fd6a234..a33ffb158 100644 --- a/tests/test_hashing/test_pandas_value_identity.py +++ b/tests/test_hashing/test_pandas_value_identity.py @@ -239,6 +239,10 @@ def _timestamp_labels(tz: str | None) -> pd.DataFrame: pd.DataFrame({"s": [{"u": 1, "v": "x"}]}), pd.DataFrame({"s": [{"v": "x", "u": 1}]}), ), + "dict key order inside nested lists and structs": ( + pd.Series([[{"a": {"u": 1, "v": "x"}, "b": 2}], None], dtype=object), + pd.Series([[{"b": 2, "a": {"v": "x", "u": 1}}], None], dtype=object), + ), "chunked copy": (_frame(), pd.concat([_frame().iloc[:1], _frame().iloc[1:]])), } @@ -363,6 +367,7 @@ def _timestamp_labels(tz: str | None) -> pd.DataFrame: "object ints with None vs float64": "object_dtype", "object int index vs int64 index": "object_dtype", "dict key order in an object column": "dict_key_order", + "dict key order inside nested lists and structs": "dict_key_order", "flags": "flags", "-0.0 vs 0.0": "signed_zero", } diff --git a/tests/test_logical_types/test_polars_type.py b/tests/test_logical_types/test_polars_type.py index e5345f1d8..6156baf07 100644 --- a/tests/test_logical_types/test_polars_type.py +++ b/tests/test_logical_types/test_polars_type.py @@ -174,7 +174,7 @@ def test_stored_bytes_are_read_by_polars_read_ipc(self) -> None: """``pl.read_ipc`` reads the stored bytes back as the exact frame.""" df = pl.DataFrame({"x": pl.Series([1, 2], dtype=pl.Int8)}) stored = LogicalPolarsDataFrame().python_to_storage(df) - back = pl.read_ipc(io.BytesIO(stored), memory_map=False) + back = pl.read_ipc(io.BytesIO(stored)) _assert_exact(back, df) def test_chunked_frame_reads_back_with_equal_content(self) -> None: diff --git a/uv.lock b/uv.lock index 8411335e7..57da3a714 100644 --- a/uv.lock +++ b/uv.lock @@ -1947,10 +1947,10 @@ requires-dist = [ { name = "gitpython", specifier = ">=3.1.45" }, { name = "ipywidgets", marker = "extra == 'all'", specifier = ">=8.1.7" }, { name = "ipywidgets", marker = "extra == 'ray'", specifier = ">=8.1.7" }, - { name = "networkx" }, + { name = "networkx", specifier = ">=2.6.3" }, { name = "numpy", specifier = ">=1.26.4" }, { name = "pandas", specifier = ">=2.2.3,<3" }, - { name = "polars", specifier = ">=1.36.0" }, + { name = "polars", specifier = ">=1.40.0" }, { name = "psycopg", extras = ["binary"], marker = "extra == 'all'", specifier = ">=3.1.17" }, { name = "psycopg", extras = ["binary"], marker = "extra == 'postgresql'", specifier = ">=3.1.17" }, { name = "pyarrow", specifier = ">=22.0.0" }, @@ -1967,7 +1967,7 @@ requires-dist = [ { name = "torch", marker = "sys_platform == 'linux' and extra == 'torch'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, { name = "torch", marker = "sys_platform != 'linux' and extra == 'all'", specifier = ">=2.6" }, { name = "torch", marker = "sys_platform != 'linux' and extra == 'torch'", specifier = ">=2.6" }, - { name = "typer", specifier = ">=0.12" }, + { name = "typer", specifier = ">=0.15.4" }, { name = "tzdata", specifier = ">=2024.1" }, { name = "universal-pathlib", specifier = ">=0.3.8" }, { name = "uuid-utils", specifier = ">=0.11.1" },