diff --git a/src/uproot/_dask.py b/src/uproot/_dask.py index de56f86e1..a5690cd8e 100644 --- a/src/uproot/_dask.py +++ b/src/uproot/_dask.py @@ -638,6 +638,11 @@ def _branch_or_field_numpy_dtype(branch): else: raise KeyError(f"field {p!r} not found in form {form!r}") return _form_to_numpy_dtype(form, initial_sizes=sizes) + elif isinstance(branch.interpretation, uproot.interpretation.grouped.AsGrouped): + raise NotImplementedError( + f"uproot.dask with library='np' cannot read the grouped TBranch " + f"{branch.name!r}: select its sub-branches or use library='ak'" + ) else: return branch.interpretation.numpy_dtype @@ -782,6 +787,8 @@ def _get_dask_array( total_entries = sum(ttree.num_entries for ttree in ttrees) step_size = max(1, math.ceil(total_entries / (total_files * steps_per_file))) + common_keys = _normalize_grouped_keys(ttrees[0], common_keys, full_paths) + dask_dict = {} step_sum = 0 @@ -891,6 +898,7 @@ def _get_dask_array_delay_open( ) if isinstance(obj, HasFields): common_keys = _with_subfield_keys(obj, common_keys) + common_keys = _normalize_grouped_keys(obj, common_keys, full_paths) dask_dict = {} diff --git a/src/uproot/behaviors/TBranch.py b/src/uproot/behaviors/TBranch.py index 6dd9c0485..96cb312a5 100644 --- a/src/uproot/behaviors/TBranch.py +++ b/src/uproot/behaviors/TBranch.py @@ -3633,6 +3633,9 @@ def _regularize_expressions( None, ) + else: + raise TypeError(f"cut must be None or a string, not {cut!r}") + return arrays, expression_context, branchid_interpretation @@ -3783,7 +3786,9 @@ def basket_to_array(basket): return # Request all chunks and then poll notifications queue until we have all the arrays we expect - hasbranches._file.source.chunks(ranges, notifications=notifications) + # (a step within baskets that have already been read has nothing to request) + if len(ranges) != 0: + hasbranches._file.source.chunks(ranges, notifications=notifications) while len(arrays) < len(branchid_interpretation): obj = notifications.get() diff --git a/src/uproot/compression.py b/src/uproot/compression.py index c007e056c..944e609a2 100644 --- a/src/uproot/compression.py +++ b/src/uproot/compression.py @@ -107,7 +107,7 @@ def decompress(self, data: bytes, uncompressed_bytes=None) -> bytes: elif self.library == "deflate": deflate = uproot.extras.deflate() - return deflate.zlib_decompress(data, bufsize=uncompressed_bytes) + return deflate.zlib_decompress(data, uncompressed_bytes) else: raise ValueError( diff --git a/src/uproot/reading.py b/src/uproot/reading.py index 0025bb8b1..2f1af026f 100644 --- a/src/uproot/reading.py +++ b/src/uproot/reading.py @@ -881,6 +881,7 @@ def streamers(self): if self._streamers is None: if self._fSeekInfo == 0: self._streamers = {} + self._streamer_rules = [] else: key_cursor = uproot.source.cursor.Cursor(self._fSeekInfo) @@ -1034,7 +1035,7 @@ def streamer_dependencies(self, classname, version="max"): if x not in out: for i in range(-1, -len(out) - 1, -1): if out[i][0] == x[0]: - out.insert(i + 1, x) + out.insert(len(out) + i + 1, x) break else: out.append(x) @@ -2111,7 +2112,13 @@ def __getitem__(self, where): head, tail = item[:index], item[index + 1 :] last = step step = step[head] - if isinstance(step, uproot.behaviors.TBranch.HasBranches): + if isinstance( + step, + ( + uproot.behaviors.TBranch.HasBranches, + uproot.behaviors.RNTuple.HasFields, + ), + ): return step["/".join([tail, *items[i + 1 :]])] else: raise uproot.KeyInFileError( diff --git a/src/uproot/source/futures.py b/src/uproot/source/futures.py index 5e49246fd..4f14944ab 100644 --- a/src/uproot/source/futures.py +++ b/src/uproot/source/futures.py @@ -465,6 +465,13 @@ def close(self): """ self.__exit__(None, None, None) + @property + def num_workers(self) -> int: + """ + Always 0: tasks run in the thread that submits them. + """ + return 0 + @property def closed(self) -> bool: """ diff --git a/src/uproot/source/http.py b/src/uproot/source/http.py index 9372c3648..75fc56f7a 100644 --- a/src/uproot/source/http.py +++ b/src/uproot/source/http.py @@ -100,6 +100,7 @@ def get_num_bytes(file_path: str, parsed_url: urllib.parse.ParseResult, timeout) response = connection.getresponse() while 300 <= response.status < 400: + response.close() connection.close() for k, x in response.getheaders(): if k.lower() == "location": @@ -117,10 +118,12 @@ def get_num_bytes(file_path: str, parsed_url: urllib.parse.ParseResult, timeout) ) if response.status == 404: + response.close() connection.close() raise uproot._util._file_not_found(file_path, "HTTP(S) returned 404") if response.status != 200: + response.close() connection.close() raise http.client.HTTPException( f"""HTTP response was {response.status}, rather than 200, in attempt to get file size @@ -129,9 +132,11 @@ def get_num_bytes(file_path: str, parsed_url: urllib.parse.ParseResult, timeout) for k, x in response.getheaders(): if k.lower() == "content-length" and x.strip() != "0": + response.close() connection.close() return int(x) else: + response.close() connection.close() raise http.client.HTTPException( f"""response headers did not include content-length: {dict(response.getheaders())} @@ -197,10 +202,12 @@ def get(self, connection, start: int, stop: int) -> bytes: response = connection.getresponse() if response.status == 404: + response.close() connection.close() raise uproot._util._file_not_found(self.file_path, "HTTP(S) returned 404") if 300 <= response.status < 400: + response.close() connection.close() for k, x in response.getheaders(): if k.lower() == "location": @@ -221,6 +228,7 @@ def get(self, connection, start: int, stop: int) -> bytes: ) if response.status != 206: + response.close() connection.close() raise http.client.HTTPException( f"""remote server responded with status {response.status}, rather than 206 (range requests) @@ -324,6 +332,7 @@ def task(resource): def task(resource): nonlocal connection + response = None try: response = connection.getresponse() @@ -364,6 +373,8 @@ def task(resource): future._set_excinfo(err) finally: + if response is not None: + response.close() connection.close() return uproot.source.futures.ResourceFuture(task) @@ -565,7 +576,13 @@ def readline(self) -> bytes: try: index = self.already_read.index(b"\n") except ValueError: - self.already_read = self.already_read + self.stream.read(self.CHUNK) + data = self.stream.read(self.CHUNK) + if len(data) == 0: + # End of stream: there's no newline to wait for. + out = self.already_read + self.already_read = b"" + return out + self.already_read = self.already_read + data else: out = self.already_read[: index + 1] self.already_read = self.already_read[index + 1 :] @@ -662,6 +679,9 @@ def chunks( ranges: list[tuple[int, int]], notifications: queue.Queue, ) -> list[uproot.source.chunk.Chunk]: + if len(ranges) == 0: + # nothing to request (and a Range header needs at least one range) + return [] if self._fallback is None: self._num_requests += 1 self._num_requested_chunks += len(ranges) diff --git a/src/uproot/source/xrootd.py b/src/uproot/source/xrootd.py index c27dbf239..7ca902181 100644 --- a/src/uproot/source/xrootd.py +++ b/src/uproot/source/xrootd.py @@ -330,6 +330,9 @@ def chunk(self, start: int, stop: int) -> uproot.source.chunk.Chunk: def chunks( self, ranges: list[tuple[int, int]], notifications: queue.Queue ) -> list[uproot.source.chunk.Chunk]: + if len(ranges) == 0: + # nothing to request: don't send an empty vector read + return [] self._num_requests += 1 self._num_requested_chunks += len(ranges) self._num_requested_bytes += sum(stop - start for start, stop in ranges) diff --git a/tests/test_1189_dask_failing_on_duplicate_keys.py b/tests/test_1189_dask_failing_on_duplicate_keys.py index 3f73b4dda..40cbfd4a3 100644 --- a/tests/test_1189_dask_failing_on_duplicate_keys.py +++ b/tests/test_1189_dask_failing_on_duplicate_keys.py @@ -1,5 +1,6 @@ # BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +import awkward as ak import pytest import skhep_testdata @@ -9,17 +10,31 @@ pytest.importorskip("dask_awkward") -def test_dask_duplicated_keys(): - - lazy = uproot.dask( - skhep_testdata.data_path("uproot-metadata-performance.root") + ":Events" - ) - materialized = lazy.FatJet_btagDDBvLV2.compute() - - lazy = uproot.dask(skhep_testdata.data_path("uproot-issue513.root") + ":Delphes") - materialized = lazy.Particle.compute() - - lazy = uproot.dask( - skhep_testdata.data_path("uproot-issue443.root") + ":muonDataTree" - ) - materialized = lazy.hitEnd.compute() +# uproot.dask only tokenizes the open TTrees of open_files=True, which is too slow with the +# 1833 TBranches of the first file, and it's the same code as for the last one +@pytest.mark.parametrize( + ("file", "tree", "branch", "open_files"), + [ + ("uproot-metadata-performance.root", "Events", "FatJet_btagDDBvLV2", False), + ("uproot-issue513.root", "Delphes", "Particle", False), + ("uproot-issue443.root", "muonDataTree", "hitEnd", False), + ("uproot-issue443.root", "muonDataTree", "hitEnd", True), + ], +) +def test_dask_duplicated_keys(file, tree, branch, open_files): + path = skhep_testdata.data_path(file) + with uproot.open(path) as f: + assert f[tree].keys(filter_name=branch) == [branch, branch] + expected = f[tree][branch].array() + + lazy = uproot.dask(f"{path}:{tree}", filter_name=branch, open_files=open_files) + assert lazy.fields == [branch] + materialized = lazy[branch].compute(scheduler="synchronous") + assert ak.array_equal(materialized, expected) + + +@pytest.mark.parametrize("library", ["ak", "np"]) +def test_dask_duplicated_keys_all_branches(library): + path = skhep_testdata.data_path("uproot-issue443.root") + ":muonDataTree" + lazy = uproot.dask(path, library=library) + assert lazy["hitEnd"].compute(scheduler="synchronous").tolist() == [] diff --git a/tests/test_1642_read_AsGrouped_with_dask_or_virtual_array.py b/tests/test_1642_read_AsGrouped_with_dask_or_virtual_array.py index c6ee4565c..e1101bf4e 100644 --- a/tests/test_1642_read_AsGrouped_with_dask_or_virtual_array.py +++ b/tests/test_1642_read_AsGrouped_with_dask_or_virtual_array.py @@ -22,5 +22,34 @@ def test_read_AsGrouped_with_dask_or_virtual_array(): assert awkward.array_equal(arr, awkward.materialize(virtual_arr)) + assert arr.value.tolist() == list(range(10)) + dask_arr = uproot.dask(path).compute() assert awkward.array_equal(arr, dask_arr) + + +@pytest.mark.parametrize("open_files", [True, False]) +@pytest.mark.parametrize( + ("full_paths", "value"), [(False, "value"), (True, "branch/value")] +) +def test_read_AsGrouped_with_dask_numpy(open_files, full_paths, value): + """ + As in an eager read of all of a TTree, a group of TBranches that are also + selected is left out: it has no NumPy dtype. + """ + path = skhep_testdata.data_path("uproot-issue-1502.root") + lazy = uproot.dask(path, library="np", open_files=open_files, full_paths=full_paths) + assert len(lazy) == 3 + assert value in lazy + computed = dask.compute(lazy, scheduler="synchronous")[0] + assert computed[value].tolist() == list(range(10)) + + +@pytest.mark.parametrize("open_files", [True, False]) +@pytest.mark.parametrize("names", ["branch", ["branch", "value"]]) +def test_AsGrouped_alone_cannot_be_a_dask_array(open_files, names): + path = skhep_testdata.data_path("uproot-issue-1502.root") + with pytest.raises( + NotImplementedError, match="cannot read the grouped TBranch 'branch'" + ): + uproot.dask(path, filter_name=names, library="np", open_files=open_files) diff --git a/tests/test_1825_fix_reading.py b/tests/test_1825_fix_reading.py new file mode 100644 index 000000000..842819443 --- /dev/null +++ b/tests/test_1825_fix_reading.py @@ -0,0 +1,555 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import contextlib +import gc +import http.client +import http.server +import queue +import re +import shutil +import struct +import threading +import zlib + +import numpy as np +import numpy +import pytest +import skhep_testdata + +import uproot +import uproot.compression +import uproot.reading +import uproot.source.xrootd +from uproot.compression import ZLIB +from uproot.reading import ReadOnlyFile +from uproot.source.http import _ResponseBuffer, HTTPSource, MultithreadedHTTPSource +from uproot.source.xrootd import XRootDSource + +ak = pytest.importorskip("awkward") + + +@pytest.fixture +def two_files(tmp_path): + """``a.root`` has ``x`` (0 to 9) and ``y`` (10 times ``x``); ``b.root`` has only ``x`` + (10 to 14).""" + a, b = str(tmp_path / "a.root"), str(tmp_path / "b.root") + with uproot.recreate(a) as file: + x = np.arange(10, dtype=np.int64) + file.mktree("t", {"x": "int64", "y": "int64"}).extend({"x": x, "y": x * 10}) + with uproot.recreate(b) as file: + x = np.arange(10, 15, dtype=np.int64) + file.mktree("t", {"x": "int64"}).extend({"x": x}) + return a, b + + +@pytest.mark.parametrize("function", ["arrays", "iterate", "concatenate"]) +@pytest.mark.parametrize("cut", [5, ["x > 1"], b"x > 1"]) +def test_cut_of_the_wrong_type_is_an_error(two_files, function, cut): + a, _ = two_files + with ( + uproot.open(a) as file, + pytest.raises(TypeError, match="cut must be None or a string"), + ): + if function == "arrays": + file["t"].arrays(["x"], cut=cut) + elif function == "iterate": + list(file["t"].iterate(["x"], cut=cut)) + else: + uproot.concatenate({a: "t"}, ["x"], cut=cut) + + +DATA = b"uproot compression test " * 200 + + +def source(): + out = uproot.source.chunk.Source() + out._file_path = "test.root" + return out + + +def decompress(block, uncompressed_bytes): + chunk = uproot.source.chunk.Chunk.wrap( + source(), numpy.frombuffer(block, dtype=numpy.uint8) + ) + cursor = uproot.source.cursor.Cursor(0) + out = uproot.compression.decompress( + chunk, cursor, {}, len(block), uncompressed_bytes + ) + return out.raw_data.tobytes() + + +@pytest.mark.parametrize("library, module", [("isal", "isal"), ("deflate", "deflate")]) +def test_zlib_alternative_libraries(library, module, monkeypatch): + pytest.importorskip(module) + # reading uses a _DecompressZLIB, and ZLIB objects look at ZLIB, where a test + # that sets uproot.ZLIB.library directly leaves its value + monkeypatch.setattr(uproot.compression._DecompressZLIB, "library", library) + monkeypatch.setattr(ZLIB, "library", library) + + # what the library compresses, the standard library decompresses + assert zlib.decompress(ZLIB(6).compress(DATA)) == DATA + + # and the other way around + assert ZLIB(6).decompress(zlib.compress(DATA), len(DATA)) == DATA + + with pytest.raises(ValueError, match=f'ZLIB.library="{library}"'): + ZLIB(0).compress(DATA) + + +@pytest.mark.parametrize("library, module", [("isal", "isal"), ("deflate", "deflate")]) +def test_zlib_alternative_libraries_read_root_file(library, module, monkeypatch): + pytest.importorskip(module) + path = skhep_testdata.data_path("uproot-Zmumu-zlib.root") + expected = uproot.open(path)["events/px1"].array(library="np") + assert len(expected) == 2304 + assert expected[:3].tolist() == pytest.approx( + [-41.1952876442, 35.1180497674, 35.1180497674] + ) + + # reading uses a _DecompressZLIB, and ZLIB objects look at ZLIB, where a test + # that sets uproot.ZLIB.library directly leaves its value + monkeypatch.setattr(uproot.compression._DecompressZLIB, "library", library) + monkeypatch.setattr(ZLIB, "library", library) + actual = uproot.open(path)["events/px1"].array(library="np") + assert numpy.array_equal(actual, expected) + + +def test_multithreaded_source_repr_without_threads(): + path = skhep_testdata.data_path("uproot-Zmumu.root") + with uproot.source.file.MultithreadedFileSource( + path, num_workers=2, use_threads=False + ) as source: + assert source.num_workers == 0 + assert repr(source).startswith( + "4siiiiiiiBiiiH16s") + + +def path_of(filename): + return skhep_testdata.data_path(filename) + + +def zero_seek_info(tmp_path): + source = path_of(ZMUMU) + with open(source, "rb") as file: + data = bytearray(file.read()) + data[HEADER.size - 2 - 16 - 8 : HEADER.size - 2 - 16 - 4] = b"\x00\x00\x00\x00" + out = tmp_path / "no-streamers.root" + out.write_bytes(data) + return out + + +def test_file_without_streamers(tmp_path): + with ReadOnlyFile(zero_seek_info(tmp_path)) as file: + assert file.fSeekInfo == 0 + assert file.streamers == {} + assert file.streamer_rules == [] + + +@pytest.fixture(scope="module") +def versions_file(tmp_path_factory): + """A file with TObject in its streamers, which everything depends on.""" + path = tmp_path_factory.mktemp("reading") / "versions.root" + with uproot.recreate(path) as file: + file["hist"] = numpy.histogram([1, 2, 3]) + return path + + +class Streamer: + """A stand-in for a TStreamerInfo with given dependencies.""" + + def __init__(self, name, class_version, dependencies=()): + self.name = name + self.class_version = class_version + self.dependencies = dependencies + + def _dependencies(self, streamers, out): + out.append((self.name, self.class_version)) + out.extend(self.dependencies) + + +def test_streamer_dependencies_of_all_versions(versions_file): + with ReadOnlyFile(versions_file) as file: + file._streamers = { + "A": { + 2: Streamer("A", 2, [("B", 2), ("C", 1)]), + 1: Streamer("A", 1, [("B", 1), ("C", 1)]), + }, + } + # newest first, versions of one class together, nothing repeated + assert file.streamer_dependencies("A", version="all") == [ + ("C", 1), + ("B", 2), + ("B", 1), + ("A", 2), + ("A", 1), + ] + + +@pytest.fixture(scope="module") +def nested_file(tmp_path_factory): + """Directories inside directories, one object with two cycles, and a TTree.""" + path = tmp_path_factory.mktemp("reading") / "nested.root" + with uproot.recreate(path) as file: + file["top"] = "top string" + file["a/hist"] = numpy.histogram([1, 2, 3]) + file["a/b/hist"] = numpy.histogram([1, 2, 3]) + file["a/b/twice"] = numpy.histogram([1, 2, 3]) + file["a/b/twice"] = numpy.histogram([4, 5, 6]) + tree = file.mktree("tree", {"x": "i8"}, title="the title") + tree.extend({"x": numpy.array([1, 2, 3])}) + file.mkrntuple("ntuple", {"x": numpy.array([1, 2, 3])}) + return path + + +@pytest.mark.parametrize("where", ["tree:x", "ntuple:x"]) +def test_getitem_descends_with_colon(nested_file, where): + with uproot.open(nested_file) as directory: + assert directory[where].array().tolist() == [1, 2, 3]