From ef5694891241f9e083b76bff4fbf5d283d2b2854 Mon Sep 17 00:00:00 2001 From: Xarray-Beam authors Date: Mon, 30 Nov 2026 13:30:58 -0800 Subject: [PATCH] Prefer Zarr v3 shard sizes when inferring chunks in open_zarr When opening sharded Zarr v3 datasets, `open_zarr` and `Dataset.from_zarr` now default to outer shard boundaries instead of inner chunk boundaries, while preserving Zarr v2, unsharded Zarr v3, and explicit `chunks` override behavior. PiperOrigin-RevId: 1032923667 --- examples/era5_climatology_test.py | 2 +- xarray_beam/_src/combiners.py | 11 ++- xarray_beam/_src/dataset.py | 3 +- xarray_beam/_src/dataset_test.py | 88 ++++++++++++++--- xarray_beam/_src/test_util.py | 2 +- xarray_beam/_src/zarr.py | 19 ++-- xarray_beam/_src/zarr_test.py | 152 ++++++++++++++++++++++++++++++ 7 files changed, 250 insertions(+), 27 deletions(-) diff --git a/examples/era5_climatology_test.py b/examples/era5_climatology_test.py index 64d48be..503b40f 100644 --- a/examples/era5_climatology_test.py +++ b/examples/era5_climatology_test.py @@ -27,7 +27,7 @@ def test(self): input_path = self.create_tempdir('source').full_path output_path = self.create_tempdir('destination').full_path - input_ds = test_util.dummy_era5_surface_dataset(times=90 * 24, freq='1H') + input_ds = test_util.dummy_era5_surface_dataset(times=90 * 24, freq='1h') input_ds.chunk({'time': 31}).to_zarr(input_path) expected = input_ds.groupby('time.month').apply( diff --git a/xarray_beam/_src/combiners.py b/xarray_beam/_src/combiners.py index 0e1adc7..412bb85 100644 --- a/xarray_beam/_src/combiners.py +++ b/xarray_beam/_src/combiners.py @@ -18,7 +18,7 @@ import dataclasses import logging import math -from typing import Literal +from typing import TypeVar import apache_beam as beam import numpy.typing as npt @@ -32,6 +32,7 @@ DimLike = str | Sequence[str] | None +_T = TypeVar('_T') @dataclasses.dataclass @@ -350,8 +351,8 @@ def _finalize_no_combiner( return key, chunk def _prepare_key( - self, key: core.Key, chunk: xarray.Dataset - ) -> tuple[tuple[tuple[int, ...], core.Key], xarray.Dataset]: + self, key: core.Key, chunk: _T + ) -> tuple[tuple[tuple[int, ...], core.Key], _T]: assert self.bins_per_stage # not empty index = _get_chunk_index(key, self.dims, self.chunks, self.sizes) # strip the final bin because it isn't needed for the combiner @@ -360,8 +361,8 @@ def _prepare_key( return ((bin_ids, key), chunk) def _strip_leading_fanout_bin( - self, bin_key: tuple[tuple[int, ...], core.Key], value: xarray.Dataset - ) -> tuple[tuple[tuple[int, ...], core.Key], xarray.Dataset]: + self, bin_key: tuple[tuple[int, ...], core.Key], value: _T + ) -> tuple[tuple[tuple[int, ...], core.Key], _T]: bin_ids, key = bin_key return (bin_ids[1:], key), value diff --git a/xarray_beam/_src/dataset.py b/xarray_beam/_src/dataset.py index 3b0a051..2f7e6cf 100644 --- a/xarray_beam/_src/dataset.py +++ b/xarray_beam/_src/dataset.py @@ -675,7 +675,8 @@ def from_zarr( path: Zarr path to read from. chunks: optional mapping from dimension names to chunk sizes, or any value that can be passed to :py:func:`xarray_beam.normalize_chunks`. If not - provided, the chunk sizes will be inferred from the Zarr file. + provided, the chunk sizes (or shard sizes, for sharded Zarr v3 stores) + will be inferred from the Zarr file. split_vars: whether variables are split between separate elements in the ptransform, or all stored in the same element. pipeline: Beam pipeline to use for this dataset. If not provided, you will diff --git a/xarray_beam/_src/dataset_test.py b/xarray_beam/_src/dataset_test.py index 22aecae..6f59d14 100644 --- a/xarray_beam/_src/dataset_test.py +++ b/xarray_beam/_src/dataset_test.py @@ -633,6 +633,63 @@ def test_from_zarr_with_chunks(self): collected = beam_ds.collect_with_direct_runner() xarray.testing.assert_identical(ds, collected) + @parameterized.parameters( + dict(split_vars=False), + dict(split_vars=True), + ) + def test_from_zarr_sharded(self, split_vars): + """Dataset.from_zarr defaults to shard boundaries and honors overrides.""" + temp_dir = self.create_tempdir().full_path + ds = xarray.Dataset( + { + 'foo': (('x', 'y'), np.arange(72).reshape(12, 6)), + 'bar': (('x', 'y'), -np.arange(72).reshape(12, 6)), + }, + coords={'x': np.arange(12), 'y': np.arange(6)}, + attrs={'description': 'sharded zarr v3'}, + ) + ds.to_zarr( + temp_dir, + zarr_format=3, + encoding={ + 'foo': {'chunks': (2, 3), 'shards': (6, 6)}, + 'bar': {'chunks': (2, 3), 'shards': (6, 6)}, + }, + ) + + beam_ds = xbeam.Dataset.from_zarr(temp_dir, split_vars=split_vars) + self.assertEqual(beam_ds.chunks, {'x': 6, 'y': 6}) + actual_chunks = test_util.EagerPipeline() | beam_ds.ptransform + keys = [k for k, _ in actual_chunks] + if split_vars: + expected_keys = [ + xbeam.Key({'x': 0, 'y': 0}, {'foo'}), + xbeam.Key({'x': 6, 'y': 0}, {'foo'}), + xbeam.Key({'x': 0, 'y': 0}, {'bar'}), + xbeam.Key({'x': 6, 'y': 0}, {'bar'}), + ] + else: + expected_keys = [ + xbeam.Key({'x': 0, 'y': 0}), + xbeam.Key({'x': 6, 'y': 0}), + ] + self.assertCountEqual(keys, expected_keys) + collected = beam_ds.collect_with_direct_runner() + xarray.testing.assert_identical(ds, collected) + + beam_ds_override = xbeam.Dataset.from_zarr( + temp_dir, chunks={'x': 2, 'y': 3}, split_vars=split_vars + ) + self.assertEqual(beam_ds_override.chunks, {'x': 2, 'y': 3}) + collected_override = beam_ds_override.collect_with_direct_runner() + xarray.testing.assert_identical(ds, collected_override) + + target_bytes = 6 * 6 * 8 * (1 if split_vars else 2) * 2 + beam_ds_bytes = xbeam.Dataset.from_zarr( + temp_dir, chunks=f'{target_bytes}B', split_vars=split_vars + ) + self.assertEqual(beam_ds_bytes.chunks, {'x': 12, 'y': 6}) + def test_to_zarr(self): temp_dir = self.create_tempdir().full_path ds = xarray.Dataset({'foo': ('x', np.arange(12))}) @@ -691,7 +748,8 @@ def test_to_zarr_shards(self): ) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds, opened) - self.assertEqual(chunks, {'x': 3}) + self.assertEqual(chunks, {'x': 6}) + self.assertEqual(opened['foo'].encoding['chunks'], (3,)) self.assertEqual(opened['foo'].encoding['shards'], (6,)) with self.subTest('unnormalized_shards'): @@ -703,7 +761,8 @@ def test_to_zarr_shards(self): ) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds, opened) - self.assertEqual(chunks, {'x': 3}) + self.assertEqual(chunks, {'x': 6}) + self.assertEqual(opened['foo'].encoding['chunks'], (3,)) self.assertEqual(opened['foo'].encoding['shards'], (6,)) with self.subTest('larger_shards'): @@ -737,7 +796,8 @@ def test_to_zarr_shards_round_up(self, zarr_shards): ) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds, opened) - self.assertEqual(chunks, {'x': 10}) + self.assertEqual(chunks, {'x': 19}) + self.assertEqual(opened['foo'].encoding['chunks'], (10,)) self.assertEqual(opened['foo'].encoding['shards'], (20,)) def test_to_zarr_chunks_per_shard(self): @@ -750,7 +810,7 @@ def test_to_zarr_chunks_per_shard(self): p |= beam_ds.to_zarr(temp_dir, zarr_chunks_per_shard={'x': 2}) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds, opened) - self.assertEqual(chunks, {'x': 3}) + self.assertEqual(chunks, {'x': 6}) self.assertEqual(opened['foo'].encoding['chunks'], (3,)) self.assertEqual(opened['foo'].encoding['shards'], (6,)) @@ -770,7 +830,7 @@ def test_to_zarr_chunks_per_shard(self): p |= beam_ds.to_zarr(temp_dir, zarr_chunks_per_shard={...: 2}) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds, opened) - self.assertEqual(chunks, {'x': 3}) + self.assertEqual(chunks, {'x': 6}) self.assertEqual(opened['foo'].encoding['chunks'], (3,)) self.assertEqual(opened['foo'].encoding['shards'], (6,)) @@ -782,7 +842,7 @@ def test_to_zarr_chunks_per_shard(self): p |= beam_ds2.to_zarr(temp_dir, zarr_chunks_per_shard={'x': 3, ...: 1}) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds2, opened) - self.assertEqual(chunks, {'x': 2, 'y': 5}) + self.assertEqual(chunks, {'x': 6, 'y': 5}) self.assertEqual(opened['foo'].encoding['chunks'], (2, 5)) self.assertEqual(opened['foo'].encoding['shards'], (6, 5)) @@ -798,7 +858,7 @@ def test_to_zarr_chunks_per_shard(self): ) opened, chunks = xbeam.open_zarr(temp_dir) xarray.testing.assert_identical(ds, opened) - self.assertEqual(chunks, {'x': 3}) + self.assertEqual(chunks, {'x': 6}) self.assertEqual(opened['foo'].encoding['chunks'], (3,)) self.assertEqual(opened['foo'].encoding['shards'], (6,)) @@ -1262,7 +1322,7 @@ class EndToEndTest(test_util.TestCase): def test_bytes_per_chunk_and_chunk_count(self): source_ds = test_util.dummy_era5_surface_dataset( - variables=2, latitudes=73, longitudes=144, times=365, freq='24H' + variables=2, latitudes=73, longitudes=144, times=365, freq='24h' ) xbeam_ds = xbeam.Dataset.from_xarray( @@ -1288,7 +1348,7 @@ def test_docstring_example(self): output_path = self.create_tempdir('output').full_path source_ds = test_util.dummy_era5_surface_dataset( - variables=2, latitudes=73, longitudes=144, times=365, freq='24H' + variables=2, latitudes=73, longitudes=144, times=365, freq='24h' ) source_ds.chunk({'time': 90}).to_zarr(input_path) @@ -1309,7 +1369,7 @@ def test_climatology(self): input_path = self.create_tempdir('source').full_path output_path = self.create_tempdir('output').full_path - source_ds = test_util.dummy_era5_surface_dataset(times=365, freq='24H') + source_ds = test_util.dummy_era5_surface_dataset(times=365, freq='24h') source_ds.chunk({'time': 90}).to_zarr(input_path) transform = ( @@ -1330,7 +1390,7 @@ def test_resample(self): output_path = self.create_tempdir('output').full_path source_ds = test_util.dummy_era5_surface_dataset( - latitudes=73, longitudes=144, times=365, freq='24H' + latitudes=73, longitudes=144, times=365, freq='24h' ) source_ds.chunk({'time': 90}).to_zarr(input_path) @@ -1351,7 +1411,9 @@ def test_resample(self): expected = source_ds.resample(time='10D').mean() actual, chunks = xbeam.open_zarr(output_path) xarray.testing.assert_identical(expected, actual) - self.assertEqual(chunks, {'time': 10, 'latitude': 73, 'longitude': 144}) + self.assertEqual(chunks, {'time': 20, 'latitude': 73, 'longitude': 144}) + self.assertEqual(actual['asn'].encoding['chunks'], (10, 73, 144)) + self.assertEqual(actual['asn'].encoding['shards'], (20, 73, 144)) def test_multiple_analysis_ready_outputs(self): input_path = self.create_tempdir('source').full_path @@ -1359,7 +1421,7 @@ def test_multiple_analysis_ready_outputs(self): climatology_path = self.create_tempdir('climatology').full_path source_ds = test_util.dummy_era5_surface_dataset( - latitudes=73, longitudes=144, times=365, freq='24H' + latitudes=73, longitudes=144, times=365, freq='24h' ) source_ds.chunk({'time': 30}).to_zarr(input_path) diff --git a/xarray_beam/_src/test_util.py b/xarray_beam/_src/test_util.py index fcba90b..614d399 100644 --- a/xarray_beam/_src/test_util.py +++ b/xarray_beam/_src/test_util.py @@ -78,7 +78,7 @@ def dummy_era5_surface_dataset( latitudes=73, longitudes=144, times=365 * 4, - freq='6H', + freq='6h', ): """A mock version of the Pangeo ERA5 surface reanalysis dataset.""" # based on: gs://pangeo-era5/reanalysis/spatial-analysis diff --git a/xarray_beam/_src/zarr.py b/xarray_beam/_src/zarr.py index 56d0f63..9363819 100644 --- a/xarray_beam/_src/zarr.py +++ b/xarray_beam/_src/zarr.py @@ -48,13 +48,18 @@ def _infer_chunks(dataset: xarray.Dataset) -> dict[str, int]: """Infer chunks for an xarray.Dataset loaded from Zarr.""" # The original Zarr array chunks (as tuples) are stored in the "encoding" - # dictionary on each DataArray object. + # dictionary on each DataArray object. For sharded Zarr v3 arrays, prefer + # shard sizes over inner chunk sizes so keys align with shard boundaries. chunks_sets = collections.defaultdict(set) for name, variable in dataset.items(): # exclude variables that are indexed, which are loaded into memory already if name not in dataset.indexes: - for dim, size in zip(variable.dims, variable.encoding['chunks']): + shards = variable.encoding.get('shards') + sizes = shards if shards is not None else variable.encoding['chunks'] + for dim, size in zip(variable.dims, sizes): + if dataset.sizes[dim] > 0: + size = min(size, dataset.sizes[dim]) chunks_sets[dim].add(size) chunks = {} @@ -74,9 +79,10 @@ def open_zarr( ) -> tuple[xarray.Dataset, dict[str, int]]: """Returns a lazily indexable xarray.Dataset and chunks from a Zarr store. - Only Zarr stores with the consistent chunking between non-indexed variables - (i.e., those for which the ``Dataset.chunks`` property is valid) can be - opened. + Only Zarr stores with consistent chunking (or sharding, for sharded Zarr v3 + stores) between non-indexed variables can be opened. For sharded Zarr v3 + stores, the returned chunk sizes correspond to the outer shard sizes rather + than inner chunk sizes. Args: store: Xarray compatible Zarr store to open. @@ -85,7 +91,8 @@ def open_zarr( Returns: (dataset, chunks) pair, consisting of a Dataset with the contents of the - Zarr store and a dict mapping from dimensions to integer chunk sizes. + Zarr store and a dict mapping from dimensions to integer chunk (or shard) + sizes. """ if 'chunks' in kwargs: raise TypeError( diff --git a/xarray_beam/_src/zarr_test.py b/xarray_beam/_src/zarr_test.py index a7d9cf9..b763275 100644 --- a/xarray_beam/_src/zarr_test.py +++ b/xarray_beam/_src/zarr_test.py @@ -43,6 +43,158 @@ def test_open_zarr(self): self.assertEqual(roundtripped_ds.chunks, {}) self.assertEqual(chunks, {'x': 2}) + @parameterized.parameters(dict(zarr_format=2), dict(zarr_format=3)) + def test_open_zarr_unsharded_formats(self, zarr_format): + """open_zarr infers inner chunk sizes for unsharded Zarr v2 and v3 stores.""" + source_ds = xarray.Dataset( + {'foo': (('x', 'y'), np.arange(12).reshape(4, 3))}, + coords={'x': np.arange(4), 'y': np.arange(3)}, + ) + temp_dir = self.create_tempdir().full_path + source_ds.chunk({'x': 2, 'y': 2}).to_zarr(temp_dir, zarr_format=zarr_format) + roundtripped_ds, chunks = xbeam.open_zarr(temp_dir) + xarray.testing.assert_identical(roundtripped_ds, source_ds) + self.assertEqual(roundtripped_ds.chunks, {}) + self.assertEqual(chunks, {'x': 2, 'y': 2}) + self.assertIsNone(roundtripped_ds['foo'].encoding.get('shards')) + + def test_open_zarr_sharded_v3(self): + """open_zarr infers outer shard sizes while preserving inner chunk encoding.""" + source_ds = xarray.Dataset( + { + 'foo': (('x', 'y'), np.arange(72).reshape(12, 6)), + 'bar': ('x', np.arange(12)), + }, + coords={'x': np.arange(12), 'y': np.arange(6)}, + attrs={'title': 'sharded'}, + ) + temp_dir = self.create_tempdir().full_path + source_ds.to_zarr( + temp_dir, + zarr_format=3, + encoding={ + 'foo': {'chunks': (2, 3), 'shards': (6, 6)}, + 'bar': {'chunks': (2,), 'shards': (6,)}, + }, + ) + roundtripped_ds, chunks = xbeam.open_zarr(temp_dir) + xarray.testing.assert_identical(roundtripped_ds, source_ds) + self.assertEqual(roundtripped_ds.chunks, {}) + self.assertEqual(chunks, {'x': 6, 'y': 6}) + self.assertEqual(roundtripped_ds['foo'].encoding['chunks'], (2, 3)) + self.assertEqual(roundtripped_ds['foo'].encoding['shards'], (6, 6)) + + actual_chunks = test_util.EagerPipeline() | xbeam.DatasetToChunks( + roundtripped_ds, chunks + ) + expected_chunks = [ + (xbeam.Key({'x': 0, 'y': 0}), source_ds.isel(x=slice(0, 6))), + (xbeam.Key({'x': 6, 'y': 0}), source_ds.isel(x=slice(6, 12))), + ] + self.assertIdenticalChunks(expected_chunks, actual_chunks) + + def test_open_zarr_sharded_v3_partial_end_shard(self): + """open_zarr handles a trailing partial shard whose length is not a chunk multiple.""" + source_ds = xarray.Dataset( + {'foo': ('lat', np.arange(721, dtype=np.float32))}, + coords={'lat': np.linspace(-90.0, 90.0, 721)}, + ) + temp_dir = self.create_tempdir().full_path + source_ds.to_zarr( + temp_dir, + zarr_format=3, + encoding={'foo': {'chunks': (45,), 'shards': (405,)}}, + ) + roundtripped_ds, chunks = xbeam.open_zarr(temp_dir) + self.assertEqual(chunks, {'lat': 405}) + actual_chunks = test_util.EagerPipeline() | xbeam.DatasetToChunks( + roundtripped_ds, chunks + ) + expected_chunks = [ + (xbeam.Key({'lat': 0}), source_ds.isel(lat=slice(0, 405))), + (xbeam.Key({'lat': 405}), source_ds.isel(lat=slice(405, 721))), + ] + self.assertIdenticalChunks(expected_chunks, actual_chunks) + self.assertEqual(actual_chunks[1][1].sizes['lat'], 316) + + def test_open_zarr_inconsistent_shards(self): + """open_zarr raises an error when variables have different shard sizes on a dim.""" + source_ds = xarray.Dataset( + { + 'foo': ('x', np.arange(12)), + 'bar': ('x', np.arange(12)), + }, + ) + temp_dir = self.create_tempdir().full_path + source_ds.to_zarr( + temp_dir, + zarr_format=3, + encoding={ + 'foo': {'chunks': (2,), 'shards': (4,)}, + 'bar': {'chunks': (2,), 'shards': (6,)}, + }, + ) + with self.assertRaisesRegex( + ValueError, + "inconsistent chunk sizes on Zarr dataset for dimension 'x': {4, 6}", + ): + xbeam.open_zarr(temp_dir) + + def test_open_zarr_mixed_sharded_and_unsharded(self): + """open_zarr reconciles sharded and unsharded variables with matching outer sizes.""" + source_ds = xarray.Dataset( + { + 'foo': (('x', 'y'), np.arange(72).reshape(12, 6)), + 'bar': ('x', np.arange(12)), + }, + ) + temp_dir = self.create_tempdir().full_path + source_ds.to_zarr( + temp_dir, + zarr_format=3, + encoding={ + 'foo': {'chunks': (2, 3), 'shards': (6, 6)}, + 'bar': {'chunks': (6,)}, + }, + ) + roundtripped_ds, chunks = xbeam.open_zarr(temp_dir) + xarray.testing.assert_identical(roundtripped_ds, source_ds) + self.assertEqual(chunks, {'x': 6, 'y': 6}) + + def test_open_zarr_clamps_oversized_shards(self): + """open_zarr clamps rounded-up shard sizes to dim size for Rechunk.""" + source_ds = xarray.Dataset( + { + 'foo': ('x', np.arange(19, dtype='int64')), + 'bar': ('x', -np.arange(19, dtype='int64')), + }, + ) + temp_dir = self.create_tempdir().full_path + source_ds.to_zarr( + temp_dir, + zarr_format=3, + encoding={ + 'foo': {'chunks': (10,), 'shards': (20,)}, + 'bar': {'chunks': (15,), 'shards': (30,)}, + }, + ) + roundtripped_ds, chunks = xbeam.open_zarr(temp_dir) + xarray.testing.assert_identical(roundtripped_ds, source_ds) + self.assertEqual(chunks, {'x': 19}) + + rechunked = ( + test_util.EagerPipeline() + | xbeam.DatasetToChunks(roundtripped_ds, chunks) + | xbeam.Rechunk( + roundtripped_ds.sizes, + source_chunks=chunks, + target_chunks={'x': -1}, + itemsize=8, + ) + ) + self.assertLen(rechunked, 1) + xarray.testing.assert_identical(rechunked[0][1], source_ds) + def test_open_zarr_inconsistent(self): source_ds = xarray.Dataset( {