Skip to content

Commit d7686f6

Browse files
authored
fix(dtype): preserve scaled generic time units and normalize the μs alias (zarr-developers#4342)
* fix(dtype): preserve scaled generic time units and normalize the μs alias `DateTime64` and `TimeDelta64` read unit and scale from the dtype object rather than `dtype.name`, which drops a generic unit's scale. V2 metadata writes an explicit `[Ngeneric]` suffix; the constructor stores `μs` as `us`. NumPy allocation drops a generic time dtype's scale and byte order, and `astype` between generic time dtypes ignores the target. The CPU buffer restores the dtype with a view after allocation and converts endian-only casts through the integer counts. Integer fill values for generic datetimes decode through `datetime_from_int`, and structured defaults build a zero count for generic datetime fields. Assisted-by: ClaudeCode:claude-opus-5-5 * test(dtype): cover the time unit grid through the dtype test harness Generate the valid native dtypes and V2/V3 JSON for `DateTime64` and `TimeDelta64` from every unit, scales 1, 2 and 2**31 - 1, and both byte orders, instead of a separate round-trip test that repeated the harness's native and JSON round trips. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(dtype): keep the scale factor on NaT time scalars `DateTime64.default_scalar`, `TimeDelta64.default_scalar`, and the NaT branch of `TimeDelta64.cast_scalar` built NaT in the bare unit, dropping the scale factor. On NumPy < 2.2, casting a timedelta NaT between scales yields a count instead of NaT, so missing chunks of a `m8[2us]` array read back as 2**62 - 1 instead of NaT. Assisted-by: ClaudeCode:claude-opus-5-5 * docs(changelog): note the scaled NaT fill fix Assisted-by: ClaudeCode:claude-opus-5-5
1 parent 34b7c3d commit d7686f6

7 files changed

Lines changed: 239 additions & 55 deletions

File tree

‎changes/4342.bugfix.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
`DateTime64` and `TimeDelta64` normalize `μs` to `us` and preserve generic-unit scale factors when converting native NumPy dtypes and serializing V2/V3 metadata. V2 writes an explicit suffix such as `[2generic]` to avoid the scale loss in NumPy's `dtype.str` and `dtype.name`. Generic temporal arrays also preserve dtype parameters during CPU buffer allocation and correctly convert byte order; generic datetime fill values can be read back, including in structured fields. The default NaT fill value now carries the scale factor, so missing chunks of a scaled timedelta array such as `m8[2us]` read back as NaT on NumPy < 2.2 instead of an arbitrary count.

‎src/zarr/core/buffer/cpu.py‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
TYPE_CHECKING,
55
Any,
66
Literal,
7+
cast,
78
)
89

910
import numpy as np
@@ -156,22 +157,55 @@ def create(
156157
order: Literal["C", "F"] = "C",
157158
fill_value: Any | None = None,
158159
) -> Self:
160+
parsed_dtype = np.dtype(dtype)
161+
zero_fill = fill_value is None or (isinstance(fill_value, int) and fill_value == 0)
162+
if parsed_dtype.kind in "mM":
163+
# NumPy allocation can drop a generic time unit's scale factor and byte order
164+
# (`np.zeros(1, ">M8[2generic]").dtype` is `<M8`). A view restores both, and
165+
# must precede assignment so values are encoded in the requested byte order.
166+
data = np.zeros(shape=tuple(shape), dtype=parsed_dtype, order=order).view(parsed_dtype)
167+
if not zero_fill:
168+
data[...] = fill_value
159169
# np.zeros is much faster than np.full, and therefore using it when possible is better.
160-
if fill_value is None or (isinstance(fill_value, int) and fill_value == 0):
161-
return cls(np.zeros(shape=tuple(shape), dtype=dtype, order=order))
170+
elif zero_fill:
171+
data = np.zeros(shape=tuple(shape), dtype=dtype, order=order)
162172
else:
163-
return cls(np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order))
173+
data = np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order)
174+
return cls(data)
164175

