Skip to content

Avoid memory copy in obstore write #2972

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions changes/2972.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Avoid an unnecessary memory copy when writing Zarr with obstore
13 changes: 13 additions & 0 deletions src/zarr/core/buffer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,19 @@ def as_numpy_array(self) -> npt.NDArray[Any]:
"""
...

def as_buffer_like(self) -> BytesLike:
"""Returns the buffer as an object that implements the Python buffer protocol.

Notes
-----
Might have to copy data, since the implementation uses `.as_numpy_array()`.

Returns
-------
An object that implements the Python buffer protocol
"""
return memoryview(self.as_numpy_array()) # type: ignore[arg-type]

def to_bytes(self) -> bytes:
"""Returns the buffer as `bytes` (host memory).

Expand Down
4 changes: 2 additions & 2 deletions src/zarr/storage/_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@
with path.open("r+b") as f:
f.seek(start)
# write takes any object supporting the buffer protocol
f.write(value.as_numpy_array()) # type: ignore[arg-type]
f.write(value.as_buffer_like())

Check warning on line 55 in src/zarr/storage/_local.py

View check run for this annotation

Codecov / codecov/patch

src/zarr/storage/_local.py#L55

Added line #L55 was not covered by tests
return None
else:
view = memoryview(value.as_numpy_array()) # type: ignore[arg-type]
view = value.as_buffer_like()
if exclusive:
mode = "xb"
else:
Expand Down
4 changes: 2 additions & 2 deletions src/zarr/storage/_obstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,15 +160,15 @@ async def set(self, key: str, value: Buffer) -> None:

self._check_writable()

buf = value.to_bytes()
buf = value.as_buffer_like()
await obs.put_async(self.store, key, buf)

async def set_if_not_exists(self, key: str, value: Buffer) -> None:
# docstring inherited
import obstore as obs

self._check_writable()
buf = value.to_bytes()
buf = value.as_buffer_like()
with contextlib.suppress(obs.exceptions.AlreadyExistsError):
await obs.put_async(self.store, key, buf, mode="create")

Expand Down