Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
17 changes: 17 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,22 @@
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.

loop[0] = None
iothread[0] = None
_executor = None

Check warning on line 101 in src/zarr/core/sync.py

View check run for this annotation

Codecov / codecov/patch

src/zarr/core/sync.py#L99-L101

Added lines #L99 - L101 were not covered by tests


# 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"]) -> 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)
Loading