165176
@classmethod
166177
def empty(
167178
cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C"
168179
) -> Self:
169-
return cls(np.empty(shape=shape, dtype=dtype, order=order))
180+
data = np.empty(shape=shape, dtype=dtype, order=order)
181+
if data.dtype.kind in "mM":
182+
# See `create`: a view restores what allocation drops from generic time dtypes.
183+
data = data.view(dtype=dtype)
184+
return cls(data)
170185

171186
@classmethod
172187
def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self:
173188
return cls.from_ndarray_like(np.asanyarray(array_like))
174189

190+
def astype(self, dtype: npt.DTypeLike, order: Literal["K", "A", "C", "F"] = "K") -> Self:
191+
target = np.dtype(dtype)
192+
if (
193+
self.dtype.kind in "mM"
194+
and isinstance(target, np.dtypes.DateTime64DType | np.dtypes.TimeDelta64DType)
195+
and target.kind == self.dtype.kind
196+
and np.datetime_data(self.dtype)[0] == "generic"
197+
and np.datetime_data(self.dtype)
198+
== np.datetime_data(
199+
cast("np.dtypes.DateTime64DType | np.dtypes.TimeDelta64DType", target)
200+
)
201+
):
202+
# NumPy's astype between generic time dtypes ignores the target and keeps the
203+
# source byte order. Convert the underlying counts for an endian-only cast.
204+
counts = self.as_numpy_array().view(self.dtype.byteorder + "i8")
205+
converted = counts.astype(target.byteorder + "i8", order=order)
206+
return self.__class__(converted.view(target))
207+
return super().astype(dtype, order=order)
208+
175209
def as_numpy_array(self) -> npt.NDArray[Any]:
176210
"""Returns the buffer as a NumPy array (host memory).
177211

‎src/zarr/core/dtype/npy/structured.py‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ def _unsupported_field_feature(dtype: np.dtype[np.void]) -> str | None:
4949
- field titles, e.g. `np.dtype([(("title", "name"), "i4")])`
5050
- subarray fields, e.g. `np.dtype([("name", "i4", (2,))])`
5151
52+
These are implementation restrictions. In particular, Zarr V2 supports subarray
53+
field descriptors; this implementation does not preserve them.
54+
5255
Returns
5356
-------
5457
str | None
@@ -563,7 +566,22 @@ def default_scalar(self) -> np.void:
563566
cast to this structured data type.
564567
"""
565568

566-
return self._cast_scalar_unchecked(0)
569+
values: list[object] = []
570+
for _, field in self.fields:
571+
dtype = field.to_native_dtype()
572+
if isinstance(field, Structured):
573+
value = field.default_scalar()
574+
elif (
575+
isinstance(dtype, np.dtypes.DateTime64DType)
576+
and np.datetime_data(cast("np.dtypes.DateTime64DType", dtype))[0] == "generic"
577+
):
578+
# NumPy rejects casting integer zero to generic datetime, but a
579+
# zero count is representable by viewing the integer storage.
580+
value = np.zeros(1, dtype=dtype.byteorder + "i8").view(dtype)[0]
581+
else:
582+
value = np.array([0], dtype=dtype)[0]
583+
values.append(value)
584+
return self._cast_scalar_unchecked(tuple(values))
567585

568586
def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void:
569587
"""

‎src/zarr/core/dtype/npy/time.py‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,11 @@ def __post_init__(self) -> None:
233233
raise ValueError(f"scale_factor must be < 2147483648, got {self.scale_factor}.")
234234
if self.unit not in get_args(DateTimeUnit):
235235
raise ValueError(f"unit must be one of {get_args(DateTimeUnit)}, got {self.unit!r}.")
236+
if self.unit == "μs":
237+
# NumPy spells the microsecond unit "us" and resolves "μs" to it, so an
238+
# instance built with "μs" would not round-trip through to_native_dtype().
239+
# Store the NumPy spelling; "μs" stays accepted as input and in stored metadata.
240+
object.__setattr__(self, "unit", "us")
236241

237242
@classmethod
238243
def from_native_dtype(cls, dtype: TBaseDType) -> Self:
@@ -256,7 +261,7 @@ def from_native_dtype(cls, dtype: TBaseDType) -> Self:
256261
"""
257262

