Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,11 @@ Deprecations

Bug Fixes
~~~~~~~~~
- Opening Zarr stores backed by ``fsspec`` zip filesystems (such as
``zip:///::...`` URLs or ``zarr.storage.FsspecStore`` wrapping a zip
filesystem) now treats missing archive members as absent Zarr keys instead of
raising ``KeyError`` when reading fill-value-only variables or coordinates
(:issue:`10950`).
- Weighted variance, standard deviation and sums of squared deviations now
use conjugated deviations for complex data, matching unweighted reductions
and correcting weighted self-correlation.
Expand Down
139 changes: 137 additions & 2 deletions xarray/backends/zarr.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from __future__ import annotations

import base64
import functools
import json
import os
import struct
from collections.abc import Hashable, Iterable, Mapping
from collections.abc import Callable, Hashable, Iterable, Mapping
from typing import TYPE_CHECKING, Any, Literal, Self, cast, override

import numpy as np
Expand Down Expand Up @@ -36,6 +37,7 @@
attempt_import,
close_on_error,
emit_user_level_warning,
is_remote_uri,
)
from xarray.core.variable import Variable
from xarray.namedarray.parallelcompat import guess_chunkmanager
Expand Down Expand Up @@ -1926,6 +1928,135 @@ def _iter_zarr_groups(root: ZarrGroup, parent: str = "/") -> Iterable[str]:
yield from _iter_zarr_groups(group, parent=str(gpath))


def _is_zip_fsspec_url(store: str) -> bool:
if not is_remote_uri(store):
return False
first_segment = store.split("::", 1)[0]
protocol = (
first_segment.split("://", 1)[0] if "://" in first_segment else first_segment
)
return protocol == "zip"


def _is_zip_fsspec_fs(fs: Any) -> bool:
zip_fs_cls: type[Any] | tuple[type[Any], ...] = ()
async_wrapper_cls: type[Any] | tuple[type[Any], ...] = ()
try:
from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
from fsspec.implementations.zip import ZipFileSystem
except ImportError:
pass
else:
zip_fs_cls = ZipFileSystem
async_wrapper_cls = AsyncFileSystemWrapper

seen: set[int] = set()
while fs is not None and id(fs) not in seen:
seen.add(id(fs))
if isinstance(fs, zip_fs_cls):
return True
protocol = getattr(fs, "protocol", None)
if protocol == "zip" or (
isinstance(protocol, tuple | list | set | frozenset) and "zip" in protocol
):
return True
if isinstance(fs, async_wrapper_cls):
fs = fs.sync_fs
else:
fs = getattr(fs, "sync_fs", None)
return False


@functools.cache
def _zip_missing_key_store_cls() -> type[Any]:
from zarr.storage import WrapperStore

class _ZipMissingKeyStore(WrapperStore):
"""WrapperStore that maps missing-member KeyError from fsspec zip stores to None."""

def with_read_only(self, read_only: bool = False) -> Self:
return type(self)(self._store.with_read_only(read_only))

async def get(
self,
key: str,
prototype: Any,
byte_range: Any = None,
) -> Any:
try:
return await super().get(
key, prototype=prototype, byte_range=byte_range
)
except KeyError:
if not await self._store.exists(key):
return None
raise

async def get_partial_values(
self,
prototype: Any,
key_ranges: Iterable[tuple[str, Any]],
) -> list[Any]:
key_ranges_list = list(key_ranges)
try:
return await super().get_partial_values(
prototype=prototype, key_ranges=key_ranges_list
)
except KeyError:
return [
await self.get(key, prototype=prototype, byte_range=byte_range)
for key, byte_range in key_ranges_list
]

base_get_partial = getattr(WrapperStore, "get_partial", None)
if base_get_partial is not None:
_base_get_partial: Callable[..., Any] = base_get_partial

class _ZipMissingKeyStoreWithGetPartial(_ZipMissingKeyStore):
async def get_partial(
self,
key: str,
*args: Any,
**kwargs: Any,
) -> Any:
try:
return await _base_get_partial(self, key, *args, **kwargs)
except KeyError:
if not await self._store.exists(key):
return None
raise

return _ZipMissingKeyStoreWithGetPartial

return _ZipMissingKeyStore


def _normalize_zip_fsspec_store(
store: Any,
*,
mode: str,
storage_options: dict[str, Any] | None,
) -> tuple[Any, dict[str, Any] | None, bool]:
"""Normalize read-only fsspec zip stores so missing archive members return None."""
if mode != "r":
return store, storage_options, False

from zarr.storage import FsspecStore

if isinstance(store, str) and _is_zip_fsspec_url(store):
fsspec_store = FsspecStore.from_url(
store,
storage_options=storage_options,
read_only=True,
)
return _zip_missing_key_store_cls()(fsspec_store), None, True

if isinstance(store, FsspecStore) and _is_zip_fsspec_fs(store.fs):
return _zip_missing_key_store_cls()(store), storage_options, False

return store, storage_options, False


