From 335b74600caf4d62ae790a56c480fc1edd74eb1b Mon Sep 17 00:00:00 2001 From: Andres Rios Tascon Date: Thu, 5 Nov 2026 11:59:10 -0500 Subject: [PATCH 1/3] fix: correct errors found while testing RNTuple reading and writing These were found by the tests of #1814, which are the regression tests here. The fixes are to columns of narrower representations (zigzag, delta and truncated or quantized floats), GPU reads of uncompressed and multi-page columns, split columns of unsupported widths, unknown field roles, field paths, linked attribute sets, anchors past 2 GB, and writing empty and masked arrays. Assisted-by: Claude Code:claude-opus-5-5 --- src/uproot/behaviors/RNTuple.py | 13 +- src/uproot/models/RNTuple.py | 182 ++++--- src/uproot/writing/_cascadentuple.py | 22 +- tests-cuda/test_1828_cov_gpu_rntuple.py | 188 +++++++ tests/test_1828_fix_rntuple.py | 676 ++++++++++++++++++++++++ 5 files changed, 975 insertions(+), 106 deletions(-) create mode 100644 tests-cuda/test_1828_cov_gpu_rntuple.py create mode 100644 tests/test_1828_fix_rntuple.py diff --git a/src/uproot/behaviors/RNTuple.py b/src/uproot/behaviors/RNTuple.py index c6d69002e..f4339f1c2 100644 --- a/src/uproot/behaviors/RNTuple.py +++ b/src/uproot/behaviors/RNTuple.py @@ -213,14 +213,10 @@ def to_akform( # Also include the field itself keys = [self.path] + [f"{self.path}.{k}" for k in keys] if top_collection is None: - # The field needs to be in the keys or be a parent of a field in the keys - if any( - key.startswith(f"{self.path}.") or key == self.path for key in keys - ): - top_names.append(self.name) - record_list.append( - rntuple.field_form(self.field_id, keys, ak_add_doc=ak_add_doc) - ) + top_names.append(self.name) + record_list.append( + rntuple.field_form(self.field_id, keys, ak_add_doc=ak_add_doc) + ) else: keys += [top_collection.path] top_names.append(top_collection.name) @@ -689,6 +685,7 @@ def iterate( library=library, backend=backend, interpreter=interpreter, + ak_add_doc=ak_add_doc, how=how, filter_branch=filter_branch, ) diff --git a/src/uproot/models/RNTuple.py b/src/uproot/models/RNTuple.py index d08c5aadc..4d47f7865 100644 --- a/src/uproot/models/RNTuple.py +++ b/src/uproot/models/RNTuple.py @@ -216,7 +216,7 @@ def _sort_key(f): ancestor_stacks.append(tmp_stack) while all( - stack[-1] == ancestor_stacks[0][-1] for stack in ancestor_stacks[1:] + stack[-1] is ancestor_stacks[0][-1] for stack in ancestor_stacks[1:] ): for stack in ancestor_stacks: stack.pop() @@ -796,8 +796,8 @@ def _field_form(self, this_id, key_prefixes, ak_add_doc=False): f"Unsplit fields are not supported. {this_record}" ) else: - # everything should recurse above this branch - raise AssertionError("this should be unreachable") + # a role from a newer version of the format, or a corrupted file + raise NotImplementedError(f"Unknown field role: {this_record}") def read_page( self, @@ -820,18 +820,7 @@ def read_page( """ page_desc = self._ntuple.page_link_list[cluster_idx][col_idx].pages[page_idx] loc = page_desc.locator - num_elements = len(destination) - # Pages storing bits, real32trunc, and real32quant need num_elements - # corrected - if field_metadata.isbit: - num_elements_toread = int(numpy.ceil(num_elements / 8)) - elif field_metadata.dtype_str in ("real32trunc", "real32quant"): - num_elements_toread = int( - numpy.ceil((num_elements * 4 * field_metadata.nbits) / 32) - ) - else: - num_elements_toread = num_elements - + num_elements_toread = _page_num_toread(len(destination), field_metadata) uncomp_size = num_elements_toread * field_metadata.dtype_toread.itemsize decomp_chunk, cursor = self.read_locator(loc, uncomp_size) content = cursor.array( @@ -1009,28 +998,34 @@ def read_cluster_pages( return_buffer = False assert len(destination) == total_len + # The pages are decoded in the column's own dtype (zigzag and quantization + # depend on its width), and only then converted to the result's dtype, which + # is wider if the field has other column representations + if field_metadata.dtype == field_metadata.dtype_result: + column_buffer = destination + else: + column_buffer = numpy.empty(total_len, dtype=field_metadata.dtype) + tracker = 0 cumsum = 0 for page_idx, page_desc in enumerate(pagelist): n_elements = page_desc.num_elements tracker_end = tracker + n_elements self.read_page( - destination[tracker:tracker_end], + column_buffer[tracker:tracker_end], cluster_idx, col_idx, page_idx, field_metadata, ) - if field_metadata.dtype != field_metadata.dtype_result: - destination[tracker:tracker_end] = destination[ - tracker:tracker_end - ].view(field_metadata.dtype)[: tracker_end - tracker] if field_metadata.delta: - destination[tracker] -= cumsum - cumsum += numpy.sum(destination[tracker:tracker_end]) + column_buffer[tracker] -= cumsum + cumsum += numpy.sum(column_buffer[tracker:tracker_end]) tracker = tracker_end - self.post_process(destination, field_metadata) + self.post_process(column_buffer, field_metadata) + if column_buffer is not destination: + destination[:] = column_buffer # Save a copy in array_cache if array_cache is not None: @@ -1118,7 +1113,13 @@ def gpu_read_cluster_pages( compression = linklist_col.compression_settings compression_level = compression % 100 algorithm = compression // 100 - algorithm_str = compression_settings_dict[algorithm] + # like uproot.compression.Compression.from_code_pair, an algorithm or a + # level of 0 means that the pages are stored uncompressed + algorithm_str = ( + None + if algorithm == 0 or compression_level == 0 + else compression_settings_dict[algorithm] + ) else: pagelist = [] algorithm_str = None @@ -1128,37 +1129,33 @@ def gpu_read_cluster_pages( total_len = numpy.sum([desc.num_elements for desc in pagelist], dtype=int) full_output_buffer = cupy.empty(total_len, dtype=field_metadata.dtype) - # Check if field compressed/decompressed - if field_metadata.isbit: # Need to correct length when dtype = bit - total_len = int(numpy.ceil(total_len / 8)) - elif field_metadata.dtype_str in ("real32trunc", "real32quant"): - total_len = int(numpy.ceil((total_len * 4 * field_metadata.nbits) / 32)) - total_raw_bytes = numpy.sum([desc.locator.num_bytes for desc in pagelist]) - page_is_compressed = ( - total_raw_bytes != total_len * field_metadata.dtype_toread.itemsize - ) - cluster_contents = FieldPayload( col_idx_orig, full_output_buffer, - page_is_compressed, + False, algorithm_str, compression_level, ) tracker = 0 for page_desc in pagelist: - num_elements = page_desc.num_elements + # Like on the CPU (read_page), each page starts at its first element, + # its raw data fill the start of the page, and whether a page is + # compressed depends on its own size (ROOT doesn't compress a page + # that compression wouldn't make smaller) + tracker_end = tracker + page_desc.num_elements + page_bytes = ( + _page_num_toread(page_desc.num_elements, field_metadata) + * field_metadata.dtype_toread.itemsize + ) + out_buff = full_output_buffer[tracker:tracker_end].view(cupy.uint8)[ + :page_bytes + ] loc = page_desc.locator n_bytes = loc.num_bytes - if field_metadata.isbit: # Need to correct length when dtype = bit - num_elements = int(numpy.ceil(num_elements / 8)) - - tracker_end = tracker + num_elements - out_buff = full_output_buffer[tracker:tracker_end] - # If compressed, skip 9 byte header - if page_is_compressed: - # If LZ4, page contains additional 8-byte checksum + if algorithm_str is not None and n_bytes < page_bytes: + cluster_contents.page_is_compressed = True + # skip the 9 byte header; LZ4 has an additional 8-byte checksum header_size = 9 if algorithm_str != "LZ4" else 9 + 8 offset = int(loc.offset + header_size) read_size = int(n_bytes - header_size) @@ -1208,7 +1205,6 @@ def gpu_deserialize_decompressed_content( if start_cluster_idx >= 0 else 0 ) - cluster_range = range(start_cluster_idx, stop_cluster_idx) col_arrays = {} # collect content for each col for key_nr in clusters_datas.columns: @@ -1222,37 +1218,24 @@ def gpu_deserialize_decompressed_content( ) res = cupy.empty(total_length, field_metadata.dtype_result) - if len(starts) == 0: - # no clusters are read, so the array is only padding (and, for - # offsets, the leading zero) - res[:] = 0 - col_arrays[key_nr] = res - continue + # clusters_datas only has columns if it read a cluster in the + # range, so ``starts`` is never empty here res[: starts[0]] = 0 - # Get uncompressed array for key for each cluster, by cluster index + # Get uncompressed array for key for each cluster, by cluster index; + # ``starts`` only has entries for non-negative cluster indices (see + # _expected_array_length_starts_dtype), so start the pairing at 0 col_decompressed_buffers = clusters_datas._grab_field_output(ncol) - # ``starts`` only contains entries for non-negative cluster indices - # (see _expected_array_length_starts_dtype), so skip negative ones - # here to keep the pairing between ``starts[i]`` and the cluster - # index aligned. - i = 0 - for cluster_i in cluster_range: - if cluster_i < 0: - continue + cluster_range = range(max(start_cluster_idx, 0), stop_cluster_idx) + for i, cluster_i in enumerate(cluster_range): stop = starts[i + 1] if i + 1 < len(starts) else total_length cluster_buffer = col_decompressed_buffers[cluster_i] cluster_buffer = self.gpu_deserialize_pages( cluster_buffer, ncol, cluster_i, field_metadata ) - # if field_metadata.dtype != field_metadata.dtype_result: + # assigning converts the values of a narrower representation to + # dtype_result (the CPU path reads raw bytes and has to view them) res[starts[i] : stop] = cluster_buffer - if field_metadata.dtype != field_metadata.dtype_result: - res[starts[i] : stop] = res[starts[i] : stop].view( - field_metadata.dtype - )[: stop - starts[i]] - i += 1 - self.combine_cluster_arrays(res, starts, field_metadata) col_arrays[key_nr] = res @@ -1384,6 +1367,13 @@ def deserialize_page_decompressed_buffer(self, destination, field_metadata): res[5::8] = content[length * 5 // 8 : length * 6 // 8] res[6::8] = content[length * 6 // 8 : length * 7 // 8] res[7::8] = content[length * 7 // 8 : length * 8 // 8] + + else: + # the bit width of a column is in the file, apart from its type + raise ValueError( + f"split column {field_metadata.ncol} has {field_metadata.nbits} " + "bits, but split columns can only have 16, 32, or 64 bits" + ) destination.view(field_metadata.dtype)[:num_elements] = res.view( field_metadata.dtype ) @@ -1521,6 +1511,19 @@ def combine_cluster_arrays(self, array, starts, field_metadata): indices[mask] += offsets[cluster_ids[mask]] +def _page_num_toread(num_elements, field_metadata): + """ + Returns the number of items of ``field_metadata.dtype_toread`` that hold a page + of ``num_elements`` elements: bits and truncated or quantized floats are packed. + """ + if field_metadata.isbit: + return int(numpy.ceil(num_elements / 8)) + elif field_metadata.dtype_str in ("real32trunc", "real32quant"): + return int(numpy.ceil((num_elements * 4 * field_metadata.nbits) / 32)) + else: + return num_elements + + def _extract_bits(packed, nbits): """ Args: @@ -1670,10 +1673,13 @@ def __repr__(self): return f"MetaData({self.name!r}, {kwargs})" def __getattr__(self, name): - if not name.startswith("_"): - return self.__dict__["_fields"][name] - else: - return self.__dict__[name] + try: + if not name.startswith("_"): + return self.__dict__["_fields"][name] + else: + return self.__dict__[name] + except KeyError: + raise AttributeError(name) from None def __setattr__(self, name, val): self.__dict__["_fields"][name] = val @@ -1868,7 +1874,8 @@ def read(self, chunk, cursor, context): out.anchor_uncompressed_size, ) = cursor.fields(chunk, _rntuple_linked_attribute_set_format, context) out.locator = LocatorReader().read(chunk, cursor, context) - out.name = cursor.rntuple_string(chunk, context) + # not "name", which is the name of the MetaData itself + out.attribute_set_name = cursor.rntuple_string(chunk, context) return out @@ -2057,7 +2064,9 @@ def index(self): if field is self: return i else: - raise AssertionError + raise ValueError( + f"RField {self.name!r} is anonymous, so its parent does not list it" + ) @property def field_id(self): @@ -2249,16 +2258,29 @@ def _add_output(self, buffer: CupyArray): self.output.append(buffer) def _decompress(self): - if self.page_is_compressed and self.algorithm is not None: + pages, outputs = self._compressed_pages() + if pages: nvcomp = uproot.extras.nvcomp() cupy = uproot.extras.cupy() codec = nvcomp.Codec( algorithm=self.algorithm, bitstream_kind=nvcomp.BitstreamKind.RAW ) - batch_nv = nvcomp.as_arrays(self.pages) + batch_nv = nvcomp.as_arrays(pages) batch = codec.decode(batch_nv) - for i, _array in enumerate(batch): - self.output[i][:] = cupy.array(_array).view(self.output[i].dtype) + for output, _array in zip(outputs, batch, strict=True): + output[:] = cupy.array(_array).view(output.dtype) + + def _compressed_pages(self): + """ + Returns the compressed pages and their decompression targets (the pages + that are stored uncompressed were read directly into their targets). + """ + pairs = [ + (page, output) + for page, output in zip(self.pages, self.output, strict=True) + if page is not None + ] + return [page for page, _ in pairs], [output for _, output in pairs] @dataclasses.dataclass @@ -2313,9 +2335,9 @@ def _decompress(self): if fieldpayload.algorithm not in to_decompress.keys(): to_decompress[fieldpayload.algorithm] = [] target[fieldpayload.algorithm] = [] - if fieldpayload.page_is_compressed: - to_decompress[fieldpayload.algorithm].extend(fieldpayload.pages) - target[fieldpayload.algorithm].extend(fieldpayload.output) + pages, outputs = fieldpayload._compressed_pages() + to_decompress[fieldpayload.algorithm].extend(pages) + target[fieldpayload.algorithm].extend(outputs) # batch decompress nvcomp = uproot.extras.nvcomp() diff --git a/src/uproot/writing/_cascadentuple.py b/src/uproot/writing/_cascadentuple.py index 121d9ade3..6d510f3e2 100644 --- a/src/uproot/writing/_cascadentuple.py +++ b/src/uproot/writing/_cascadentuple.py @@ -329,11 +329,7 @@ def __init__(self, location, name, ntuple_description, akform): super().__init__(location, aloc) def __repr__(self): - return "{}({}, {})".format( - type(self).__name__, - self._location, - ", ".join([repr(x) for x in self._akform]), - ) + return f"{type(self).__name__}({self._location}, {self._akform!r})" def _build_field_col_records( self, akform, field_name=None, parent_fid=None, add_field=True, description="" @@ -1172,7 +1168,6 @@ def write(self, sink): anchor_raw_data, len(anchor_raw_data), replaces=self._key, - big=False, ) self._anchor.location = self._key.location + self._key.allocation #### Anchor end ############################## @@ -1291,18 +1286,9 @@ def _to_packed(layout): This is similar to `to_packed` in Awkward, but a bit more consistent. """ match layout.__class__: - case awkward.contents.BitMaskedArray: - next = layout.to_IndexedOptionArray64() - content = _to_packed(next._content[: layout.length]) - return awkward.contents.IndexedOptionArray( - next._index, content, parameters=next.parameters - ) - case awkward.contents.ByteMaskedArray: - next = layout.to_IndexedOptionArray64() - content = _to_packed(next._content[: layout._mask.length]) - return awkward.contents.IndexedOptionArray( - next._index, content, parameters=next.parameters - ) + case awkward.contents.BitMaskedArray | awkward.contents.ByteMaskedArray: + # the content of an option has no entries for the missing values on disk + return _to_packed(layout.to_IndexedOptionArray64()) case awkward.contents.EmptyArray: return layout case awkward.contents.IndexedArray: diff --git a/tests-cuda/test_1828_cov_gpu_rntuple.py b/tests-cuda/test_1828_cov_gpu_rntuple.py new file mode 100644 index 000000000..55032712c --- /dev/null +++ b/tests-cuda/test_1828_cov_gpu_rntuple.py @@ -0,0 +1,188 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE +from __future__ import annotations + +import numpy +import pytest +import skhep_testdata + +import uproot +from uproot.source.cufile_interface import CuFileSource + +ak = pytest.importorskip("awkward") +cupy = pytest.importorskip("cupy") +pytestmark = pytest.mark.skipif( + cupy.cuda.runtime.driverGetVersion() == 0, reason="No available CUDA driver." +) + +UNCOMPRESSED = "rntviewer-testfile-uncomp-single-rntuple-v1-0-0-0.root" + + +def test_optional_fields(tmp_path): + path = tmp_path / "optional.root" + # missing entries first, in a row, and last + data = ak.Array( + { + "x": [None, 2, None, None, 5, 6, None], + "y": [[1.5], None, [], [2.5, 3.5], None, [4.5], [5.5]], + } + ) + # the GPU interpreter can decompress ZSTD and LZ4, but not ZLIB + with uproot.recreate(path, compression=uproot.ZSTD(1)) as file: + file.mkrntuple("ntuple", data) + + with uproot.open(path) as file: + arrays = file["ntuple"].arrays(backend="cuda", interpreter="gpu") + assert ak.backend(arrays) == "cuda" + assert ak.to_backend(arrays, "cpu").to_list() == data.to_list() + + +def test_direct_reads_from_before_the_first_cluster(tmp_path): + path = tmp_path / "flat.root" + with uproot.recreate(path, compression=uproot.ZSTD(1)) as file: + file.mkrntuple("ntuple", {"x": numpy.array([1, 2, 3], numpy.int64)}) + + with uproot.open(path) as file: + ntuple = file["ntuple"] + + def read(start, stop): + # without cluster_offset, which is then taken from the clusters + datas = ntuple.gpu_read_cluster_range(["column-0"], start, stop) + datas._decompress() + arrays = ntuple.gpu_deserialize_decompressed_content(datas, start, stop) + return {key: cupy.asnumpy(value).tolist() for key, value in arrays.items()} + + # index -1 is before the first cluster, so it adds nothing + assert read(0, 1) == {0: [1, 2, 3]} + assert read(-1, 1) == {0: [1, 2, 3]} + assert read(-1, 0) == {} + + +def test_narrower_representation_is_converted_by_value(): + # column 1 is a float16 representation of a field whose result is float32 + filename = skhep_testdata.data_path( + "test_multiple_representations_rntuple_v1-0-0-0.root" + ) + with uproot.open(filename) as file: + ntuple = file["ntuple"] + assert ntuple.get_field_metadata(1).dtype == numpy.dtype("float16") + assert ntuple.get_field_metadata(1).dtype_result == numpy.dtype("float32") + datas = ntuple.gpu_read_cluster_range(["column-1"], 0, 3) + datas._decompress() + arrays = ntuple.gpu_deserialize_decompressed_content(datas, 0, 3) + expected = ntuple.read_cluster_range(1, 0, 3) + assert cupy.asnumpy(arrays[1]).tolist() == expected.tolist() == [1.0, 2.0, 3.0] + + +def test_uncompressed_pages_and_cufile_counters(): + filename = skhep_testdata.data_path(UNCOMPRESSED) + with uproot.open(filename) as file: + ntuple = file["Contributors"] + # column 1 holds the characters of firstName in one page of 178 bytes + field_metadata = ntuple.get_field_metadata(1) + filehandle = CuFileSource(filename, "rb") + assert filehandle.file_path == filename + payload = ntuple.gpu_read_cluster_pages(0, 1, filehandle, field_metadata) + assert filehandle.num_requested_chunks == 1 + assert filehandle.num_requested_bytes == 178 + assert filehandle.requested_chunk_sizes == [178] + assert len(filehandle.futures) == 1 + filehandle.get_all() + filehandle.close() + + assert not payload.page_is_compressed + payload._decompress() # nothing to decompress, the pages were read as is + data = ntuple.gpu_deserialize_pages(payload.data, 1, 0, field_metadata) + expected = ntuple.read_cluster_range(1, 0, 1) + assert cupy.asnumpy(data).tobytes() == expected.tobytes() + assert bytes(expected[:5]) == b"Jakob" + + +@pytest.mark.parametrize( + "compression_settings", + [0, 5, 100 * uproot.const.kZSTD], # nothing, algorithm 0, level 0 +) +def test_compression_settings_of_uncompressed_pages(compression_settings): + filename = skhep_testdata.data_path(UNCOMPRESSED) + with uproot.open(filename) as file: + ntuple = file["Contributors"] + ntuple.page_link_list[0][1].compression_settings = compression_settings + field_metadata = ntuple.get_field_metadata(1) + filehandle = CuFileSource(filename, "rb") + payload = ntuple.gpu_read_cluster_pages(0, 1, filehandle, field_metadata) + filehandle.get_all() + filehandle.close() + + assert payload.algorithm is None + assert payload.compression_level == compression_settings % 100 + payload._decompress() + data = ntuple.gpu_deserialize_pages(payload.data, 1, 0, field_metadata) + expected = ntuple.read_cluster_range(1, 0, 1) + assert cupy.asnumpy(data).tobytes() == expected.tobytes() + + +def test_uncompressed_arrays(): + with uproot.open(skhep_testdata.data_path(UNCOMPRESSED)) as file: + ntuple = file["Contributors"] + arrays = ntuple.arrays(backend="cuda", interpreter="gpu") + expected = ntuple.arrays() + assert len(expected) == 22 + assert ak.to_backend(arrays, "cpu").to_list() == expected.to_list() + + +@pytest.mark.parametrize( + ("compression", "first", "compressed"), + [ + # every page is read as is + (None, [True, False, True] * 333 + [True], [False, False]), + # the first page is compressed, but the second is too small for it + (uproot.ZSTD(1), [True] * 1000, [True, False]), + # the column is compressed, but neither of its pages + (uproot.ZSTD(1), [True, False, False] * 4 + [True], [False, False]), + ], +) +def test_bit_column_of_many_pages(tmp_path, compression, first, compressed): + # uproot writes one page per cluster, so the pages of two clusters are made + # the pages of the first; their numbers of bits are not multiples of 8 + second = [True, False, True, True, False] + path = tmp_path / "bits.root" + with uproot.recreate(path, compression=compression) as file: + ntuple = file.mkrntuple("ntuple", {"b": numpy.array(first)}) + ntuple.extend({"b": numpy.array(second)}) + + with uproot.open(path) as file: + ntuple = file["ntuple"] + field_metadata = ntuple.get_field_metadata(0) + assert field_metadata.isbit + first_pages = ntuple.page_link_list[0][0].pages + first_pages.extend(ntuple.page_link_list[1][0].pages) + assert [page.num_elements for page in first_pages] == [len(first), 5] + expected = first + second + assert ntuple.read_cluster_pages(0, 0, field_metadata).tolist() == expected + + datas = ntuple.gpu_read_cluster_range(["column-0"], 0, 1) + payload = datas.refs[0].fieldpayloads[0] + assert [page is not None for page in payload.pages] == compressed + assert payload.page_is_compressed == any(compressed) + datas._decompress() + arrays = ntuple.gpu_deserialize_decompressed_content(datas, 0, 1) + assert cupy.asnumpy(arrays[0]).tolist() == expected + + +@pytest.mark.parametrize("compression", [None, uproot.ZSTD(1)]) +def test_bit_column_payload_decompresses_itself(tmp_path, compression): + path = tmp_path / "bits.root" + values = [True] * 1000 + [False] * 3 + with uproot.recreate(path, compression=compression) as file: + file.mkrntuple("ntuple", {"b": numpy.array(values)}) + + with uproot.open(path) as file: + ntuple = file["ntuple"] + field_metadata = ntuple.get_field_metadata(0) + filehandle = CuFileSource(str(path), "rb") + payload = ntuple.gpu_read_cluster_pages(0, 0, filehandle, field_metadata) + filehandle.get_all() + filehandle.close() + assert payload.page_is_compressed == (compression is not None) + payload._decompress() + data = ntuple.gpu_deserialize_pages(payload.data, 0, 0, field_metadata) + assert cupy.asnumpy(data).tolist() == values diff --git a/tests/test_1828_fix_rntuple.py b/tests/test_1828_fix_rntuple.py new file mode 100644 index 000000000..360e75272 --- /dev/null +++ b/tests/test_1828_fix_rntuple.py @@ -0,0 +1,676 @@ +# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE + +from __future__ import annotations + +import json +import pickle +import struct +import sys + +import awkward as ak +import numpy as np +import pytest +import xxhash + +import uproot +import uproot.const +import uproot.models.RNTuple as models +from uproot.const import kStartBigFile + +ak = pytest.importorskip("awkward") + + +@pytest.fixture +def ntuple_path(tmp_path): + """A small RNTuple with nested records, lists, and documented fields.""" + path = tmp_path / "nested.root" + rec = ak.Array( + [ + {"a": 1, "inner": {"deep": 1.5}}, + {"a": 2, "inner": {"deep": 2.5}}, + {"a": 3, "inner": {"deep": 3.5}}, + ] + ) + vec = ak.Array([[{"p": 1}], [], [{"p": 2}, {"p": 3}]]) + data = ak.with_field(ak.Array({"x": [10, 20, 30]}), rec, "rec") + data = ak.with_field(data, vec, "vec") + data = ak.with_parameter(data, "__doc__", "Some entries") + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", data, description="The description") + return path + + +@pytest.fixture +def ntuple(ntuple_path): + with uproot.open(ntuple_path) as file: + yield file["ntuple"] + + +def test_pickle_with_loaded_metadata(ntuple): + assert ntuple.header.ntuple_name == "ntuple" + unpickled = pickle.loads(pickle.dumps(ntuple)) + assert unpickled.header.ntuple_name == "ntuple" + assert unpickled.arrays().x.to_list() == [10, 20, 30] + + +def test_field_index_of_an_anonymous_field(ntuple): + anonymous = ntuple["vec"].ntuple.all_fields[ntuple["vec"].field_id + 1] + assert anonymous.is_anonymous + with pytest.raises(ValueError, match="anonymous"): + anonymous.index + + +def test_iterate_adds_docs(tmp_path): + path = tmp_path / "documented.root" + form = ak.forms.RecordForm( + [ak.forms.NumpyForm("int32", parameters={"__doc__": "the x"})], ["x"] + ) + with uproot.recreate(path) as file: + ntuple = file.mkrntuple("ntuple", form) + ntuple.extend({"x": np.array([1, 2], dtype=np.int32)}) + with uproot.open(path) as file: + chunks = list(file["ntuple"].iterate(ak_add_doc=True)) + assert [chunk.x.layout.parameter("__doc__") for chunk in chunks] == ["the x"] + + +@pytest.mark.parametrize( + "record", + [ + {"member": 1, ":_0": {"member": 2}, ":_1": {"member": 3}}, + # only in base classes, whose (empty) leaf fields are equal Mappings + {":_0": {"member": 2}, ":_1": {"member": 3}}, + ], +) +def test_duplicates_that_cannot_be_told_apart(tmp_path, record): + # uproot writes records without a type name, which is what prefixes are made of + path = tmp_path / "file.root" + data = ak.Array([record] * 2) + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", {"c": data}) + with uproot.open(path) as file: + ntuple = file["ntuple"] + for _ in range(2): + with pytest.raises(RuntimeError, match="names are still not unique"): + ntuple.all_fields + + +def _write(path, data): + with uproot.recreate(path, compression=None) as file: + file.mkrntuple("ntuple", data) + return path + + +def _list_frame_items(buffer, position): + """ + Returns the positions of the payloads of a list frame of record frames, and the + position that follows the list frame. + """ + list_size, num_items = struct.unpack_from("> 15), by hand + zigzag = np.array([65535, 65534, 1, 0, 32768, 32769, 2, 3], dtype=", " + ", 'x', 'std::int64_t', '', '')" + ) + + assert repr(cascading._header).startswith( + f"NTuple_Header({cascading._header._location}, RecordForm(" + ) + assert repr(cascading._footer).startswith( + "NTuple_Footer(extension_field_record_frames=[]" + ) + assert repr(cascading._anchor).startswith("NTuple_Anchor(") + assert repr(cascading).startswith("NTuple(") + assert repr(cascading._footer) in repr(cascading) + + +def make_big(directory, num_bytes=kStartBigFile): + # skip over two gigabytes of file instead of writing them, leaving a hole + directory.file._cascading.freesegments.allocate(num_bytes) + + +skip_without_sparse_files = pytest.mark.skipif( + sys.platform == "win32", reason="this needs a sparse file to be fast" +) + + +@skip_without_sparse_files +@pytest.mark.parametrize("data", [None, {"x": np.array([1.5, 2.5])}]) +# past 2 GiB, the anchor's key can't hold its location in a 4-byte fSeekKey +@pytest.mark.parametrize("num_bytes", [kStartBigFile, 2**31 + 1000]) +def test_rntuple_past_the_big_file_boundary(tmp_path, data, num_bytes): + path = tmp_path / "big.root" + with uproot.recreate(path, compression=None) as file: + file["small"] = "before the boundary" + make_big(file, num_bytes) + # the anchor's key is big, and so must be its copy in the directory's + # list of keys, which readers take fKeylen from + if data is None: + file.mkrntuple("ntuple", {"x": "float64"}) + else: + file.mkrntuple("ntuple", data) + + with uproot.open(path) as file: + assert file["small"] == "before the boundary" + key = file.key("ntuple") + assert key.fSeekKey >= num_bytes + assert key.fVersion > 1000 # a big key + ntuple = file["ntuple"] + assert ntuple.num_entries == (0 if data is None else 2) + assert ntuple.arrays()["x"].tolist() == ([] if data is None else [1.5, 2.5]) + + +_WRITERS = """ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_1828 { + +struct Base { + int member; + float other; +}; +struct Child : Base { + int member; +}; +struct Left { + int shared; +}; +struct Right { + int shared; +}; +struct Both : Left, Right { + int member; +}; + +void write_projections(const char *path) +{ + auto model = ROOT::RNTupleModel::Create(); + auto pt = model->MakeField("pt"); + auto values = model->MakeField>("values"); + model + ->AddProjectedField(ROOT::RFieldBase::Create("pt_alias", "float").Unwrap(), + [](const std::string &) { return std::string("pt"); }) + .ThrowOnError(); + model + ->AddProjectedField( + ROOT::RFieldBase::Create("num_values", "ROOT::RNTupleCardinality").Unwrap(), + [](const std::string &) { return std::string("values"); }) + .ThrowOnError(); + auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); + for (int i = 0; i < 4; i++) { + *pt = 1.5f * i; + *values = std::vector(i, i); + writer->Fill(); + } +} + +void write_shadowed_members(const char *path) +{ + auto model = ROOT::RNTupleModel::Create(); + auto child = model->MakeField("child"); + auto both = model->MakeField("both"); + auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); + for (int i = 0; i < 3; i++) { + child->member = i; + child->Base::member = 10 * i; + child->other = 0.5f * i; + both->member = 100 * i; + both->Left::shared = 200 * i; + both->Right::shared = 300 * i; + writer->Fill(); + } +} + +void write_streamer_field(const char *path) +{ + auto model = ROOT::RNTupleModel::Create(); + model->MakeField("x"); + model->AddField(std::make_unique("streamed", "std::vector")); + auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); + auto entry = writer->CreateEntry(); + auto x = entry->GetPtr("x"); + auto streamed = entry->GetPtr>("streamed"); + for (int i = 0; i < 2; i++) { + *x = i; + streamed->push_back(i); + writer->Fill(*entry); + } +} + +void write_without_fields(const char *path) +{ + auto writer = ROOT::RNTupleWriter::Recreate(ROOT::RNTupleModel::Create(), "ntuple", path); +} + +std::string show(const char *path, int entry) +{ + std::ostringstream stream; + ROOT::RNTupleReader::Open("ntuple", path)->Show(entry, stream); + return stream.str(); +} + +// Show doesn't support variants +std::string show_variant(const char *path, int entry) +{ + auto reader = ROOT::RNTupleReader::Open("ntuple", path); + auto view = reader->GetView>("a"); + auto value = view(entry); + if (value.index() == 0) + return std::to_string(std::get<0>(value)); + return std::get<1>(value); +} + +} // namespace test_1828 +""" + + +_ATTRIBUTE_WRITER = """ +#include + +namespace test_1828 { + +void write_attributes(const char *path) +{ + auto file = std::unique_ptr(TFile::Open(path, "RECREATE")); + auto model = ROOT::RNTupleModel::Create(); + auto x = model->MakeField("x"); + auto writer = ROOT::RNTupleWriter::Append(std::move(model), "ntuple", *file); + auto attribute_model = ROOT::RNTupleModel::Create(); + auto note = attribute_model->MakeField("note"); + auto attributes = writer->CreateAttributeSet(std::move(attribute_model), "my_attributes"); + auto range = attributes->BeginRange(); + *note = "a note"; + for (int i = 0; i < 4; i++) { + *x = i; + writer->Fill(); + } + attributes->CommitRange(std::move(range)); + writer.reset(); +} + +} // namespace test_1828 +""" + + +@pytest.fixture(scope="module") +def root(): + ROOT = pytest.importorskip("ROOT") + if ROOT.gROOT.GetVersionInt() < 63800: + pytest.skip("needs the RNTuple interfaces of a recent ROOT") + # ROOT warnings become Python warnings, which are errors in this test suite. The + # classes above have no dictionaries, which ROOT warns about. + ignore_level = ROOT.gErrorIgnoreLevel + ROOT.gErrorIgnoreLevel = ROOT.kError + if not hasattr(ROOT, "test_1828"): + assert ROOT.gInterpreter.Declare(_WRITERS) + if ROOT.gROOT.GetVersionInt() >= 64000: + assert ROOT.gInterpreter.Declare(_ATTRIBUTE_WRITER) + yield ROOT.test_1828 + ROOT.gErrorIgnoreLevel = ignore_level + + +def _show(root, path, entry): + return json.loads(str(root.show(str(path), entry))) + + +def test_members_that_shadow_inherited_members(root, tmp_path): + path = tmp_path / "file.root" + root.write_shadowed_members(str(path)) + with uproot.open(path) as file: + ntuple = file["ntuple"] + assert sorted(ntuple["child"].keys()) == [ + "member", + "other", + "test_1828::Base::member", + ] + # members of different bases are told apart by their own prefix, and the one + # that is not repeated in a base stays as it is + assert sorted(ntuple["both"].keys()) == [ + "member", + "test_1828::Left::shared", + "test_1828::Right::shared", + ] + out = ntuple.arrays() + assert out.child.member.to_list() == [0, 1, 2] + assert out.child["test_1828::Base::member"].to_list() == [0, 10, 20] + assert out.both["test_1828::Left::shared"].to_list() == [0, 200, 400] + assert out.both["test_1828::Right::shared"].to_list() == [0, 300, 600] + + +def test_linked_attribute_set_written_by_root(root, tmp_path): + if not hasattr(root, "write_attributes"): + pytest.skip("needs RNTuple attributes") + path = tmp_path / "file.root" + root.write_attributes(str(path)) + with uproot.open(path) as file: + ntuple = file["ntuple"] + linked = ntuple.footer.linked_attribute_sets + assert [record.attribute_set_name for record in linked] == ["my_attributes"] + assert ntuple.arrays().x.to_list() == [0, 1, 2, 3] + + +@pytest.mark.parametrize( + ("data", "expected"), + [ + ( + ak.contents.BitMaskedArray( + ak.index.IndexU8(np.array([0b101], dtype=np.uint8)), + ak.contents.NumpyArray(np.array([1, 2, 3], dtype=np.int32)), + valid_when=True, + length=3, + lsb_order=True, + ), + [1, None, 3], + ), + ( + ak.contents.UnmaskedArray( + ak.contents.NumpyArray(np.array([1, 2], dtype=np.int32)) + ), + [1, 2], + ), + ], +) +def test_root_reads_packed_layouts(root, tmp_path, data, expected): + path = tmp_path / "file.root" + with uproot.recreate(path) as file: + file.mkrntuple("ntuple", {"a": ak.Array(data)}) + assert [_show(root, path, i)["a"] for i in range(len(expected))] == expected From 630bd46d23de49a21598b5e4500086df001ff65d Mon Sep 17 00:00:00 2001 From: Andres Rios Tascon Date: Fri, 6 Nov 2026 10:50:54 -0500 Subject: [PATCH 2/3] test: declare only the C++ that the RNTuple regression tests use The ROOT fixture also declared writers that only the tests of #1832 use, and if any of them didn't compile with some ROOT version, the tests here would fail too. The fixture also restores gErrorIgnoreLevel if a declaration fails. Assisted-by: Claude Code:claude-opus-5-5 --- tests/test_1828_fix_rntuple.py | 71 ++++------------------------------ 1 file changed, 8 insertions(+), 63 deletions(-) diff --git a/tests/test_1828_fix_rntuple.py b/tests/test_1828_fix_rntuple.py index 360e75272..c83e4d187 100644 --- a/tests/test_1828_fix_rntuple.py +++ b/tests/test_1828_fix_rntuple.py @@ -17,8 +17,6 @@ import uproot.models.RNTuple as models from uproot.const import kStartBigFile -ak = pytest.importorskip("awkward") - @pytest.fixture def ntuple_path(tmp_path): @@ -459,7 +457,6 @@ def test_rntuple_past_the_big_file_boundary(tmp_path, data, num_bytes): #include #include #include -#include #include namespace test_1828 { @@ -481,28 +478,6 @@ def test_rntuple_past_the_big_file_boundary(tmp_path, data, num_bytes): int member; }; -void write_projections(const char *path) -{ - auto model = ROOT::RNTupleModel::Create(); - auto pt = model->MakeField("pt"); - auto values = model->MakeField>("values"); - model - ->AddProjectedField(ROOT::RFieldBase::Create("pt_alias", "float").Unwrap(), - [](const std::string &) { return std::string("pt"); }) - .ThrowOnError(); - model - ->AddProjectedField( - ROOT::RFieldBase::Create("num_values", "ROOT::RNTupleCardinality").Unwrap(), - [](const std::string &) { return std::string("values"); }) - .ThrowOnError(); - auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); - for (int i = 0; i < 4; i++) { - *pt = 1.5f * i; - *values = std::vector(i, i); - writer->Fill(); - } -} - void write_shadowed_members(const char *path) { auto model = ROOT::RNTupleModel::Create(); @@ -520,27 +495,6 @@ def test_rntuple_past_the_big_file_boundary(tmp_path, data, num_bytes): } } -void write_streamer_field(const char *path) -{ - auto model = ROOT::RNTupleModel::Create(); - model->MakeField("x"); - model->AddField(std::make_unique("streamed", "std::vector")); - auto writer = ROOT::RNTupleWriter::Recreate(std::move(model), "ntuple", path); - auto entry = writer->CreateEntry(); - auto x = entry->GetPtr("x"); - auto streamed = entry->GetPtr>("streamed"); - for (int i = 0; i < 2; i++) { - *x = i; - streamed->push_back(i); - writer->Fill(*entry); - } -} - -void write_without_fields(const char *path) -{ - auto writer = ROOT::RNTupleWriter::Recreate(ROOT::RNTupleModel::Create(), "ntuple", path); -} - std::string show(const char *path, int entry) { std::ostringstream stream; @@ -548,17 +502,6 @@ def test_rntuple_past_the_big_file_boundary(tmp_path, data, num_bytes): return stream.str(); } -// Show doesn't support variants -std::string show_variant(const char *path, int entry) -{ - auto reader = ROOT::RNTupleReader::Open("ntuple", path); - auto view = reader->GetView>("a"); - auto value = view(entry); - if (value.index() == 0) - return std::to_string(std::get<0>(value)); - return std::get<1>(value); -} - } // namespace test_1828 """ @@ -600,12 +543,14 @@ def root(): # classes above have no dictionaries, which ROOT warns about. ignore_level = ROOT.gErrorIgnoreLevel ROOT.gErrorIgnoreLevel = ROOT.kError - if not hasattr(ROOT, "test_1828"): - assert ROOT.gInterpreter.Declare(_WRITERS) - if ROOT.gROOT.GetVersionInt() >= 64000: - assert ROOT.gInterpreter.Declare(_ATTRIBUTE_WRITER) - yield ROOT.test_1828 - ROOT.gErrorIgnoreLevel = ignore_level + try: + if not hasattr(ROOT, "test_1828"): + assert ROOT.gInterpreter.Declare(_WRITERS) + if ROOT.gROOT.GetVersionInt() >= 64000: + assert ROOT.gInterpreter.Declare(_ATTRIBUTE_WRITER) + yield ROOT.test_1828 + finally: + ROOT.gErrorIgnoreLevel = ignore_level def _show(root, path, entry): From 05562add436eecd67391b32420382e93d69995d2 Mon Sep 17 00:00:00 2001 From: Andres Rios Tascon Date: Tue, 10 Nov 2026 17:41:58 -0500 Subject: [PATCH 3/3] refactor: remove the unused page_is_compressed field of FieldPayload Each page now decides whether it is compressed, and uncompressed pages are recorded as None, so nothing reads the cluster-wide flag anymore. Assisted-by: Claude Code:claude-opus-5-5 --- src/uproot/models/RNTuple.py | 3 --- tests-cuda/test_1828_cov_gpu_rntuple.py | 7 ++++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/uproot/models/RNTuple.py b/src/uproot/models/RNTuple.py index 4d47f7865..bb31c2d81 100644 --- a/src/uproot/models/RNTuple.py +++ b/src/uproot/models/RNTuple.py @@ -1132,7 +1132,6 @@ def gpu_read_cluster_pages( cluster_contents = FieldPayload( col_idx_orig, full_output_buffer, - False, algorithm_str, compression_level, ) @@ -1154,7 +1153,6 @@ def gpu_read_cluster_pages( n_bytes = loc.num_bytes if algorithm_str is not None and n_bytes < page_bytes: - cluster_contents.page_is_compressed = True # skip the 9 byte header; LZ4 has an additional 8-byte checksum header_size = 9 if algorithm_str != "LZ4" else 9 + 8 offset = int(loc.offset + header_size) @@ -2245,7 +2243,6 @@ class FieldPayload: key: str data: CupyArray # Type: ignore - page_is_compressed: bool algorithm: str compression_level: int pages: list[CupyArray] = dataclasses.field(default_factory=list) diff --git a/tests-cuda/test_1828_cov_gpu_rntuple.py b/tests-cuda/test_1828_cov_gpu_rntuple.py index 55032712c..75b79732b 100644 --- a/tests-cuda/test_1828_cov_gpu_rntuple.py +++ b/tests-cuda/test_1828_cov_gpu_rntuple.py @@ -89,7 +89,7 @@ def test_uncompressed_pages_and_cufile_counters(): filehandle.get_all() filehandle.close() - assert not payload.page_is_compressed + assert payload.pages == [None] payload._decompress() # nothing to decompress, the pages were read as is data = ntuple.gpu_deserialize_pages(payload.data, 1, 0, field_metadata) expected = ntuple.read_cluster_range(1, 0, 1) @@ -162,7 +162,6 @@ def test_bit_column_of_many_pages(tmp_path, compression, first, compressed): datas = ntuple.gpu_read_cluster_range(["column-0"], 0, 1) payload = datas.refs[0].fieldpayloads[0] assert [page is not None for page in payload.pages] == compressed - assert payload.page_is_compressed == any(compressed) datas._decompress() arrays = ntuple.gpu_deserialize_decompressed_content(datas, 0, 1) assert cupy.asnumpy(arrays[0]).tolist() == expected @@ -182,7 +181,9 @@ def test_bit_column_payload_decompresses_itself(tmp_path, compression): payload = ntuple.gpu_read_cluster_pages(0, 0, filehandle, field_metadata) filehandle.get_all() filehandle.close() - assert payload.page_is_compressed == (compression is not None) + assert any(page is not None for page in payload.pages) == ( + compression is not None + ) payload._decompress() data = ntuple.gpu_deserialize_pages(payload.data, 0, 0, field_metadata) assert cupy.asnumpy(data).tolist() == values