258263
if cls._check_native_dtype(dtype):
259-
unit, scale_factor = np.datetime_data(dtype.name)
264+
unit, scale_factor = np.datetime_data(dtype)
260265
unit = cast("DateTimeUnit", unit)
261266
return cls(
262267
unit=unit,
@@ -492,7 +497,10 @@ def to_json(self, zarr_format: ZarrFormat) -> TimeDelta64JSON_V2 | TimeDelta64JS
492497
If the zarr_format is not 2 or 3.
493498
"""
494499
if zarr_format == 2:
495-
name = self.to_native_dtype().str
500+
name: str = self.to_native_dtype().str
501+
if self.unit == "generic" and self.scale_factor != 1:
502+
# NumPy omits generic scale from dtype.str; preserve it explicitly.
503+
name += f"[{self.scale_factor}generic]"
496504
return {"name": name, "object_codec_id": None}
497505
elif zarr_format == 3:
498506
return {
@@ -548,8 +556,7 @@ def cast_scalar(self, data: object) -> np.timedelta64:
548556
"""
549557
if self._check_scalar(data):
550558
if isinstance(data, np.timedelta64) and np.isnat(data):
551-
# numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload.
552-
return np.timedelta64("NaT", self.unit) # type: ignore[arg-type]
559+
return self._cast_scalar_unchecked("NaT")
553560
return self._cast_scalar_unchecked(data)
554561
msg = (
555562
f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the "
@@ -564,8 +571,9 @@ def default_scalar(self) -> np.timedelta64:
564571
This method provides a default value for the timedelta64 scalar, which is
565572
a 'Not-a-Time' (NaT) value.
566573
"""
567-
# numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload.
568-
return np.timedelta64("NaT", self.unit) # type: ignore[arg-type]
574+
# Carry the scale factor: NumPy < 2.2 turns a timedelta NaT into a count when
575+
# casting it between scales, e.g. NaT[us] into a [2us] array.
576+
return self._cast_scalar_unchecked("NaT")
569577

570578
def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.timedelta64:
571579
"""
@@ -777,7 +785,10 @@ def to_json(self, zarr_format: ZarrFormat) -> DateTime64JSON_V2 | DateTime64JSON
777785
If the zarr_format is not 2 or 3.
778786
"""
779787
if zarr_format == 2:
780-
name = self.to_native_dtype().str
788+
name: str = self.to_native_dtype().str
789+
if self.unit == "generic" and self.scale_factor != 1:
790+
# NumPy omits generic scale from dtype.str; preserve it explicitly.
791+
name += f"[{self.scale_factor}generic]"
781792
return {"name": name, "object_codec_id": None}
782793
elif zarr_format == 3:
783794
return {
@@ -818,6 +829,9 @@ def _cast_scalar_unchecked(self, data: DateTimeLike) -> np.datetime64:
818829
numpy.datetime64
819830
The input cast to a NumPy datetime scalar.
820831
"""
832+
if isinstance(data, int):
833+
# The scalar constructor rejects integer counts with a generic unit.
834+
return datetime_from_int(data, unit=self.unit, scale_factor=self.scale_factor)
821835
# numpy 2.x stub: datetime64(scalar, formatted_unit_str) is runtime-valid
822836
# but no overload matches the dynamic f-string unit argument.
823837
return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return]
@@ -858,9 +872,7 @@ def default_scalar(self) -> np.datetime64:
858872
numpy.datetime64
859873
The default scalar value, which is a 'Not-a-Time' (NaT) value
860874
"""
861-
862-
# numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload.
863-
return np.datetime64("NaT", self.unit) # type: ignore[arg-type]
875+
return self._cast_scalar_unchecked("NaT")
864876

865877
def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.datetime64:
866878
"""

‎src/zarr/testing/strategies.py‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,23 +95,12 @@ def _leaf_zdtypes(cls: type[ZDType[TBaseDType, TBaseScalar]]) -> SearchStrategy[
9595
if "length" in params:
9696
kwargs["length"] = st.integers(min_value=1, max_value=16)
9797
if "unit" in params:
98-
# NumPy spells the microsecond unit "us", so the "μs" alias never round-trips as-is.
99-
kwargs["unit"] = st.sampled_from([u for u in DATETIME_UNIT if u != "μs"])
98+
# The constructor normalizes the microsecond alias; all units accept a scale.
99+
kwargs["unit"] = st.sampled_from(DATETIME_UNIT)
100100
kwargs["scale_factor"] = st.integers(min_value=1, max_value=2**31 - 1)
101-
return st.builds(cls, **kwargs).map(_normalize_generic_scale_factor)
102101
return st.builds(cls, **kwargs)
103102

104103

105-
def _normalize_generic_scale_factor(zdtype: Any) -> Any:
106-
"""
107-
NumPy retains generic scale factors internally, but its dtype string omits them.
108-
Use `scale_factor=1` so the generated dtype survives Zarr V2 string serialization.
109-
"""
110-
if zdtype.unit == "generic":
111-
return dataclasses.replace(zdtype, scale_factor=1)
112-
return zdtype
113-
114-
115104
def _struct_zdtypes(
116105
children: SearchStrategy[ZDType[Any, Any]],
117106
) -> SearchStrategy[ZDType[Any, Any]]:

‎tests/test_buffer.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,3 +296,32 @@ def test_all_equal_distinguishes_negative_zero(dtype: str) -> None:
296296
assert not cpu.NDBuffer.from_numpy_array(negative).all_equal(0.0)
297297
assert cpu.NDBuffer.from_numpy_array(negative).all_equal(-0.0)
298298
assert not cpu.NDBuffer.from_numpy_array(positive).all_equal(-0.0)
299+
300+
301+
@pytest.mark.parametrize("kind", ["M8", "m8"])
302+
@pytest.mark.parametrize("byteorder", ["<", ">"])
303+
@pytest.mark.parametrize("scale_factor", [2, 2**31 - 1])
304+
@pytest.mark.parametrize("fill_value", [None, 0, "NaT"])
305+
@pytest.mark.parametrize("order", ["C", "F"])
306+
@pytest.mark.filterwarnings(
307+
"ignore:The 'generic' unit for NumPy timedelta is deprecated:DeprecationWarning"
308+
)
309+
def test_cpu_generic_time_allocation(
310+
kind: str,
311+
byteorder: str,
312+
scale_factor: int,
313+
fill_value: int | str | None,
314+
order: Literal["C", "F"],
315+
) -> None:
316+
"""Both allocation paths retain generic scale even when NumPy drops it."""
317+
dtype = np.dtype(f"{byteorder}{kind}[{scale_factor}generic]")
318+
empty = cpu.NDBuffer.empty((2, 3), dtype=dtype, order=order)
319+
filled = cpu.NDBuffer.create(shape=(2, 3), dtype=dtype, order=order, fill_value=fill_value)
320+
for buffer in (empty, filled):
321+
assert buffer.dtype == dtype
322+
array = buffer.as_numpy_array()
323+
assert array.flags.c_contiguous if order == "C" else array.flags.f_contiguous
324+
expected = -(2**63) if fill_value == "NaT" else 0
325+
np.testing.assert_array_equal(
326+
filled.as_numpy_array().view(dtype.byteorder + "i8"), np.full((2, 3), expected)
327+
)

0 commit comments

Comments
 (0)