def _get_open_params(
store,
mode,
Expand All @@ -1945,6 +2076,10 @@ def _get_open_params(
if isinstance(store, os.PathLike):
store = os.fspath(store)

store, storage_options, opened_new_store = _normalize_zip_fsspec_store(
store, mode=mode, storage_options=storage_options
)

open_kwargs = dict(
# mode='a-' is a handcrafted xarray specialty
mode="a" if mode == "a-" else mode,
Expand Down Expand Up @@ -2004,7 +2139,7 @@ def _get_open_params(
open_kwargs["use_consolidated"] = False
zarr_group = zarr.open_group(store, **open_kwargs)

close_store_on_close = zarr_group.store is not store
close_store_on_close = opened_new_store or zarr_group.store is not store

# we use this to determine how to handle fill_value
if use_zarr_fill_value_as_mask is None:
Expand Down
113 changes: 113 additions & 0 deletions xarray/tests/backends/test_zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import tempfile
import uuid
import warnings
import zipfile
from collections import ChainMap
from collections.abc import Iterator, Mapping
from importlib import import_module
Expand Down Expand Up @@ -2578,6 +2579,118 @@ def test_open_fsspec(fsspec_memory_zarr_stores) -> None:
xr.testing.assert_equal(ds0, ds2)


@requires_zarr
@requires_fsspec
def test_load_dataarray_fsspec_zip_coordinates(tmp_path: Path) -> None:
import fsspec
from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
from zarr.storage import FsspecStore, ZipStore

da = DataArray(np.zeros(1), dims="foo", coords={"foo": [0]})
store_dir = tmp_path / "store.zarr"
da.to_zarr(store_dir, zarr_format=3, consolidated=False)

zip_path = tmp_path / "store.zip"
with zipfile.ZipFile(zip_path, "w") as zf:
for file_path in store_dir.rglob("*"):
if file_path.is_file():
zf.write(file_path, arcname=file_path.relative_to(store_dir).as_posix())

zip_url = f"zip:///::{zip_path.as_posix()}"
assert_identical(
da,
xr.load_dataarray(zip_url, engine="zarr", zarr_format=3, consolidated=False),
)

# Default consolidated=None probe falls back to non-consolidated metadata
with pytest.warns(RuntimeWarning, match="consolidated metadata"):
assert_identical(
da,
xr.load_dataarray(zip_url, engine="zarr", zarr_format=3, consolidated=None),
)

# FsspecStore around fsspec's zip filesystem via AsyncFileSystemWrapper
zip_fs = fsspec.filesystem("zip", fo=str(zip_path))
fsspec_store = FsspecStore(
AsyncFileSystemWrapper(zip_fs, asynchronous=True), read_only=True
)
assert_identical(
da,
xr.load_dataarray(
fsspec_store, engine="zarr", zarr_format=3, consolidated=False
),
)

# Directory path and ZipStore still round-trip identically
assert_identical(
da,
xr.load_dataarray(store_dir, engine="zarr", zarr_format=3, consolidated=False),
)
with contextlib.closing(ZipStore(zip_path, mode="r")) as zip_store:
assert_identical(
da,
xr.load_dataarray(
zip_store, engine="zarr", zarr_format=3, consolidated=False
),
)

# Non-fill coordinate value and archive path prefix are read rather than replaced by fill
da_nonzero = DataArray(np.zeros(1), dims="foo", coords={"foo": [1]})
nonzero_dir = tmp_path / "nonzero.zarr"
da_nonzero.to_zarr(nonzero_dir, zarr_format=3, consolidated=False)
nonzero_zip = tmp_path / "nonzero.zip"
with zipfile.ZipFile(nonzero_zip, "w") as zf:
for file_path in nonzero_dir.rglob("*"):
if file_path.is_file():
zf.write(
file_path,
arcname=f"nested/{file_path.relative_to(nonzero_dir).as_posix()}",
)
assert_identical(
da_nonzero,
xr.load_dataarray(
f"zip:///nested::{nonzero_zip.as_posix()}",
engine="zarr",
zarr_format=3,
consolidated=False,
),
)

# A zip archive that is not a zarr store still fails to open
not_zarr_zip = tmp_path / "not_zarr.zip"
with zipfile.ZipFile(not_zarr_zip, "w") as zf:
zf.writestr("readme.txt", "not a zarr store")
with pytest.raises(FileNotFoundError):
xr.load_dataarray(
f"zip:///::{not_zarr_zip.as_posix()}",
engine="zarr",
zarr_format=3,
consolidated=False,
)

# A KeyError from the inner store for a key that exists still propagates
nonzero_zip_fs = fsspec.filesystem("zip", fo=str(nonzero_zip))
nonzero_store = FsspecStore(
AsyncFileSystemWrapper(nonzero_zip_fs, asynchronous=True),
path="nested",
read_only=True,
)
original_cat_file = nonzero_store.fs._cat_file

async def _raise_key_error(path: str, *args: Any, **kwargs: Any) -> bytes:
if path.endswith(("zarr.json", ".zarray", ".zattrs", ".zgroup", ".zmetadata")):
return await original_cat_file(path, *args, **kwargs)
raise KeyError("unexpected key error")

with (
patch.object(nonzero_store.fs, "_cat_file", side_effect=_raise_key_error),
pytest.raises(KeyError, match="unexpected key error"),
):
xr.load_dataarray(
nonzero_store, engine="zarr", zarr_format=3, consolidated=False
)


@requires_zarr
@requires_fsspec
@requires_dask
Expand Down
Loading