From 758e88ecb1189c54b20c7235a63caa574c581dea Mon Sep 17 00:00:00 2001 From: Bhaskar Gurram Date: Sat, 31 Oct 2026 18:03:56 +0000 Subject: [PATCH] Pass target_options when MultiZarrToZarr reads reference files from paths When the inputs are paths to JSON reference files, the batch read used a filesystem created with asynchronous=True and called its blocking cat(), which fails with "Loop is not running" for http/s3/gcs paths. It also ignored the compression given in target_options, and decoded the files in the sorted order returned by cat() rather than the order of the inputs, so INDEX, list and filename-based coo_map selectors could be paired with the wrong dataset. Read the files through the filesystem of the OpenFiles, decompress with the compression of each OpenFile, keep the input order, and pass target_options to ReferenceFileSystem when falling back to opening each path. Fixes #522 --- kerchunk/combine.py | 30 +++++++++++------- tests/test_combine.py | 73 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 11 deletions(-) diff --git a/kerchunk/combine.py b/kerchunk/combine.py index 0a52383b..5ad99e68 100644 --- a/kerchunk/combine.py +++ b/kerchunk/combine.py @@ -1,11 +1,13 @@ import asyncio import collections.abc +import io import logging import re from typing import List import warnings import fsspec +import fsspec.compression import fsspec.utils import numpy as np import numcodecs @@ -18,6 +20,14 @@ logger = logging.getLogger("kerchunk.combine") +def _load_json(data, compression=None): + """Decode JSON references from raw bytes, decompressing them first if needed""" + if compression: + with fsspec.compression.compr[compression](io.BytesIO(data), mode="rb") as f: + data = f.read() + return ujson.loads(data) + + def drop(fields): """Generate example preprocessor removing given fields""" @@ -271,24 +281,22 @@ def fss(self): for path in self.path: self._paths.append(path.get("templates", {}).get("u", None)) else: - self._paths = [] - for of in fsspec.open_files(self.path, **self.target_options): - self._paths.append(of.full_name) - fs = fsspec.core.url_to_fs( - self.path[0], asynchronous=True, **self.target_options - )[0] + ofs = fsspec.open_files(self.path, **self.target_options) + self._paths = [of.full_name for of in ofs] try: - # JSON path - fo_list = fs.cat(self.path) - fo_list = [ujson.loads(v) for v in fo_list.values()] - except (IOError, TypeError, ValueError): + # JSON path: fetch all reference files in one batch and + # decode them in the same order as the inputs + raw = ofs.fs.cat([of.path for of in ofs]) + fo_list = [_load_json(raw[of.path], of.compression) for of in ofs] + except (IOError, KeyError, TypeError, ValueError): # tries again sequentially in comprehension below - fo_list = self.path + fo_list = self._paths self._fss = [ fsspec.filesystem( "reference", fo=fo, + target_options=self.target_options if isinstance(fo, str) else None, remote_protocol=self.remote_protocol, remote_options=self.remote_options, ) diff --git a/tests/test_combine.py b/tests/test_combine.py index 75821395..e712454e 100644 --- a/tests/test_combine.py +++ b/tests/test_combine.py @@ -3,6 +3,7 @@ import numpy as np import dask.array as da import pytest +import ujson import xarray as xr import zarr.storage @@ -862,3 +863,75 @@ def test_chunk_error(refs): with pytest.raises(ValueError) as e: mzz.translate() assert "chunk size mismatch" in str(e.value) + + +def _write_refs(path, refs, compression=None): + with fsspec.open(str(path), "wt", compression=compression) as f: + f.write(ujson.dumps(refs)) + + +@pytest.mark.parametrize("compression", [None, "gzip"]) +def test_paths_target_options(refs, tmp_path, compression): + paths = [] + for name in ["single1", "single2"]: + path = tmp_path / f"{name}.json" + _write_refs(path, refs[name], compression=compression) + paths.append(str(path)) + mzz = MultiZarrToZarr( + paths, + target_options={"compression": compression}, + remote_protocol="memory", + concat_dims=["time"], + ) + out = mzz.translate() + assert out["refs"]["data/0.0.0"] == ["memory:///single1.zarr/data/0.0.0"] + assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"] + + +def test_paths_keep_input_order(refs, tmp_path): + # the file names sort the other way round from the order of the inputs + _write_refs(tmp_path / "b.json", refs["single1"]) + _write_refs(tmp_path / "a.json", refs["single2"]) + mzz = MultiZarrToZarr( + [str(tmp_path / "b.json"), str(tmp_path / "a.json")], + remote_protocol="memory", + concat_dims=["time"], + coo_map={"time": "INDEX"}, + ) + out = mzz.translate() + assert out["refs"]["data/0.0.0"] == ["memory:///single1.zarr/data/0.0.0"] + assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"] + + +@pytest.fixture +def http_dir(tmp_path): + pytest.importorskip("aiohttp") + import functools + import http.server + import threading + + class Handler(http.server.SimpleHTTPRequestHandler): + def log_message(self, *args): + pass + + handler = functools.partial(Handler, directory=str(tmp_path)) + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield tmp_path, f"http://127.0.0.1:{server.server_address[1]}" + server.shutdown() + server.server_close() + + +def test_paths_async_filesystem(refs, http_dir): + root, url = http_dir + for name in ["single1", "single2"]: + _write_refs(root / f"{name}.json", refs[name]) + mzz = MultiZarrToZarr( + [f"{url}/single1.json", f"{url}/single2.json"], + remote_protocol="memory", + concat_dims=["time"], + ) + out = mzz.translate() + assert out["refs"]["data/0.0.0"] == ["memory:///single1.zarr/data/0.0.0"] + assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"]