diff --git a/changes/4707.bugfix.md b/changes/4707.bugfix.md new file mode 100644 index 0000000000..9f6b50b08b --- /dev/null +++ b/changes/4707.bugfix.md @@ -0,0 +1 @@ +LocalStore.get_partial_values() now returns `None` for each missing key and returns the requested byte ranges for the other entries in order. diff --git a/src/zarr/storage/_local.py b/src/zarr/storage/_local.py index 20d4b102b1..912d2cf421 100644 --- a/src/zarr/storage/_local.py +++ b/src/zarr/storage/_local.py @@ -2,9 +2,11 @@ import asyncio import contextlib +import errno import io import os import shutil +import stat import sys import time import uuid @@ -28,21 +30,35 @@ from zarr.core.buffer import BufferPrototype -def _get(path: Path, prototype: BufferPrototype, byte_range: ByteRequest | None) -> Buffer: +def _read_file(path: Path, byte_range: ByteRequest | None) -> bytes: if byte_range is None: - return prototype.buffer.from_bytes(path.read_bytes()) + return path.read_bytes() with path.open("rb") as f: size = f.seek(0, io.SEEK_END) if isinstance(byte_range, RangeByteRequest): f.seek(byte_range.start) - return prototype.buffer.from_bytes(f.read(byte_range.end - f.tell())) + return f.read(byte_range.end - f.tell()) elif isinstance(byte_range, OffsetByteRequest): f.seek(byte_range.offset) elif isinstance(byte_range, SuffixByteRequest): f.seek(max(0, size - byte_range.suffix)) else: raise TypeError(f"Unexpected byte_range, got {byte_range}.") - return prototype.buffer.from_bytes(f.read()) + return f.read() + + +def _get(path: Path, prototype: BufferPrototype, byte_range: ByteRequest | None) -> Buffer | None: + try: + data = _read_file(path, byte_range) + except (FileNotFoundError, IsADirectoryError, NotADirectoryError): + return None + except PermissionError: + # Opening a directory on Windows can report access denied. + with contextlib.suppress(OSError): + if path.is_dir(): + return None + raise + return prototype.buffer.from_bytes(data) if sys.platform == "win32": @@ -143,6 +159,18 @@ def _ensure_root(root: Path, *, create: bool) -> None: raise FileNotFoundError(f"{root} does not exist") +def _check_batch_root(root: Path, *, require_root: bool) -> None: + """Only an unopened writable store may have a missing root.""" + try: + mode = root.stat().st_mode + except FileNotFoundError: + if require_root: + raise + return + if not stat.S_ISDIR(mode): + raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), root) + + def _clear(root: Path) -> None: shutil.rmtree(root) root.mkdir() @@ -319,11 +347,7 @@ def get_sync( if prototype is None: prototype = default_buffer_prototype() self._ensure_open_sync() - path = self.root / key - try: - return _get(path, prototype, byte_range) - except (FileNotFoundError, IsADirectoryError, NotADirectoryError): - return None + return _get(self.root / key, prototype, byte_range) def set_sync(self, key: str, value: Buffer) -> None: self._ensure_open_sync() @@ -351,12 +375,7 @@ async def get( if prototype is None: prototype = default_buffer_prototype() await self._ensure_open() - path = self.root / key - - try: - return await asyncio.to_thread(_get, path, prototype, byte_range) - except (FileNotFoundError, IsADirectoryError, NotADirectoryError): - return None + return await asyncio.to_thread(_get, self.root / key, prototype, byte_range) async def get_partial_values( self, @@ -364,11 +383,18 @@ async def get_partial_values( key_ranges: Iterable[tuple[str, ByteRequest | None]], ) -> list[Buffer | None]: # docstring inherited - args = [] - for key, byte_range in key_ranges: - path = self.root / key - args.append((_get, path, prototype, byte_range)) - return await concurrent_map(args, asyncio.to_thread, limit=None) # TODO: fix limit + # Consume the iterable before scheduling reads in case it raises partway through. + root = self.root + require_root = self._is_open or self.read_only + args = [(_get, root / key, prototype, byte_range) for key, byte_range in key_ranges] + values: list[Buffer | None] = await concurrent_map( + args, + asyncio.to_thread, + limit=None, # TODO: fix limit + ) + if any(value is None for value in values): + await asyncio.to_thread(_check_batch_root, root, require_root=require_root) + return values async def set(self, key: str, value: Buffer) -> None: # docstring inherited diff --git a/tests/test_store/test_local.py b/tests/test_store/test_local.py index 8e7cc5279a..df3ca118ef 100644 --- a/tests/test_store/test_local.py +++ b/tests/test_store/test_local.py @@ -6,9 +6,11 @@ import os import pathlib import re +import sys import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any +from unittest.mock import AsyncMock import numpy as np import pytest @@ -16,6 +18,7 @@ import zarr import zarr.storage._local from zarr import create_array +from zarr.abc.store import RangeByteRequest from zarr.core.buffer import Buffer, cpu from zarr.storage import LocalStore from zarr.storage._local import _RETRY_DELAYS, _atomic_write, _move_with_retry @@ -24,6 +27,9 @@ if TYPE_CHECKING: from collections.abc import AsyncIterator, Awaitable, Callable, Iterator + from typing import Self + + from zarr.core.common import BytesLike _LOCAL_STORE_FILE = zarr.storage._local.__file__ _ASYNC_CODE_FLAGS = inspect.CO_COROUTINE | inspect.CO_ASYNC_GENERATOR @@ -199,6 +205,137 @@ async def test_filesystem_calls_are_observed( await ops[method]() assert helper in {function for function, _ in filesystem_calls.off_loop} + async def test_get_partial_values_with_missing_key(self, store: LocalStore) -> None: + await store.set("chunk", self.buffer_cls.from_bytes(b"NAME")) + values = await store.get_partial_values( + cpu.buffer_prototype, + [ + ("chunk", RangeByteRequest(0, 2)), + ("missing", None), + ("chunk", RangeByteRequest(2, 4)), + ], + ) + assert [v.to_bytes() if v is not None else None for v in values] == [b"NA", None, b"ME"] + + @pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 7)]) + async def test_get_partial_values_propagates_buffer_error( + self, store: LocalStore, byte_range: RangeByteRequest | None + ) -> None: + class FileBackedBuffer(cpu.Buffer): + @classmethod + def from_bytes(cls, bytes_like: BytesLike) -> Self: + path = store.root / bytes(bytes_like).decode("ascii") + return super().from_bytes(path.read_bytes()) + + await store.set("chunk", self.buffer_cls.from_bytes(b"backing")) + prototype = cpu.buffer_prototype._replace(buffer=FileBackedBuffer) + with pytest.raises(FileNotFoundError) as exc: + await store.get_partial_values(prototype, [("chunk", byte_range)]) + assert exc.value.filename == str(store.root / "backing") + + async def test_get_partial_values_leaves_missing_root_absent( + self, tmp_path: pathlib.Path + ) -> None: + root = tmp_path / "store" + store = LocalStore(root) + assert await store.get_partial_values(cpu.buffer_prototype, [("missing", None)]) == [None] + assert not root.exists() + + async def test_get_partial_values_missing_read_only_root(self, tmp_path: pathlib.Path) -> None: + root = tmp_path / "store" + store = LocalStore(root, read_only=True) + with pytest.raises(FileNotFoundError) as exc: + await store.get_partial_values(cpu.buffer_prototype, [("chunk", None)]) + assert exc.value.filename == str(root) + assert not root.exists() + + @pytest.mark.parametrize("read_only", [False, True], ids=["writable", "read-only"]) + async def test_get_partial_values_renamed_open_root( + self, tmp_path: pathlib.Path, read_only: bool + ) -> None: + root = tmp_path / "store" + root.mkdir() + (root / "chunk").write_bytes(b"data") + store = await LocalStore.open(root, read_only=read_only) + keys = [("chunk", None), ("missing", None)] + chunk, missing = await store.get_partial_values(cpu.buffer_prototype, keys) + assert chunk is not None + assert chunk.to_bytes() == b"data" + assert missing is None + + root.rename(tmp_path / "moved") + with pytest.raises(FileNotFoundError) as exc: + await store.get_partial_values(cpu.buffer_prototype, keys) + assert exc.value.filename == str(root) + + async def test_get_partial_values_replaced_root(self, tmp_path: pathlib.Path) -> None: + root = tmp_path / "store" + store = await LocalStore.open(root) + root.rename(tmp_path / "original") + root.write_bytes(b"not a directory") + + with pytest.raises(NotADirectoryError): + await store.get_partial_values( + cpu.buffer_prototype, [("first", None), ("second", None)] + ) + + async def test_get_partial_values_file_as_key_prefix(self, store: LocalStore) -> None: + await store.set("prefix", self.buffer_cls.from_bytes(b"data")) + child, value = await store.get_partial_values( + cpu.buffer_prototype, [("prefix/child", None), ("prefix", None)] + ) + assert child is None + assert value is not None + assert value.to_bytes() == b"data" + + async def test_get_partial_values_propagates_permission_error( + self, store: LocalStore, monkeypatch: pytest.MonkeyPatch + ) -> None: + await store.set("key", self.buffer_cls.from_bytes(b"private")) + + def deny_read(path: pathlib.Path) -> bytes: + raise PermissionError(path) + + monkeypatch.setattr(pathlib.Path, "read_bytes", deny_read) + with pytest.raises(PermissionError): + await store.get_partial_values(cpu.buffer_prototype, [("key", None)]) + + async def test_get_partial_values_directory_and_child( + self, store: LocalStore, monkeypatch: pytest.MonkeyPatch + ) -> None: + await store.set("group/chunk", self.buffer_cls.from_bytes(b"data")) + if sys.platform != "win32": + # Windows denies opening directories for reading. Exercise that error on POSIX too. + read_bytes = pathlib.Path.read_bytes + + def windows_read_bytes(path: pathlib.Path) -> bytes: + if path == store.root / "group": + raise PermissionError(path) + return read_bytes(path) + + monkeypatch.setattr(pathlib.Path, "read_bytes", windows_read_bytes) + + directory, child = await store.get_partial_values( + cpu.buffer_prototype, [("group", None), ("group/chunk", None)] + ) + assert directory is None + assert child is not None + assert child.to_bytes() == b"data" + + async def test_get_partial_values_invalid_iterable_schedules_no_reads( + self, store: LocalStore, monkeypatch: pytest.MonkeyPatch + ) -> None: + def key_ranges() -> Iterator[tuple[str, None]]: + yield "first", None + raise ValueError("invalid range sequence") + + to_thread = AsyncMock() + monkeypatch.setattr(asyncio, "to_thread", to_thread) + with pytest.raises(ValueError, match="invalid range sequence"): + await store.get_partial_values(cpu.buffer_prototype, key_ranges()) + await asyncio.sleep(0) # Give any abandoned tasks a chance to start. + to_thread.assert_not_called() + async def test_concurrent_lazy_open(self, store_not_open: LocalStore) -> None: """Concurrent first calls on an unopened store all succeed.