Skip to content

Commit 12aa83b

Browse files
deps: bump cast-value.rs to >= 0.4.2 (zarr-developers#4260)
* deps: bump cast-value.rs to >= 0.4.2 * deps: update uv.lock for cast-value-rs >= 0.4.2 The pyproject floor alone left uv.lock pinning 0.4.0, so any lock-honoring install (uv sync --locked/--frozen) kept the version that silently transposes non-row-major input. Assisted-by: ClaudeCode:claude-fable-5 * fix(cast_value): enforce the cast-value-rs floor at runtime The pyproject floor only binds installs that go through the zarr[cast-value-rs] extra. An environment that already has an older cast-value-rs installed kept silently corrupting non-row-major input after upgrading zarr, which is the failure this floor exists to stop. Check the installed version at import and raise from _do_cast, so the error surfaces when the codec is used rather than breaking `import zarr` for everyone else. A backend without distribution metadata (a `maturin develop` build) has no version to compare and is left alone. Assisted-by: ClaudeCode:claude-fable-5 * test(cast_value): cover cast_value next to the transpose codec Regression test for zarr-developers#4237: a cast_value codec on either side of a transpose codec must round-trip, because transpose hands the next codec a non-row-major view. Imported unchanged from zarr-developers#4238, where this test was written. The np.ascontiguousarray workaround that accompanied it there is deliberately left out: cast-value-rs 0.4.2 normalizes layout itself, and the workaround promotes 0-d arrays to shape (1,), breaking 0-d arrays. Co-authored-by: Raphael Jolivet <raphael.jolivet@minesparis.psl.eu> Assisted-by: ClaudeCode:claude-fable-5 --------- Co-authored-by: Raphael Jolivet <contact@raphael-jolivet.name> Co-authored-by: Raphael Jolivet <raphael.jolivet@minesparis.psl.eu>
1 parent e62e45b commit 12aa83b

5 files changed

Lines changed: 230 additions & 74 deletions

File tree

‎changes/4260.bugfix.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The `cast_value` codec now requires `cast-value-rs>=0.4.2`. Earlier versions of that backend silently corrupted data when handed an array that was not row-major — the layout the `transpose` codec produces — so a `cast_value` codec next to a `transpose` codec would either write transposed values with no error or fail with `ValueError: Input array must be contiguous`. The minimum version is enforced at runtime as well as in the package metadata, so an environment that already has an older `cast-value-rs` installed now raises `ImportError` when the codec is used, instead of corrupting data.

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ remote = [
8181
gpu = [
8282
"cupy-cuda12x; sys_platform != 'darwin'",
8383
]
84-
cast-value-rs = ["cast-value-rs"]
84+
cast-value-rs = ["cast-value-rs>=0.4.2"]
8585
cli = ["typer"]
8686
optional = ["universal-pathlib"]
8787

‎src/zarr/codecs/cast_value.py‎

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,18 @@
55
rounding, out-of-range handling, and explicit scalar mappings.
66
77
Requires the optional ``cast-value-rs`` package for the actual casting
8-
logic. Install it with: ``pip install cast-value-rs``.
8+
logic. Install it with: ``pip install 'cast-value-rs>=0.4.2'``.
99
"""
1010

1111
from __future__ import annotations
1212

1313
from collections.abc import Mapping
1414
from dataclasses import dataclass, replace
15+
from importlib.metadata import PackageNotFoundError, version
1516
from typing import TYPE_CHECKING, Final, Literal, TypedDict, cast
1617

1718
import numpy as np
19+
from packaging.version import Version
1820

1921
from zarr.abc.codec import ArrayArrayCodec
2022
from zarr.core.common import JSON, parse_named_configuration
@@ -123,12 +125,40 @@ def parse_scalar_map(obj: ScalarMapJSON | ScalarMap) -> ScalarMap:
123125
# Backend: cast-value-rs
124126
# ---------------------------------------------------------------------------
125127

128+
# Versions below this silently transpose input arrays that are not row-major -
129+
# the layout `transpose` hands to the next codec - writing corrupted data with
130+
# no error. Keep in sync with the `cast-value-rs` extra in pyproject.toml.
131+
CAST_VALUE_RS_MIN_VERSION: Final = "0.4.2"
132+
133+
_INSTALL_HINT: Final = f"Install it with: pip install 'cast-value-rs>={CAST_VALUE_RS_MIN_VERSION}'"
134+
135+
136+
def _check_backend_version() -> str | None:
137+
"""Return a message describing an unusable backend version, or `None` if it is usable."""
138+
try:
139+
installed = version("cast-value-rs")
140+
except PackageNotFoundError:
141+
# Importable but without distribution metadata, e.g. a `maturin develop`
142+
# build. There is no version to compare, so let it through.
143+
return None
144+
if Version(installed) < Version(CAST_VALUE_RS_MIN_VERSION):
145+
return (
146+
f"The cast_value codec requires cast-value-rs >= {CAST_VALUE_RS_MIN_VERSION}, "
147+
f"but version {installed} is installed. Earlier versions silently corrupt data "
148+
f"when the input array is not row-major. {_INSTALL_HINT}"
149+
)
150+
return None
151+
152+
153+
# Set once at import; raised from `_do_cast`, so an unusable backend does not
154+
# make `import zarr` fail for users who never touch this codec.
155+
_BACKEND_ERROR: str | None
126156
try:
127157
from cast_value_rs import cast_array as cast_array_rs
128-
129-
_HAS_RUST_BACKEND = True
130158
except ModuleNotFoundError:
131-
_HAS_RUST_BACKEND = False
159+
_BACKEND_ERROR = f"The cast_value codec requires the 'cast-value-rs' package. {_INSTALL_HINT}"
160+
else:
161+
_BACKEND_ERROR = _check_backend_version()
132162

133163

134164
def _check_representable(
@@ -305,11 +335,8 @@ def _do_cast(
305335
target_dtype: np.dtype,
306336
scalar_map: Mapping[str | float | int, str | float | int] | None,
307337
) -> np.ndarray:
308-
if not _HAS_RUST_BACKEND:
309-
raise ImportError(
310-
"The cast_value codec requires the 'cast-value-rs' package. "
311-
"Install it with: pip install cast-value-rs"
312-
)
338+
if _BACKEND_ERROR is not None:
339+
raise ImportError(_BACKEND_ERROR)
313340
scalar_map_entries: dict[float | int, float | int] | None = None
314341
if scalar_map is not None:
315342
src_dtype = arr.dtype

‎tests/test_codecs/test_cast_value.py‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
import numpy as np
66
import pytest
7+
from numpy.testing import assert_array_equal
78

89
import zarr
910
from tests.conftest import Expect, ExpectFail
11+
from zarr.codecs import BytesCodec, TransposeCodec
1012
from zarr.codecs.cast_value import CastValue
13+
from zarr.storage import MemoryStore
1114

1215
try:
1316
import cast_value_rs # noqa: F401
@@ -477,3 +480,134 @@ def test_parse_scalar_map(case: Expect[Any, Any]) -> None:
477480
from zarr.codecs.cast_value import parse_scalar_map
478481

479482
assert parse_scalar_map(case.input) == case.output
483+
484+
485+
# ---------------------------------------------------------------------------
486+
# Backend version guard
487+
# ---------------------------------------------------------------------------
488+
489+
490+
@pytest.mark.parametrize(
491+
"case",
492+
[
493+
Expect(input="0.4.2", output=None, id="exactly-minimum"),
494+
Expect(input="0.4.3", output=None, id="newer-patch"),
495+
Expect(input="0.5.0", output=None, id="newer-minor"),
496+
Expect(input="1.0.0", output=None, id="newer-major"),
497+
Expect(input="0.4.2.post1", output=None, id="post-release"),
498+
Expect(input="0.4.0", output="0.4.0", id="known-corrupting"),
499+
Expect(input="0.4.1", output="0.4.1", id="one-patch-below"),
500+
Expect(input="0.3.0", output="0.3.0", id="older-minor"),
501+
Expect(input="0.4.2.dev1", output="0.4.2.dev1", id="pre-release-of-minimum"),
502+
],
503+
ids=lambda c: c.id,
504+
)
505+
def test_check_backend_version(
506+
case: Expect[str, str | None], monkeypatch: pytest.MonkeyPatch
507+
) -> None:
508+
"""Versions at or above the minimum pass; older ones report the installed version."""
509+
from zarr.codecs import cast_value as mod
510+
511+
monkeypatch.setattr(mod, "version", lambda _: case.input)
512+
result = mod._check_backend_version()
513+
514+
if case.output is None:
515+
assert result is None
516+
else:
517+
assert result is not None
518+
assert case.output in result
519+
assert mod.CAST_VALUE_RS_MIN_VERSION in result
520+
521+
522+
def test_check_backend_version_allows_missing_metadata(monkeypatch: pytest.MonkeyPatch) -> None:
523+
"""A backend without distribution metadata is allowed: there is no version to compare."""
524+
from importlib.metadata import PackageNotFoundError
525+
526+
from zarr.codecs import cast_value as mod
527+
528+
def raise_not_found(_: str) -> str:
529+
raise PackageNotFoundError
530+
531+
monkeypatch.setattr(mod, "version", raise_not_found)
532+
assert mod._check_backend_version() is None
533+
534+
535+
def test_encode_rejects_outdated_backend(monkeypatch: pytest.MonkeyPatch) -> None:
536+
"""Using the codec with an outdated backend raises instead of corrupting data."""
537+
from zarr.codecs import cast_value as mod
538+
539+
monkeypatch.setattr(mod, "_BACKEND_ERROR", "outdated backend")
540+
codec = CastValue(data_type="uint16")
541+
542+
with pytest.raises(ImportError, match="outdated backend"):
543+
codec._do_cast(
544+
np.arange(4, dtype=np.float32), target_dtype=np.dtype("uint16"), scalar_map=None
545+
)
546+
547+
548+
def test_min_version_matches_pyproject() -> None:
549+
"""The runtime floor and the packaging floor must not drift apart."""
550+
import re
551+
import tomllib
552+
from pathlib import Path
553+
554+
from zarr.codecs.cast_value import CAST_VALUE_RS_MIN_VERSION
555+
556+
pyproject = Path(__file__).parents[2] / "pyproject.toml"
557+
if not pyproject.is_file():
558+
pytest.skip("pyproject.toml is not available in an installed checkout")
559+
560+
with pyproject.open("rb") as f:
561+
extras = tomllib.load(f)["project"]["optional-dependencies"]
562+
563+
(requirement,) = extras["cast-value-rs"]
564+
match = re.fullmatch(r"cast-value-rs>=(?P<version>[\w.]+)", requirement)
565+
assert match is not None, f"unexpected requirement form: {requirement!r}"
566+
assert match.group("version") == CAST_VALUE_RS_MIN_VERSION
567+
568+
569+
# ---------------------------------------------------------------------------
570+
# Non-contiguous input (regression for #4237)
571+
# ---------------------------------------------------------------------------
572+
573+
574+
@requires_cast_value_rs
575+
def test_enforce_contiguous_arrays() -> None:
576+
"""
577+
Transpose codec produces non-contiguous arrays.
578+
Ensure cast_value makes them contiguous before processing.
579+
"""
580+
data = np.arange(20, dtype=np.float32).reshape(5, 2, 2)
581+
582+
def make_array(filters: list[Any]) -> Any:
583+
return zarr.create_array(
584+
store=MemoryStore(),
585+
shape=data.shape,
586+
dtype=data.dtype,
587+
chunks=data.shape,
588+
filters=filters,
589+
serializer=BytesCodec(endian="little"),
590+
compressors=None,
591+
zarr_format=3,
592+
)
593+
594+
# Cast before transpose
595+
array = make_array(
596+
[
597+
CastValue(data_type="uint16"),
598+
TransposeCodec(order=(1, 2, 0)),
599+
]
600+
)
601+
array[:] = data
602+
assert_array_equal(array[:], data)
603+
604+
# Cast after transpose
605+
array = make_array(
606+
[
607+
TransposeCodec(order=(1, 2, 0)),
608+
CastValue(data_type="uint16"),
609+
]
610+
)
611+
612+
array[:] = data
613+
assert_array_equal(array[:], data)

0 commit comments

Comments
 (0)