JingsongLi commented on code in PR #9850: URL: https://github.com/apache/paimon/pull/9850#discussion_r4056249561
########## paimon-python/pypaimon/read/reader/parquet_page_index_reader.py: ########## @@ -0,0 +1,438 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Read contiguous Parquet row windows using their OffsetIndex. + +Selected encoded pages are placed in bounded, in-memory Parquet files. PyArrow +still decodes the pages, including dictionary and compression encodings. Source +files are never rewritten. Nested fields retain their complete physical schema +and align their leaf columns at common row boundaries. Files without indexes and +disjoint ranges use the normal reader: per-page seeks can amplify requests in +filesystems that prefetch remote data (including Jindo). +""" + +import base64 +import bisect +import struct + +import pyarrow as pa +import pyarrow.parquet as pq + + +# Bound encoded data retained by the temporary column files, independently of +# the number of requested rows and the size of the source row group. +_MAX_PAGE_BYTES = 32 * 1024 * 1024 +_MAX_INDEX_BYTES = 8 * 1024 * 1024 + + +class _Compact: + """Thrift compact values used by Parquet metadata (no generated bindings).""" + + def __init__(self, data): + self.data = memoryview(data) + self.position = 0 + + def take(self, size): + end = self.position + size + if size < 0 or end > len(self.data): + raise ValueError("Truncated Parquet page-index metadata") + result = self.data[self.position:end] + self.position = end + return result + + def unsigned(self): + result = 0 + for shift in range(0, 70, 7): + value = self.take(1)[0] + result |= (value & 127) << shift + if value < 128: + return result + raise ValueError("Invalid Parquet compact integer") + + def value(self, kind, depth=0): + if depth > 64: + raise ValueError("Parquet metadata nesting exceeds 64 levels") + if kind in (1, 2): + return kind == 1 + if kind == 3: + return self.take(1).tobytes() + if kind in (4, 5, 6): + value = self.unsigned() + return (value >> 1) ^ -(value & 1) + if kind == 7: + return self.take(8).tobytes() + if kind == 8: + return self.take(self.unsigned()).tobytes() + if kind in (9, 10): + header = self.take(1)[0] + count, element = header >> 4, header & 15 + if count == 15: + count = self.unsigned() + if count > len(self.data) - self.position: + raise ValueError("Invalid Parquet compact collection size") + return element, [ + self.value(self.take(1)[0] if element in (1, 2) else element, depth + 1) + for _ in range(count) + ] + if kind == 12: + fields = {} + previous = 0 + while True: + header = self.take(1)[0] + if header == 0: + return fields + delta, field_kind = header >> 4, header & 15 + field = previous + delta if delta else self.value(4) + if field in fields: + raise ValueError("Duplicate Parquet compact field") + fields[field] = field_kind, self.value(field_kind, depth + 1) + previous = field + raise ValueError("Unsupported Parquet compact type: {}".format(kind)) + + +def _unsigned(value): + result = bytearray() + while value >= 128: + result.append((value & 127) | 128) + value >>= 7 + result.append(value) + return bytes(result) + + +def _encode(kind, value): + if kind in (1, 2): + return bytes([1 if value else 2]) + if kind in (3, 7): + return value + if kind in (4, 5, 6): + return _unsigned(value * 2 if value >= 0 else -value * 2 - 1) + if kind == 8: + return _unsigned(len(value)) + value + if kind in (9, 10): + element, items = value + size = len(items) + header = bytes([(min(size, 15) << 4) | element]) + if size >= 15: + header += _unsigned(size) + return header + b"".join(_encode(element, item) for item in items) + if kind == 12: + result = bytearray() + previous = 0 + for field, (field_kind, item) in sorted(value.items()): + delta = field - previous + if field_kind in (1, 2): + field_kind = 1 if item else 2 + if 0 < delta < 16: + result.append((delta << 4) | field_kind) + else: + result.append(field_kind) + result.extend(_encode(4, field)) + if field_kind not in (1, 2): + result.extend(_encode(field_kind, item)) + previous = field + result.append(0) + return bytes(result) + raise ValueError("Unsupported Parquet compact type: {}".format(kind)) + + +def _get(fields, field, default=None): + return fields[field][1] if field in fields else default + + +def _read_exact(source, offset, length): + if offset < 4 or length <= 0: + raise ValueError("Invalid Parquet page-index byte range") + data = source.read_at(length, offset) + if len(data) != length: + raise OSError("Truncated Parquet page-index byte range") + return data + + +class ParquetPageIndexReader: + def __init__(self, source, metadata, schema, footer, columns, fields, batch_size): + self.source = source + self.metadata = metadata + self.schema = schema + self.footer = footer + self.columns = columns + self.fields = fields + self.batch_size = batch_size + + @classmethod + def create(cls, source, parquet_file, columns, row_groups, batch_size): + metadata = parquet_file.metadata + schema = parquet_file.schema_arrow + if not columns or len(set(schema.names)) != len(schema): + return None + indices = [schema.get_field_index(name) for name in columns] + if any(index < 0 for index in indices) or len(set(indices)) != len(indices): + return None + if not any(getattr(metadata.row_group(group).column(index), + "has_offset_index", False) + for group in row_groups for index in range(metadata.num_columns)): + return None + output = pa.BufferOutputStream() + metadata.write_metadata_file(output) + serialized = output.getvalue().to_pybytes() + length = struct.unpack("<I", serialized[-8:-4])[0] + footer = _Compact(serialized[-8 - length:-8]).value(12) + if 8 in footer or 9 in footer: + return None # Encrypted pages need the original file identity/AAD. + elements = _get(footer, 2)[1] + # Parquet stores a preorder schema tree and one chunk per physical leaf. + # Arrow field positions cannot be used as physical column positions. + fields = [] + position, leaf = 1, 0 + for _ in range(_get(elements[0], 5)): + start, first_leaf, pending = position, leaf, 1 + while pending: + if position >= len(elements): + raise ValueError("Truncated Parquet schema tree") + element = elements[position] + children = _get(element, 5, 0) + if children < 0 or (1 in element and children) or (1 not in element and not children): + raise ValueError("Invalid Parquet schema child count") + pending += children - 1 + leaf += int(1 in element) + position += 1 + fields.append((elements[start:position], list(range(first_leaf, leaf)))) + if (position != len(elements) or leaf != metadata.num_columns + or len(fields) != len(schema)): + return None + if not any(all(getattr(metadata.row_group(group).column(leaf), + "has_offset_index", False) + for index in indices for leaf in fields[index][1]) + for group in row_groups): + return None + return cls(source, metadata, schema, footer, indices, fields, batch_size) + + def read_row_group(self, group, runs): + """Return selected batches, or None when the ordinary reader is cheaper.""" + # Decide before reading indexes so scattered selections preserve the + # existing I/O pattern. A future multi-range path needs an I/O planner + # that accounts for filesystem prefetch, not just compressed page sizes. + if len(runs) != 1: + return None + row_group = _get(self.footer, 4)[1][group] + row_count = _get(row_group, 3) + if sum(upper - lower + 1 for lower, upper in runs) >= row_count: + return None + chunks = _get(row_group, 1)[1] + physical_columns = [leaf for index in self.columns for leaf in self.fields[index][1]] + if any(4 not in chunks[index] or 5 not in chunks[index] + or _get(chunks[index], 1) or 8 in chunks[index] or 9 in chunks[index] + or 10 in _get(chunks[index], 3) # Legacy index pages. + for index in physical_columns): + return None + indexed = {} + plans = [] + selected_bytes = 0 + index_bytes = 0 + full_bytes = 0 + for index in sorted(physical_columns): + chunk = chunks[index] + index_size = _get(chunk, 5) + if index_size > _MAX_INDEX_BYTES: + return None + raw = _read_exact(self.source, _get(chunk, 4), index_size) Review Comment: [P2] Batch OffsetIndex reads before deciding to fall back Each physical leaf performs a separate read_at here, while selected_bytes plus index_bytes is checked only after every index has been fetched. With 200 scalar columns and a one-page row group, selecting rows 0 through 1 adds about 200 index range reads and then falls back to the full-row-group reader because no page can be skipped. parquet-mr retains decoded indexes in a row-group ColumnIndexStore and coalesces or vector-reads selected data ranges; its source also explicitly marks batching consecutive OffsetIndexes as a TODO. Please keep this default-on Python path at least no worse than that model by planning and coalescing adjacent index ranges from the footer, reusing decoded indexes, and/or rejecting the optimization from footer metadata before issuing per-column reads. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
