Skip to content

Multiprocessing support #2815

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

Merged
merged 6 commits into from
Feb 11, 2025
Merged
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
21 changes: 21 additions & 0 deletions src/zarr/core/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import atexit
import logging
import os
import threading
from concurrent.futures import ThreadPoolExecutor, wait
from typing import TYPE_CHECKING, TypeVar
Expand Down Expand Up @@ -89,6 +90,26 @@ def cleanup_resources() -> None:
atexit.register(cleanup_resources)


def reset_resources_after_fork() -> None:
"""
Ensure that global resources are reset after a fork. Without this function,
forked processes will retain invalid references to the parent process's resources.
"""
global loop, iothread, _executor
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strictly speaking, loop and iothread don't need to be global, since they are mutated in-place.

# These lines are excluded from coverage because this function only runs in a child process,
# which is not observed by the test coverage instrumentation. Despite the apparent lack of
# test coverage, this function should be adequately tested by any test that uses Zarr IO with
# multiprocessing.
loop[0] = None # pragma: no cover
iothread[0] = None # pragma: no cover
_executor = None # pragma: no cover


# this is only available on certain operating systems
if hasattr(os, "register_at_fork"):
os.register_at_fork(after_in_child=reset_resources_after_fork)


async def _runner(coro: Coroutine[Any, Any, T]) -> T | BaseException:
"""
Await a coroutine and return the result of running it. If awaiting the coroutine raises an
Expand Down
38 changes: 38 additions & 0 deletions tests/test_array.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import dataclasses
import json
import math
import multiprocessing as mp
import pickle
import re
import sys
from itertools import accumulate
from typing import TYPE_CHECKING, Any, Literal
from unittest import mock
Expand Down Expand Up @@ -1382,3 +1384,39 @@ def test_roundtrip_numcodecs() -> None:
metadata = root["test"].metadata.to_dict()
expected = (*filters, BYTES_CODEC, *compressors)
assert metadata["codecs"] == expected


def _index_array(arr: Array, index: Any) -> Any:
return arr[index]


@pytest.mark.parametrize(
"method",
[
pytest.param(
"fork",
marks=pytest.mark.skipif(
sys.platform in ("win32", "darwin"), reason="fork not supported on Windows or OSX"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because windows should only perform spawn? This decorator is a bit verbose, it would be OK to put if ... : pytest.skip() in the body of the function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I prefer (verbose) parametrization over checking the OS in the test itself. The former gives better feedback in the test summary.

),
),
"spawn",
pytest.param(
"forkserver",
marks=pytest.mark.skipif(
sys.platform == "win32", reason="forkserver not supported on Windows"
),
),
],
)
@pytest.mark.parametrize("store", ["local"], indirect=True)
def test_multiprocessing(store: Store, method: Literal["fork", "spawn", "forkserver"]) -> None:
"""
Test that arrays can be pickled and indexed in child processes
"""
data = np.arange(100)
arr = zarr.create_array(store=store, data=data)
ctx = mp.get_context(method)
pool = ctx.Pool()

results = pool.starmap(_index_array, [(arr, slice(len(data)))])
assert all(np.array_equal(r, data) for r in results)