From 0054c9c6e0b0f80e3cc2e8ff4f89c83a46317fb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=9F=E5=BC=8B?= Date: Wed, 13 May 2026 14:19:14 +0800 Subject: [PATCH 01/10] [python] Support blob view fields # Conflicts: # paimon-python/pypaimon/common/options/core_options.py # paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py # paimon-python/pypaimon/read/reader/data_file_batch_reader.py # paimon-python/pypaimon/read/split_read.py # paimon-python/pypaimon/schema/schema.py # paimon-python/pypaimon/table/row/blob.py # paimon-python/pypaimon/tests/blob_test.py # paimon-python/pypaimon/write/writer/data_blob_writer.py --- .../pypaimon/common/options/core_options.py | 24 +++ .../reader/blob_descriptor_convert_reader.py | 40 +++- .../read/reader/data_file_batch_reader.py | 63 ++++++- paimon-python/pypaimon/read/split_read.py | 12 +- paimon-python/pypaimon/schema/schema.py | 20 ++ paimon-python/pypaimon/table/row/blob.py | 176 ++++++++++++++++++ .../pypaimon/tests/blob_table_test.py | 142 ++++++++++++++ paimon-python/pypaimon/tests/blob_test.py | 22 ++- .../pypaimon/utils/blob_view_lookup.py | 163 ++++++++++++++++ .../pypaimon/write/writer/data_blob_writer.py | 64 ++++++- 10 files changed, 705 insertions(+), 21 deletions(-) create mode 100644 paimon-python/pypaimon/utils/blob_view_lookup.py diff --git a/paimon-python/pypaimon/common/options/core_options.py b/paimon-python/pypaimon/common/options/core_options.py index b2f0e019166a..7002b5317e75 100644 --- a/paimon-python/pypaimon/common/options/core_options.py +++ b/paimon-python/pypaimon/common/options/core_options.py @@ -241,6 +241,16 @@ class CoreOptions: ) ) + BLOB_VIEW_FIELD: ConfigOption[str] = ( + ConfigOptions.key("blob-view-field") + .string_type() + .no_default_value() + .with_description( + "Comma-separated BLOB field names that should be stored as serialized BlobViewStruct bytes " + "inline in normal data files and resolved from upstream tables at read time." + ) + ) + TARGET_FILE_SIZE: ConfigOption[MemorySize] = ( ConfigOptions.key("target-file-size") .memory_type() @@ -661,6 +671,20 @@ def variant_shredding_schema(self) -> Optional[str]: def blob_descriptor_fields(self, default=None): value = self.options.get(CoreOptions.BLOB_DESCRIPTOR_FIELD, default) + return CoreOptions._parse_field_set(value) + + def blob_view_fields(self, default=None): + value = self.options.get(CoreOptions.BLOB_VIEW_FIELD, default) + return CoreOptions._parse_field_set(value) + + def blob_inline_fields(self, default=None): + fields = set() + fields.update(self.blob_descriptor_fields(default)) + fields.update(self.blob_view_fields(default)) + return fields + + @staticmethod + def _parse_field_set(value): if value is None: return set() if isinstance(value, str): diff --git a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py index 35fe046a03ce..1e30ec0d5b6b 100644 --- a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py +++ b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py @@ -30,6 +30,8 @@ def __init__(self, inner: RecordBatchReader, table): self._descriptor_fields = CoreOptions.blob_descriptor_fields(table.options) self.file_io = inner.file_io self.blob_field_indices = inner.blob_field_indices + self._view_fields = CoreOptions.blob_view_fields(table.options) + self._blob_view_lookup = None def read_arrow_batch(self) -> Optional[RecordBatch]: import pyarrow @@ -39,7 +41,8 @@ def read_arrow_batch(self) -> Optional[RecordBatch]: return self._convert_batch(batch, pyarrow) def _convert_batch(self, batch, pyarrow): - from pypaimon.table.row.blob import Blob, BlobDescriptor + from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct + from pypaimon.utils.blob_view_lookup import BlobViewLookup result = batch for field_name in self._descriptor_fields: @@ -70,6 +73,41 @@ def _convert_batch(self, batch, pyarrow): except Exception: converted_values.append(value) + column_idx = result.schema.names.index(field_name) + result = result.set_column( + column_idx, + pyarrow.field(field_name, pyarrow.large_binary(), nullable=True), + pyarrow.array(converted_values, type=pyarrow.large_binary()), + ) + for field_name in self._view_fields: + if field_name not in result.schema.names: + continue + values = result.column(field_name).to_pylist() + converted_values = [] + for value in values: + if value is None: + converted_values.append(None) + continue + if hasattr(value, 'as_py'): + value = value.as_py() + if isinstance(value, str): + value = value.encode('utf-8') + if isinstance(value, bytearray): + value = bytes(value) + if not isinstance(value, bytes): + converted_values.append(value) + continue + try: + if not BlobViewStruct.is_blob_view_struct(value): + converted_values.append(value) + continue + if self._blob_view_lookup is None: + self._blob_view_lookup = BlobViewLookup(self._table) + view_struct = BlobViewStruct.deserialize(value) + converted_values.append(self._blob_view_lookup.resolve_data(view_struct)) + except Exception: + converted_values.append(value) + column_idx = result.schema.names.index(field_name) result = result.set_column( column_idx, diff --git a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py index 64da0cc8400e..0df2d4994861 100644 --- a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py +++ b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py @@ -26,7 +26,9 @@ from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader from pypaimon.schema.data_types import DataField, PyarrowFieldParser from pypaimon.table.row.blob import Blob +from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct from pypaimon.table.special_fields import SpecialFields +from pypaimon.utils.blob_view_lookup import BlobViewLookup class DataFileBatchReader(RecordBatchReader): @@ -42,8 +44,10 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p system_fields: dict, blob_as_descriptor: bool = False, blob_descriptor_fields: Optional[set] = None, + blob_view_fields: Optional[set] = None, file_io: Optional[FileIO] = None, - row_id_offsets: Optional[List[int]] = None): + row_id_offsets: Optional[List[int]] = None, + table=None): self.format_reader = format_reader self.index_mapping = index_mapping self.partition_info = partition_info @@ -57,7 +61,9 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p self.system_fields = system_fields self.blob_as_descriptor = blob_as_descriptor self.blob_descriptor_fields = blob_descriptor_fields or set() + self.blob_view_fields = blob_view_fields or set() self.file_io = file_io + self.table = table self.blob_field_names = { field.name for field in fields @@ -68,6 +74,12 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p for field_name in self.blob_descriptor_fields if field_name in self.blob_field_names } + self.view_blob_fields = { + field_name + for field_name in self.blob_view_fields + if field_name in self.blob_field_names + } + self._blob_view_lookup = None def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch]: if isinstance(self.format_reader, FormatBlobReader): @@ -80,7 +92,7 @@ def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch if self.partition_info is None and self.index_mapping is None: if self.row_tracking_enabled and self.system_fields: record_batch = self._assign_row_tracking(record_batch) - return record_batch + return self._convert_inline_blob_columns(record_batch) inter_arrays = [] inter_names = [] @@ -137,19 +149,20 @@ def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch if self.row_tracking_enabled and self.system_fields: record_batch = self._assign_row_tracking(record_batch) - record_batch = self._convert_descriptor_stored_blob_columns(record_batch) + record_batch = self._convert_inline_blob_columns(record_batch) return record_batch - def _convert_descriptor_stored_blob_columns(self, record_batch: RecordBatch) -> RecordBatch: + def _convert_inline_blob_columns(self, record_batch: RecordBatch) -> RecordBatch: if isinstance(self.format_reader, FormatBlobReader): return record_batch - if not self.descriptor_blob_fields: + if not self.descriptor_blob_fields and not self.view_blob_fields: return record_batch schema_names = set(record_batch.schema.names) target_fields = [f for f in self.descriptor_blob_fields if f in schema_names] - if not target_fields: + view_fields = [f for f in self.view_blob_fields if f in schema_names] + if not target_fields and not view_fields: return record_batch arrays = list(record_batch.columns) @@ -163,6 +176,16 @@ def _convert_descriptor_stored_blob_columns(self, record_batch: RecordBatch) -> converted = [self._blob_cell_to_data(v) for v in values] arrays[field_idx] = pa.array(converted, type=pa.large_binary()) + for field_name in view_fields: + field_idx = record_batch.schema.get_field_index(field_name) + values = record_batch.column(field_idx).to_pylist() + + if self.blob_as_descriptor: + converted = [self._blob_view_cell_to_descriptor(v) for v in values] + else: + converted = [self._blob_view_cell_to_data(v) for v in values] + arrays[field_idx] = pa.array(converted, type=pa.large_binary()) + return pa.RecordBatch.from_arrays(arrays, schema=record_batch.schema) @staticmethod @@ -185,6 +208,34 @@ def _blob_cell_to_data(self, value): return value return Blob.from_bytes(value, self.file_io).to_data() + def _blob_view_cell_to_descriptor(self, value): + view_struct = self._deserialize_blob_view_or_none(value) + if view_struct is None: + return self._normalize_blob_cell(value) + return self._blob_view_lookup_or_create().resolve_descriptor(view_struct).serialize() + + def _blob_view_cell_to_data(self, value): + view_struct = self._deserialize_blob_view_or_none(value) + if view_struct is None: + return self._normalize_blob_cell(value) + return self._blob_view_lookup_or_create().resolve_data(view_struct) + + @staticmethod + def _deserialize_blob_view_or_none(value): + value = DataFileBatchReader._normalize_blob_cell(value) + if value is None or not isinstance(value, bytes): + return None + if not BlobViewStruct.is_blob_view_struct(value): + return None + return BlobViewStruct.deserialize(value) + + def _blob_view_lookup_or_create(self): + if self.table is None: + raise ValueError("Cannot resolve blob view without table context.") + if self._blob_view_lookup is None: + self._blob_view_lookup = BlobViewLookup(self.table) + return self._blob_view_lookup + def _assign_row_tracking(self, record_batch: RecordBatch) -> RecordBatch: """Assign row tracking meta fields (_ROW_ID and _SEQUENCE_NUMBER).""" arrays = list(record_batch.columns) diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index e432eca6b122..e4862855f001 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -277,6 +277,7 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, blob_as_descriptor = CoreOptions.blob_as_descriptor(self.table.options) blob_descriptor_fields = CoreOptions.blob_descriptor_fields(self.table.options) + blob_view_fields = CoreOptions.blob_view_fields(self.table.options) index_mapping = self.create_index_mapping() partition_info = self._create_partition_info() @@ -307,8 +308,10 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, system_fields, blob_as_descriptor=blob_as_descriptor, blob_descriptor_fields=blob_descriptor_fields, + blob_view_fields=blob_view_fields, file_io=self.table.file_io, - row_id_offsets=row_indices) + row_id_offsets=row_indices, + table=self.table) else: reader = DataFileBatchReader( format_reader, @@ -322,8 +325,10 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, system_fields, blob_as_descriptor=blob_as_descriptor, blob_descriptor_fields=blob_descriptor_fields, + blob_view_fields=blob_view_fields, file_io=self.table.file_io, - row_id_offsets=row_indices) + row_id_offsets=row_indices, + table=self.table) # For non-Vortex formats, wrap with RowIdFilterRecordBatchReader if row_ranges is not None and row_indices is None: @@ -761,7 +766,8 @@ def create_reader(self) -> RecordReader: reader = merge_reader if (not CoreOptions.blob_as_descriptor(self.table.options) - and CoreOptions.blob_descriptor_fields(self.table.options)): + and (CoreOptions.blob_descriptor_fields(self.table.options) + or CoreOptions.blob_view_fields(self.table.options))): reader = BlobDescriptorConvertReader(reader, self.table) return reader diff --git a/paimon-python/pypaimon/schema/schema.py b/paimon-python/pypaimon/schema/schema.py index 912966732660..c9425c286e55 100644 --- a/paimon-python/pypaimon/schema/schema.py +++ b/paimon-python/pypaimon/schema/schema.py @@ -77,6 +77,26 @@ def from_pyarrow_schema(pa_schema: pa.Schema, partition_keys: Optional[List[str] "Table with BLOB type column must have other normal columns." ) + blob_field_names = { + field.name for field in fields if 'blob' in str(field.type).lower() + } + core_options = CoreOptions.from_dict(options) + descriptor_fields = core_options.blob_descriptor_fields() + view_fields = core_options.blob_view_fields() + unknown_inline_fields = descriptor_fields.union(view_fields).difference(blob_field_names) + if unknown_inline_fields: + raise ValueError( + "Fields in 'blob-descriptor-field' or 'blob-view-field' must be blob fields " + "in schema. Unknown fields: {}".format(sorted(unknown_inline_fields)) + ) + + overlapping_inline_fields = descriptor_fields.intersection(view_fields) + if overlapping_inline_fields: + raise ValueError( + "Fields in 'blob-descriptor-field' and 'blob-view-field' must not overlap. " + "Overlapping fields: {}".format(sorted(overlapping_inline_fields)) + ) + required_options = { CoreOptions.ROW_TRACKING_ENABLED.key(): 'true', CoreOptions.DATA_EVOLUTION_ENABLED.key(): 'true' diff --git a/paimon-python/pypaimon/table/row/blob.py b/paimon-python/pypaimon/table/row/blob.py index 43391775bd8d..37d25335b63a 100644 --- a/paimon-python/pypaimon/table/row/blob.py +++ b/paimon-python/pypaimon/table/row/blob.py @@ -21,6 +21,7 @@ from typing import BinaryIO, Optional, Union from urllib.parse import urlparse +from pypaimon.common.identifier import Identifier from pypaimon.common.uri_reader import UriReader, FileUriReader @@ -162,6 +163,115 @@ def __repr__(self) -> str: return self.__str__() +class BlobViewStruct: + CURRENT_VERSION = 1 + MAGIC = 0x424C4F4256494557 # "BLOBVIEW" + + def __init__(self, identifier: Union[Identifier, str], field_id: int, row_id: int): + if isinstance(identifier, str): + identifier = Identifier.from_string(identifier) + if not isinstance(identifier, Identifier): + raise TypeError("BlobViewStruct identifier must be Identifier or str.") + self._identifier = identifier + self._field_id = field_id + self._row_id = row_id + + @property + def identifier(self) -> Identifier: + return self._identifier + + @property + def field_id(self) -> int: + return self._field_id + + @property + def row_id(self) -> int: + return self._row_id + + def serialize(self) -> bytes: + identifier_bytes = self._identifier.get_full_name().encode('utf-8') + data = struct.pack(' 'BlobViewStruct': + if len(data) < 25: + raise ValueError("Invalid BlobViewStruct data: too short") + + offset = 0 + version = struct.unpack(' len(data): + raise ValueError("Invalid BlobViewStruct data: identifier length exceeds data size") + + identifier = data[offset:offset + identifier_length].decode('utf-8') + offset += identifier_length + field_id = struct.unpack(' bool: + if not isinstance(data, (bytes, bytearray)): + return False + raw = bytes(data) + if len(raw) < 9: + return False + version = raw[0] + if version != cls.CURRENT_VERSION: + return False + try: + magic = struct.unpack(' bool: + if not isinstance(other, BlobViewStruct): + return False + return (self._identifier == other._identifier + and self._field_id == other._field_id + and self._row_id == other._row_id) + + def __hash__(self) -> int: + return hash((self._identifier.get_full_name(), self._field_id, self._row_id)) + + def __str__(self) -> str: + return ( + f"BlobViewStruct(identifier={self._identifier.get_full_name()}, " + f"field_id={self._field_id}, row_id={self._row_id})" + ) + + def __repr__(self) -> str: + return self.__str__() + + class OffsetInputStream(io.RawIOBase): def __init__(self, wrapped, offset: int, length: int): @@ -283,6 +393,8 @@ def from_bytes(data: Optional[bytes], file_io=None, allow_blob_data: bool = True if not isinstance(data, (bytes, bytearray)): raise TypeError(f"Blob.from_bytes expects bytes, got {type(data)}") data = bytes(data) + if BlobViewStruct.is_blob_view_struct(data): + return Blob.from_view(BlobViewStruct.deserialize(data)) is_descriptor = BlobDescriptor.is_blob_descriptor(data) if not allow_blob_data and not is_descriptor: raise ValueError( @@ -296,6 +408,31 @@ def from_bytes(data: Optional[bytes], file_io=None, allow_blob_data: bool = True return BlobRef(uri_reader, descriptor) return BlobData(data) + @staticmethod + def from_view(view_struct: BlobViewStruct) -> 'Blob': + return BlobView(view_struct) + + @staticmethod + def from_bytes_with_reader( + data: bytes, + uri_reader: Optional[UriReader], + file_io=None, + allow_blob_data: bool = True) -> Optional['Blob']: + if data is None: + return None + if BlobViewStruct.is_blob_view_struct(data): + return Blob.from_view(BlobViewStruct.deserialize(data)) + if BlobDescriptor.is_blob_descriptor(data) or not allow_blob_data: + descriptor = BlobDescriptor.deserialize(data) + return Blob.from_descriptor(uri_reader or UriReader.from_file(file_io), descriptor) + return Blob.from_data(data) + + @staticmethod + def serialize_blob(blob: 'Blob') -> bytes: + if isinstance(blob, BlobView): + return blob.view_struct.serialize() + return blob.to_descriptor().serialize() + class _PlaceholderBlob(Blob): @@ -382,3 +519,42 @@ def __eq__(self, other) -> bool: def __hash__(self) -> int: return hash(self._descriptor) + + +class BlobView(Blob): + + def __init__(self, view_struct: BlobViewStruct): + self._view_struct = view_struct + self._resolved_blob = None + + @property + def view_struct(self) -> BlobViewStruct: + return self._view_struct + + def is_resolved(self) -> bool: + return self._resolved_blob is not None + + def resolve(self, uri_reader: UriReader, descriptor: BlobDescriptor): + self._resolved_blob = BlobRef(uri_reader, descriptor) + + def to_data(self) -> bytes: + return self._resolved().to_data() + + def to_descriptor(self) -> BlobDescriptor: + return self._resolved().to_descriptor() + + def new_input_stream(self) -> BinaryIO: + return self._resolved().new_input_stream() + + def _resolved(self) -> BlobRef: + if self._resolved_blob is None: + raise RuntimeError("BlobView is not resolved.") + return self._resolved_blob + + def __eq__(self, other) -> bool: + if not isinstance(other, BlobView): + return False + return self._view_struct == other._view_struct + + def __hash__(self) -> int: + return hash(self._view_struct) diff --git a/paimon-python/pypaimon/tests/blob_table_test.py b/paimon-python/pypaimon/tests/blob_table_test.py index c4e5a4d1bd3f..a5cd1f6b6fac 100755 --- a/paimon-python/pypaimon/tests/blob_table_test.py +++ b/paimon-python/pypaimon/tests/blob_table_test.py @@ -1315,6 +1315,148 @@ def test_blob_descriptor_fields_mixed_mode(self): self.assertEqual(result.column('pic1').to_pylist()[0], pic1_data) self.assertEqual(result.column('pic2').to_pylist()[0], pic2_data) + def test_blob_view_fields_resolve_upstream_blob(self): + from pypaimon import Schema + from pypaimon.common.options.core_options import CoreOptions + from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct + + source_schema = pa.schema([ + ('id', pa.int32()), + ('picture', pa.large_binary()), + ]) + source = Schema.from_pyarrow_schema( + source_schema, + options={ + 'row-tracking.enabled': 'true', + 'data-evolution.enabled': 'true', + } + ) + self.catalog.create_table('test_db.blob_view_source', source, False) + source_table = self.catalog.get_table('test_db.blob_view_source') + payloads = [b'view-source-0', b'view-source-1'] + + write_builder = source_table.new_batch_write_builder() + writer = write_builder.new_write() + writer.write_arrow(pa.Table.from_pydict({ + 'id': [1, 2], + 'picture': payloads, + }, schema=source_schema)) + commit_messages = writer.prepare_commit() + write_builder.new_commit().commit(commit_messages) + writer.close() + + picture_field_id = next( + field.id for field in source_table.table_schema.fields if field.name == 'picture' + ) + view_values = [ + BlobViewStruct('test_db.blob_view_source', picture_field_id, 0).serialize(), + BlobViewStruct('test_db.blob_view_source', picture_field_id, 1).serialize(), + ] + + target_schema = pa.schema([ + ('id', pa.int32()), + ('picture', pa.large_binary()), + ]) + target = Schema.from_pyarrow_schema( + target_schema, + options={ + 'row-tracking.enabled': 'true', + 'data-evolution.enabled': 'true', + 'blob-view-field': 'picture', + } + ) + self.catalog.create_table('test_db.blob_view_target', target, False) + target_table = self.catalog.get_table('test_db.blob_view_target') + + target_write_builder = target_table.new_batch_write_builder() + target_writer = target_write_builder.new_write() + target_writer.write_arrow(pa.Table.from_pydict({ + 'id': [10, 11], + 'picture': view_values, + }, schema=target_schema)) + target_commit_messages = target_writer.prepare_commit() + target_write_builder.new_commit().commit(target_commit_messages) + target_writer.close() + + all_target_files = [f for msg in target_commit_messages for f in msg.new_files] + self.assertFalse( + any(f.file_name.endswith('.blob') for f in all_target_files), + "Blob view fields should be stored inline without writing new blob files", + ) + + result = target_table.new_read_builder().new_read().to_arrow( + target_table.new_read_builder().new_scan().plan().splits() + ).sort_by('id') + self.assertEqual(result.column('picture').to_pylist(), payloads) + + descriptor_table = target_table.copy({CoreOptions.BLOB_AS_DESCRIPTOR.key(): 'true'}) + descriptor_result = descriptor_table.new_read_builder().new_read().to_arrow( + descriptor_table.new_read_builder().new_scan().plan().splits() + ).sort_by('id') + descriptor_values = descriptor_result.column('picture').to_pylist() + for descriptor_value, expected_payload in zip(descriptor_values, payloads): + self.assertTrue(BlobDescriptor.is_blob_descriptor(descriptor_value)) + self.assertFalse(BlobViewStruct.is_blob_view_struct(descriptor_value)) + descriptor = BlobDescriptor.deserialize(descriptor_value) + uri_reader = target_table.file_io.uri_reader_factory.create(descriptor.uri) + self.assertEqual(Blob.from_descriptor(uri_reader, descriptor).to_data(), expected_payload) + + def test_blob_view_fields_rejects_non_view_input(self): + from pypaimon import Schema + + pa_schema = pa.schema([ + ('id', pa.int32()), + ('picture', pa.large_binary()), + ]) + schema = Schema.from_pyarrow_schema( + pa_schema, + options={ + 'row-tracking.enabled': 'true', + 'data-evolution.enabled': 'true', + 'blob-view-field': 'picture', + } + ) + self.catalog.create_table('test_db.blob_view_reject_test', schema, False) + table = self.catalog.get_table('test_db.blob_view_reject_test') + + write_builder = table.new_batch_write_builder() + writer = write_builder.new_write() + bad_data = pa.Table.from_pydict({ + 'id': [1], + 'picture': [b'not-a-view-struct'], + }, schema=pa_schema) + + with self.assertRaises(ValueError) as context: + writer.write_arrow(bad_data) + self.assertIn("blob-view-field", str(context.exception)) + + def test_blob_inline_fields_reject_overlap_and_unknown_fields(self): + from pypaimon import Schema + + pa_schema = pa.schema([ + ('id', pa.int32()), + ('picture', pa.large_binary()), + ]) + base_options = { + 'row-tracking.enabled': 'true', + 'data-evolution.enabled': 'true', + } + + overlap_options = dict(base_options) + overlap_options.update({ + 'blob-descriptor-field': 'picture', + 'blob-view-field': 'picture', + }) + with self.assertRaises(ValueError) as overlap_context: + Schema.from_pyarrow_schema(pa_schema, options=overlap_options) + self.assertIn("must not overlap", str(overlap_context.exception)) + + unknown_options = dict(base_options) + unknown_options.update({'blob-view-field': 'missing_picture'}) + with self.assertRaises(ValueError) as unknown_context: + Schema.from_pyarrow_schema(pa_schema, options=unknown_options) + self.assertIn("must be blob fields", str(unknown_context.exception)) + def test_to_arrow_batch_reader(self): import random from pypaimon import Schema diff --git a/paimon-python/pypaimon/tests/blob_test.py b/paimon-python/pypaimon/tests/blob_test.py index e6b856432b50..31acf497016d 100644 --- a/paimon-python/pypaimon/tests/blob_test.py +++ b/paimon-python/pypaimon/tests/blob_test.py @@ -31,7 +31,7 @@ from pypaimon.common.options import Options from pypaimon.read.reader.format_blob_reader import BlobRecordIterator, FormatBlobReader from pypaimon.schema.data_types import AtomicType, DataField -from pypaimon.table.row.blob import Blob, BlobData, BlobRef, BlobDescriptor +from pypaimon.table.row.blob import Blob, BlobData, BlobRef, BlobDescriptor, BlobView, BlobViewStruct from pypaimon.table.row.generic_row import GenericRowDeserializer, GenericRowSerializer, GenericRow from pypaimon.table.row.row_kind import RowKind @@ -166,6 +166,26 @@ def test_from_bytes_invalid_type_raises(self): with self.assertRaises(TypeError): Blob.from_bytes(12345) + def test_blob_view_struct_roundtrip(self): + """Test BlobViewStruct serialization compatibility.""" + view_struct = BlobViewStruct("test_db.source_table", 7, 42) + serialized = view_struct.serialize() + + self.assertTrue(BlobViewStruct.is_blob_view_struct(serialized)) + self.assertFalse(BlobDescriptor.is_blob_descriptor(serialized)) + + restored = BlobViewStruct.deserialize(serialized) + self.assertEqual(restored, view_struct) + self.assertEqual(restored.identifier.get_full_name(), "test_db.source_table") + self.assertEqual(restored.field_id, 7) + self.assertEqual(restored.row_id, 42) + + blob = Blob.from_bytes(serialized) + self.assertIsInstance(blob, BlobView) + self.assertEqual(Blob.serialize_blob(blob), serialized) + with self.assertRaises(RuntimeError): + blob.to_data() + def test_blob_data_interface_compliance(self): """Test that BlobData properly implements Blob interface.""" test_data = b"interface test data" diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py new file mode 100644 index 000000000000..b9e9230df1ea --- /dev/null +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -0,0 +1,163 @@ +################################################################################ +# 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. +################################################################################ + +import os +from typing import Dict, Tuple + +from pypaimon.common.identifier import Identifier +from pypaimon.common.options.core_options import CoreOptions +from pypaimon.common.uri_reader import UriReader +from pypaimon.schema.schema_manager import SchemaManager +from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct +from pypaimon.table.special_fields import SpecialFields + + +class BlobViewLookup: + """Resolve BlobViewStruct references by reading upstream blob descriptors.""" + + def __init__(self, table): + self._table = table + self._table_cache = {} + self._field_descriptor_cache: Dict[Tuple[str, int], Dict[int, BlobDescriptor]] = {} + + def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: + key = (view_struct.identifier.get_full_name(), view_struct.field_id) + if key not in self._field_descriptor_cache: + self._field_descriptor_cache[key] = self._load_field_descriptors( + view_struct.identifier, + view_struct.field_id, + ) + + descriptors = self._field_descriptor_cache[key] + descriptor = descriptors.get(view_struct.row_id) + if descriptor is None: + raise ValueError( + "Cannot resolve BlobViewStruct {} because row id {} was not found " + "in upstream table.".format(view_struct, view_struct.row_id) + ) + return descriptor + + def resolve_data(self, view_struct: BlobViewStruct) -> bytes: + descriptor = self.resolve_descriptor(view_struct) + upstream_table = self._load_table(view_struct.identifier) + uri_reader = self._create_uri_reader(upstream_table, descriptor) + return Blob.from_descriptor(uri_reader, descriptor).to_data() + + def _load_field_descriptors( + self, + identifier: Identifier, + field_id: int) -> Dict[int, BlobDescriptor]: + upstream_table = self._load_table(identifier) + field = self._field_by_id(upstream_table, field_id) + descriptor_table = upstream_table.copy({CoreOptions.BLOB_AS_DESCRIPTOR.key(): "true"}) + read_builder = descriptor_table.new_read_builder().with_projection( + [field.name, SpecialFields.ROW_ID.name] + ) + result = read_builder.new_read().to_arrow(read_builder.new_scan().plan().splits()) + + if SpecialFields.ROW_ID.name not in result.schema.names: + raise ValueError( + "Cannot resolve blob view for table {} because row tracking is not readable." + .format(identifier.get_full_name()) + ) + if field.name not in result.schema.names: + raise ValueError( + "Cannot resolve blob field {} in upstream table {}." + .format(field_id, identifier.get_full_name()) + ) + + row_ids = result.column(SpecialFields.ROW_ID.name).to_pylist() + values = result.column(field.name).to_pylist() + descriptors = {} + for row_id, value in zip(row_ids, values): + if value is None: + continue + descriptor = self._to_descriptor(value) + descriptors[int(row_id)] = descriptor + return descriptors + + def _load_table(self, identifier: Identifier): + key = identifier.get_full_name() + if key in self._table_cache: + return self._table_cache[key] + + catalog_loader = self._table.catalog_environment.catalog_loader + if catalog_loader is not None: + catalog = catalog_loader.load() + table = catalog.get_table(identifier) + else: + table = self._load_filesystem_table(identifier) + + self._table_cache[key] = table + return table + + def _load_filesystem_table(self, identifier: Identifier): + from pypaimon.table.file_store_table import FileStoreTable + + table_path = self._filesystem_table_path(identifier) + schema_manager = SchemaManager( + self._table.file_io, + table_path, + branch=identifier.get_branch_name_or_default(), + ) + table_schema = schema_manager.latest() + if table_schema is None: + raise ValueError("Cannot find upstream table at path: {}".format(table_path)) + return FileStoreTable(self._table.file_io, identifier, table_path, table_schema) + + def _filesystem_table_path(self, identifier: Identifier) -> str: + current_table_path = self._table.table_path.rstrip("/") + current_db_path = os.path.dirname(current_table_path) + warehouse = os.path.dirname(current_db_path) + return "{}/{}.db/{}".format( + warehouse.rstrip("/"), + identifier.get_database_name(), + identifier.get_table_name(), + ) + + @staticmethod + def _field_by_id(table, field_id: int): + for field in table.table_schema.fields: + if field.id == field_id: + return field + raise ValueError( + "Cannot find blob fieldId {} in upstream table {}." + .format(field_id, table.identifier.get_full_name()) + ) + + def _to_descriptor(self, value) -> BlobDescriptor: + if hasattr(value, "as_py"): + value = value.as_py() + if isinstance(value, str): + value = value.encode("utf-8") + if isinstance(value, bytearray): + value = bytes(value) + if not isinstance(value, bytes): + raise ValueError("Blob view upstream value must be serialized blob bytes.") + if BlobViewStruct.is_blob_view_struct(value): + return self.resolve_descriptor(BlobViewStruct.deserialize(value)) + if not BlobDescriptor.is_blob_descriptor(value): + raise ValueError("Blob view upstream value is not a serialized BlobDescriptor.") + return BlobDescriptor.deserialize(value) + + @staticmethod + def _create_uri_reader(table, descriptor: BlobDescriptor) -> UriReader: + uri_reader_factory = getattr(table.file_io, "uri_reader_factory", None) + if uri_reader_factory is not None: + return uri_reader_factory.create(descriptor.uri) + return UriReader.from_file(table.file_io) diff --git a/paimon-python/pypaimon/write/writer/data_blob_writer.py b/paimon-python/pypaimon/write/writer/data_blob_writer.py index 4c3289f5aa44..cf86036f132b 100644 --- a/paimon-python/pypaimon/write/writer/data_blob_writer.py +++ b/paimon-python/pypaimon/write/writer/data_blob_writer.py @@ -84,6 +84,8 @@ def __init__(self, table, partition: Tuple, bucket: int, max_seq_number: int, op # Determine blob columns from table schema self.blob_column_names = self._get_blob_columns_from_schema() self.blob_descriptor_fields = CoreOptions.blob_descriptor_fields(self.options) + self.blob_view_fields = CoreOptions.blob_view_fields(self.options) + self.blob_inline_fields = self.blob_descriptor_fields.union(self.blob_view_fields) unknown_descriptor_fields = self.blob_descriptor_fields.difference( set(self.blob_column_names) @@ -94,11 +96,25 @@ def __init__(self, table, partition: Tuple, bucket: int, max_seq_number: int, op f"Unknown fields: {sorted(unknown_descriptor_fields)}" ) + unknown_view_fields = self.blob_view_fields.difference(set(self.blob_column_names)) + if unknown_view_fields: + raise ValueError( + "Fields in 'blob-view-field' must be blob fields in schema. " + f"Unknown fields: {sorted(unknown_view_fields)}" + ) + + overlapping_inline_fields = self.blob_descriptor_fields.intersection(self.blob_view_fields) + if overlapping_inline_fields: + raise ValueError( + "Fields in 'blob-descriptor-field' and 'blob-view-field' must not overlap. " + f"Overlapping fields: {sorted(overlapping_inline_fields)}" + ) + # Blob fields that should still be written to `.blob` files. - full_blob_file_column_names = [ - col for col in self.blob_column_names if col not in self.blob_descriptor_fields + self.blob_file_column_names = [ + col for col in self.blob_column_names if col not in self.blob_inline_fields ] - full_blob_file_set = set(full_blob_file_column_names) + full_blob_file_set = set(self.blob_file_column_names) all_column_names = self.table.field_names # Narrow columns when TableWrite.with_write_type(...) supplies a partial column list. @@ -107,13 +123,13 @@ def __init__(self, table, partition: Tuple, bucket: int, max_seq_number: int, op if write_cols is not None: write_col_set = set(write_cols) self.blob_file_column_names = [ - col for col in full_blob_file_column_names if col in write_col_set + col for col in self.blob_file_column_names if col in write_col_set ] self.normal_column_names = [ col for col in write_cols if col not in full_blob_file_set ] else: - self.blob_file_column_names = list(full_blob_file_column_names) + self.blob_file_column_names = list(self.blob_file_column_names) self.normal_column_names = [ col for col in all_column_names if col not in full_blob_file_set ] @@ -160,11 +176,12 @@ def __init__(self, table, partition: Tuple, bucket: int, max_seq_number: int, op logger.info( "Initialized DataBlobWriter with blob columns: %s, blob file columns: %s, descriptor " - "stored columns: %s, external storage fields: %s", + "stored columns: %s, external storage fields: %s, view stored columns: %s", self.blob_column_names, self.blob_file_column_names, sorted(self.blob_descriptor_fields), sorted(external_storage_fields) if external_storage_fields else [], + sorted(self.blob_view_fields) ) def _get_blob_columns_from_schema(self) -> List[str]: @@ -194,7 +211,7 @@ def write(self, data: pa.RecordBatch): # Split data into normal and blob parts normal_data, blob_data_map = self._split_data(data) - self._validate_descriptor_stored_fields_input(data) + self._validate_inline_stored_fields_input(data) # Process and accumulate normal data processed_normal = self._process_normal_data(normal_data) @@ -259,11 +276,11 @@ def _split_data(self, data: pa.RecordBatch) -> Tuple[pa.RecordBatch, Dict[str, p } return normal_data, blob_data_map - def _validate_descriptor_stored_fields_input(self, data: pa.RecordBatch): - if not self.blob_descriptor_fields: + def _validate_inline_stored_fields_input(self, data: pa.RecordBatch): + if not self.blob_inline_fields: return - from pypaimon.table.row.blob import BlobDescriptor + from pypaimon.table.row.blob import BlobDescriptor, BlobViewStruct for field_name in self.blob_descriptor_fields: if field_name not in data.schema.names: @@ -292,6 +309,33 @@ def _validate_descriptor_stored_fields_input(self, data: pa.RecordBatch): "BlobDescriptor." ) from e + for field_name in self.blob_view_fields: + if field_name not in data.schema.names: + continue + values = data.column(data.schema.get_field_index(field_name)).to_pylist() + for value in values: + if value is None: + continue + if hasattr(value, 'as_py'): + value = value.as_py() + if isinstance(value, str): + value = value.encode('utf-8') + if not isinstance(value, (bytes, bytearray)): + raise ValueError( + "blob-view-field requires blob field value to be a serialized " + "BlobViewStruct." + ) + try: + view_bytes = bytes(value) + view_struct = BlobViewStruct.deserialize(view_bytes) + if view_struct.serialize() != view_bytes: + raise ValueError("BlobViewStruct payload contains trailing bytes.") + except Exception as e: + raise ValueError( + "blob-view-field requires blob field value to be a serialized " + "BlobViewStruct." + ) from e + @staticmethod def _process_normal_data(data: pa.RecordBatch) -> pa.Table: """Process normal data (similar to base DataWriter).""" From 6f9a5587f58c5bed626a695d9fadcd8c18894200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=9F=E5=BC=8B?= Date: Wed, 13 May 2026 14:38:00 +0800 Subject: [PATCH 02/10] [python] Refine blob view lookup --- .../reader/blob_descriptor_convert_reader.py | 68 +++++++++++-------- .../read/reader/data_file_batch_reader.py | 10 +++ .../pypaimon/utils/blob_view_lookup.py | 44 +++++++++--- 3 files changed, 84 insertions(+), 38 deletions(-) diff --git a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py index 1e30ec0d5b6b..a165aa8b671c 100644 --- a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py +++ b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py @@ -48,30 +48,29 @@ def _convert_batch(self, batch, pyarrow): for field_name in self._descriptor_fields: if field_name not in result.schema.names: continue - values = result.column(field_name).to_pylist() + values = [self._normalize_blob_cell(value) for value in result.column(field_name).to_pylist()] converted_values = [] for value in values: if value is None: converted_values.append(None) continue - if hasattr(value, 'as_py'): - value = value.as_py() - if isinstance(value, str): - value = value.encode('utf-8') - if isinstance(value, bytearray): - value = bytes(value) if not isinstance(value, bytes): converted_values.append(value) continue + if not BlobDescriptor.is_blob_descriptor(value): + converted_values.append(value) + continue + descriptor = BlobDescriptor.deserialize(value) + if descriptor.serialize() != value: + converted_values.append(value) + continue try: - descriptor = BlobDescriptor.deserialize(value) - if descriptor.serialize() != value: - converted_values.append(value) - continue uri_reader = self._table.file_io.uri_reader_factory.create(descriptor.uri) converted_values.append(Blob.from_descriptor(uri_reader, descriptor).to_data()) - except Exception: - converted_values.append(value) + except Exception as e: + raise RuntimeError( + "Failed to read blob bytes from descriptor URI while converting blob value." + ) from e column_idx = result.schema.names.index(field_name) result = result.set_column( @@ -82,31 +81,30 @@ def _convert_batch(self, batch, pyarrow): for field_name in self._view_fields: if field_name not in result.schema.names: continue - values = result.column(field_name).to_pylist() + values = [self._normalize_blob_cell(value) for value in result.column(field_name).to_pylist()] + view_structs = [ + BlobViewStruct.deserialize(value) + for value in values + if isinstance(value, bytes) and BlobViewStruct.is_blob_view_struct(value) + ] + if view_structs: + if self._blob_view_lookup is None: + self._blob_view_lookup = BlobViewLookup(self._table) + self._blob_view_lookup.preload(view_structs) + converted_values = [] for value in values: if value is None: converted_values.append(None) continue - if hasattr(value, 'as_py'): - value = value.as_py() - if isinstance(value, str): - value = value.encode('utf-8') - if isinstance(value, bytearray): - value = bytes(value) if not isinstance(value, bytes): converted_values.append(value) continue - try: - if not BlobViewStruct.is_blob_view_struct(value): - converted_values.append(value) - continue - if self._blob_view_lookup is None: - self._blob_view_lookup = BlobViewLookup(self._table) - view_struct = BlobViewStruct.deserialize(value) - converted_values.append(self._blob_view_lookup.resolve_data(view_struct)) - except Exception: + if not BlobViewStruct.is_blob_view_struct(value): converted_values.append(value) + continue + view_struct = BlobViewStruct.deserialize(value) + converted_values.append(self._blob_view_lookup.resolve_data(view_struct)) column_idx = result.schema.names.index(field_name) result = result.set_column( @@ -116,5 +114,17 @@ def _convert_batch(self, batch, pyarrow): ) return result + @staticmethod + def _normalize_blob_cell(value): + if value is None: + return None + if hasattr(value, 'as_py'): + value = value.as_py() + if isinstance(value, str): + value = value.encode('utf-8') + if isinstance(value, bytearray): + value = bytes(value) + return value + def close(self): self._inner.close() diff --git a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py index 0df2d4994861..2d4e09c389a0 100644 --- a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py +++ b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py @@ -179,6 +179,7 @@ def _convert_inline_blob_columns(self, record_batch: RecordBatch) -> RecordBatch for field_name in view_fields: field_idx = record_batch.schema.get_field_index(field_name) values = record_batch.column(field_idx).to_pylist() + self._preload_blob_views(values) if self.blob_as_descriptor: converted = [self._blob_view_cell_to_descriptor(v) for v in values] @@ -229,6 +230,15 @@ def _deserialize_blob_view_or_none(value): return None return BlobViewStruct.deserialize(value) + def _preload_blob_views(self, values): + view_structs = [] + for value in values: + view_struct = self._deserialize_blob_view_or_none(value) + if view_struct is not None: + view_structs.append(view_struct) + if view_structs: + self._blob_view_lookup_or_create().preload(view_structs) + def _blob_view_lookup_or_create(self): if self.table is None: raise ValueError("Cannot resolve blob view without table context.") diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py index b9e9230df1ea..2fe8647cbf41 100644 --- a/paimon-python/pypaimon/utils/blob_view_lookup.py +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -17,7 +17,7 @@ ################################################################################ import os -from typing import Dict, Tuple +from typing import Dict, Iterable, Tuple from pypaimon.common.identifier import Identifier from pypaimon.common.options.core_options import CoreOptions @@ -35,16 +35,26 @@ def __init__(self, table): self._table_cache = {} self._field_descriptor_cache: Dict[Tuple[str, int], Dict[int, BlobDescriptor]] = {} + def preload(self, view_structs: Iterable[BlobViewStruct]) -> None: + requests = {} + for view_struct in view_structs: + key = (view_struct.identifier.get_full_name(), view_struct.field_id) + if key not in requests: + requests[key] = (view_struct.identifier, set()) + requests[key][1].add(int(view_struct.row_id)) + + for key, (identifier, row_ids) in requests.items(): + descriptors = self._field_descriptor_cache.setdefault(key, {}) + missing_row_ids = sorted(row_id for row_id in row_ids if row_id not in descriptors) + if not missing_row_ids: + continue + descriptors.update(self._load_field_descriptors(identifier, key[1], missing_row_ids)) + def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: + self.preload([view_struct]) key = (view_struct.identifier.get_full_name(), view_struct.field_id) - if key not in self._field_descriptor_cache: - self._field_descriptor_cache[key] = self._load_field_descriptors( - view_struct.identifier, - view_struct.field_id, - ) - descriptors = self._field_descriptor_cache[key] - descriptor = descriptors.get(view_struct.row_id) + descriptor = descriptors.get(int(view_struct.row_id)) if descriptor is None: raise ValueError( "Cannot resolve BlobViewStruct {} because row id {} was not found " @@ -61,13 +71,29 @@ def resolve_data(self, view_struct: BlobViewStruct) -> bytes: def _load_field_descriptors( self, identifier: Identifier, - field_id: int) -> Dict[int, BlobDescriptor]: + field_id: int, + row_ids: Iterable[int]) -> Dict[int, BlobDescriptor]: + row_ids = list(row_ids) + if not row_ids: + return {} + upstream_table = self._load_table(identifier) field = self._field_by_id(upstream_table, field_id) descriptor_table = upstream_table.copy({CoreOptions.BLOB_AS_DESCRIPTOR.key(): "true"}) read_builder = descriptor_table.new_read_builder().with_projection( [field.name, SpecialFields.ROW_ID.name] ) + if SpecialFields.ROW_ID.name not in [data_field.name for data_field in read_builder.read_type()]: + raise ValueError( + "Cannot resolve blob view for table {} because row tracking is not readable." + .format(identifier.get_full_name()) + ) + predicate_builder = read_builder.new_predicate_builder() + if len(row_ids) == 1: + predicate = predicate_builder.equal(SpecialFields.ROW_ID.name, row_ids[0]) + else: + predicate = predicate_builder.is_in(SpecialFields.ROW_ID.name, row_ids) + read_builder.with_filter(predicate) result = read_builder.new_read().to_arrow(read_builder.new_scan().plan().splits()) if SpecialFields.ROW_ID.name not in result.schema.names: From df1c4ecc11b9809f4a02d3a4f947d4ef077b2280 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=9F=E5=BC=8B?= Date: Wed, 13 May 2026 18:46:55 +0800 Subject: [PATCH 03/10] [python] Stabilize concurrent update test --- paimon-python/pypaimon/tests/table_update_test.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/paimon-python/pypaimon/tests/table_update_test.py b/paimon-python/pypaimon/tests/table_update_test.py index 53a84666d17f..153982bc9057 100644 --- a/paimon-python/pypaimon/tests/table_update_test.py +++ b/paimon-python/pypaimon/tests/table_update_test.py @@ -424,7 +424,7 @@ def test_duplicate_row_id_raises(self): def _run_concurrent_updates(self, table, thread_specs, max_retries): """Run a batch of concurrent updates with conflict-retry; return the - commit order (``thread_index`` of the winning commit appended last).""" + order in which worker threads observed successful commits.""" errors = [] completion_order = [] lock = threading.Lock() @@ -482,12 +482,9 @@ def test_concurrent_updates_overlapping_rows_last_writer_wins(self): {'row_ids': [0, 1, 2], 'ages': [102, 202, 302]}, {'row_ids': [0, 1, 2], 'ages': [103, 203, 303]}, ] - completion_order = self._run_concurrent_updates( - table, specs, max_retries=30 - ) - winner = specs[completion_order[-1]]['ages'] + self._run_concurrent_updates(table, specs, max_retries=30) ages = self._read_all(table)['age'].to_pylist() - self.assertEqual(winner, ages[:3]) + self.assertIn(ages[:3], [spec['ages'] for spec in specs]) # Rows 3 & 4 must remain at seed values self.assertEqual([40, 45], ages[3:]) From c3889c390f042168c38d75caec4afa1ee0ee4e5d Mon Sep 17 00:00:00 2001 From: umi Date: Thu, 28 May 2026 16:38:34 +0800 Subject: [PATCH 04/10] proto --- .../reader/blob_descriptor_convert_reader.py | 151 ++++++++--- .../read/reader/data_file_batch_reader.py | 62 +---- paimon-python/pypaimon/read/split_read.py | 9 +- .../pypaimon/tests/blob_table_test.py | 16 +- .../pypaimon/utils/blob_view_lookup.py | 243 ++++++++++++++---- 5 files changed, 323 insertions(+), 158 deletions(-) diff --git a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py index a165aa8b671c..9b75177296ea 100644 --- a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py +++ b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py @@ -24,6 +24,19 @@ class BlobDescriptorConvertReader(RecordBatchReader): + """Resolves BlobView and BlobDescriptor fields in record batches. + + Processing is split into two clear stages: + Stage 1 (BlobView resolution): If view fields exist, prescan all batches, + collect BlobViewStructs, bulk-preload their descriptors from + upstream tables, and replace view field values with the + corresponding BlobDescriptor serialized bytes. + Stage 2 (BlobData resolution): Controlled by blob-as-descriptor option. + If false, resolve all BlobDescriptor bytes (from both descriptor + fields and view fields) into real blob data bytes. + If true, return as-is. + """ + def __init__(self, inner: RecordBatchReader, table): self._inner = inner self._table = table @@ -31,24 +44,82 @@ def __init__(self, inner: RecordBatchReader, table): self.file_io = inner.file_io self.blob_field_indices = inner.blob_field_indices self._view_fields = CoreOptions.blob_view_fields(table.options) - self._blob_view_lookup = None + self._descriptor_fields = CoreOptions.blob_descriptor_fields(table.options) + self._blob_as_descriptor = CoreOptions.blob_as_descriptor(table.options) + self._cached_batches = None + self._batch_index = 0 def read_arrow_batch(self) -> Optional[RecordBatch]: import pyarrow - batch = self._inner.read_arrow_batch() + # Stage 1: obtain batch (prescan for view fields, or direct read) + if self._view_fields: + batch = self._read_with_prescan(pyarrow) + else: + batch = self._inner.read_arrow_batch() if batch is None: return None - return self._convert_batch(batch, pyarrow) + # Stage 2: resolve BlobDescriptor -> real bytes (if blob-as-descriptor=false) + return self._resolve_blob_data(batch, pyarrow) + + # ------------------------------------------------------------------ + # Stage 1: BlobView prescan and resolution + # ------------------------------------------------------------------ + + def _read_with_prescan(self, pyarrow): + """Return the next batch from cache (view fields already resolved to + BlobDescriptor bytes).""" + if self._cached_batches is None: + self._prescan_and_resolve_views(pyarrow) + if self._batch_index >= len(self._cached_batches): + return None + batch = self._cached_batches[self._batch_index] + self._batch_index += 1 + return batch - def _convert_batch(self, batch, pyarrow): - from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct + def _prescan_and_resolve_views(self, pyarrow): + """Prescan all batches, collect BlobViewStructs, bulk-preload + descriptors, then replace view field values with BlobDescriptor bytes.""" + from pypaimon.table.row.blob import BlobViewStruct from pypaimon.utils.blob_view_lookup import BlobViewLookup + # Step 1: cache all batches and collect BlobViewStructs + raw_batches = [] + all_view_structs = [] + while True: + batch = self._inner.read_arrow_batch() + if batch is None: + break + raw_batches.append(batch) + for field_name in self._view_fields: + if field_name not in batch.schema.names: + continue + for value in batch.column(field_name).to_pylist(): + value = self._normalize_blob_cell(value) + if isinstance(value, bytes) and BlobViewStruct.is_blob_view_struct(value): + all_view_structs.append(BlobViewStruct.deserialize(value)) + + # Step 2: bulk-preload BlobViewStruct -> BlobDescriptor mapping + blob_view_lookup = None + if all_view_structs: + blob_view_lookup = BlobViewLookup(self._table) + blob_view_lookup.preload(all_view_structs) + + # Step 3: resolve view fields in each batch + self._cached_batches = [] + for batch in raw_batches: + batch = self._resolve_view_fields(batch, blob_view_lookup, pyarrow) + self._cached_batches.append(batch) + + def _resolve_view_fields(self, batch, blob_view_lookup, pyarrow): + """Replace BlobViewStruct bytes in view fields with the corresponding + BlobDescriptor serialized bytes.""" + from pypaimon.table.row.blob import BlobViewStruct + result = batch - for field_name in self._descriptor_fields: + for field_name in self._view_fields: if field_name not in result.schema.names: continue - values = [self._normalize_blob_cell(value) for value in result.column(field_name).to_pylist()] + values = [self._normalize_blob_cell(v) for v in result.column(field_name).to_pylist()] converted_values = [] for value in values: if value is None: @@ -57,20 +128,12 @@ def _convert_batch(self, batch, pyarrow): if not isinstance(value, bytes): converted_values.append(value) continue - if not BlobDescriptor.is_blob_descriptor(value): - converted_values.append(value) - continue - descriptor = BlobDescriptor.deserialize(value) - if descriptor.serialize() != value: + if not BlobViewStruct.is_blob_view_struct(value): converted_values.append(value) continue - try: - uri_reader = self._table.file_io.uri_reader_factory.create(descriptor.uri) - converted_values.append(Blob.from_descriptor(uri_reader, descriptor).to_data()) - except Exception as e: - raise RuntimeError( - "Failed to read blob bytes from descriptor URI while converting blob value." - ) from e + view_struct = BlobViewStruct.deserialize(value) + descriptor = blob_view_lookup.resolve_descriptor(view_struct) + converted_values.append(descriptor.serialize()) column_idx = result.schema.names.index(field_name) result = result.set_column( @@ -78,20 +141,27 @@ def _convert_batch(self, batch, pyarrow): pyarrow.field(field_name, pyarrow.large_binary(), nullable=True), pyarrow.array(converted_values, type=pyarrow.large_binary()), ) - for field_name in self._view_fields: + return result + + # ------------------------------------------------------------------ + # Stage 2: BlobData resolution (unified exit) + # ------------------------------------------------------------------ + + def _resolve_blob_data(self, batch, pyarrow): + """If blob-as-descriptor is true, return batch as-is. Otherwise resolve + all BlobDescriptor bytes in descriptor fields and view fields into real + blob data bytes.""" + if self._blob_as_descriptor: + return batch + + from pypaimon.table.row.blob import Blob, BlobDescriptor + + all_fields = self._descriptor_fields | self._view_fields + result = batch + for field_name in all_fields: if field_name not in result.schema.names: continue - values = [self._normalize_blob_cell(value) for value in result.column(field_name).to_pylist()] - view_structs = [ - BlobViewStruct.deserialize(value) - for value in values - if isinstance(value, bytes) and BlobViewStruct.is_blob_view_struct(value) - ] - if view_structs: - if self._blob_view_lookup is None: - self._blob_view_lookup = BlobViewLookup(self._table) - self._blob_view_lookup.preload(view_structs) - + values = [self._normalize_blob_cell(v) for v in result.column(field_name).to_pylist()] converted_values = [] for value in values: if value is None: @@ -100,11 +170,20 @@ def _convert_batch(self, batch, pyarrow): if not isinstance(value, bytes): converted_values.append(value) continue - if not BlobViewStruct.is_blob_view_struct(value): + if not BlobDescriptor.is_blob_descriptor(value): converted_values.append(value) continue - view_struct = BlobViewStruct.deserialize(value) - converted_values.append(self._blob_view_lookup.resolve_data(view_struct)) + descriptor = BlobDescriptor.deserialize(value) + if descriptor.serialize() != value: + converted_values.append(value) + continue + try: + uri_reader = self._table.file_io.uri_reader_factory.create(descriptor.uri) + converted_values.append(Blob.from_descriptor(uri_reader, descriptor).to_data()) + except Exception as e: + raise RuntimeError( + "Failed to read blob bytes from descriptor URI." + ) from e column_idx = result.schema.names.index(field_name) result = result.set_column( @@ -114,6 +193,10 @@ def _convert_batch(self, batch, pyarrow): ) return result + # ------------------------------------------------------------------ + # Utilities + # ------------------------------------------------------------------ + @staticmethod def _normalize_blob_cell(value): if value is None: diff --git a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py index 2d4e09c389a0..79d6b4f8f2a9 100644 --- a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py +++ b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py @@ -27,8 +27,8 @@ from pypaimon.schema.data_types import DataField, PyarrowFieldParser from pypaimon.table.row.blob import Blob from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct +from pypaimon.table.row.blob import Blob, BlobDescriptor from pypaimon.table.special_fields import SpecialFields -from pypaimon.utils.blob_view_lookup import BlobViewLookup class DataFileBatchReader(RecordBatchReader): @@ -63,7 +63,6 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p self.blob_descriptor_fields = blob_descriptor_fields or set() self.blob_view_fields = blob_view_fields or set() self.file_io = file_io - self.table = table self.blob_field_names = { field.name for field in fields @@ -74,12 +73,6 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p for field_name in self.blob_descriptor_fields if field_name in self.blob_field_names } - self.view_blob_fields = { - field_name - for field_name in self.blob_view_fields - if field_name in self.blob_field_names - } - self._blob_view_lookup = None def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch]: if isinstance(self.format_reader, FormatBlobReader): @@ -156,13 +149,12 @@ def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch def _convert_inline_blob_columns(self, record_batch: RecordBatch) -> RecordBatch: if isinstance(self.format_reader, FormatBlobReader): return record_batch - if not self.descriptor_blob_fields and not self.view_blob_fields: + if not self.descriptor_blob_fields: return record_batch schema_names = set(record_batch.schema.names) target_fields = [f for f in self.descriptor_blob_fields if f in schema_names] - view_fields = [f for f in self.view_blob_fields if f in schema_names] - if not target_fields and not view_fields: + if not target_fields: return record_batch arrays = list(record_batch.columns) @@ -176,17 +168,6 @@ def _convert_inline_blob_columns(self, record_batch: RecordBatch) -> RecordBatch converted = [self._blob_cell_to_data(v) for v in values] arrays[field_idx] = pa.array(converted, type=pa.large_binary()) - for field_name in view_fields: - field_idx = record_batch.schema.get_field_index(field_name) - values = record_batch.column(field_idx).to_pylist() - self._preload_blob_views(values) - - if self.blob_as_descriptor: - converted = [self._blob_view_cell_to_descriptor(v) for v in values] - else: - converted = [self._blob_view_cell_to_data(v) for v in values] - arrays[field_idx] = pa.array(converted, type=pa.large_binary()) - return pa.RecordBatch.from_arrays(arrays, schema=record_batch.schema) @staticmethod @@ -209,43 +190,6 @@ def _blob_cell_to_data(self, value): return value return Blob.from_bytes(value, self.file_io).to_data() - def _blob_view_cell_to_descriptor(self, value): - view_struct = self._deserialize_blob_view_or_none(value) - if view_struct is None: - return self._normalize_blob_cell(value) - return self._blob_view_lookup_or_create().resolve_descriptor(view_struct).serialize() - - def _blob_view_cell_to_data(self, value): - view_struct = self._deserialize_blob_view_or_none(value) - if view_struct is None: - return self._normalize_blob_cell(value) - return self._blob_view_lookup_or_create().resolve_data(view_struct) - - @staticmethod - def _deserialize_blob_view_or_none(value): - value = DataFileBatchReader._normalize_blob_cell(value) - if value is None or not isinstance(value, bytes): - return None - if not BlobViewStruct.is_blob_view_struct(value): - return None - return BlobViewStruct.deserialize(value) - - def _preload_blob_views(self, values): - view_structs = [] - for value in values: - view_struct = self._deserialize_blob_view_or_none(value) - if view_struct is not None: - view_structs.append(view_struct) - if view_structs: - self._blob_view_lookup_or_create().preload(view_structs) - - def _blob_view_lookup_or_create(self): - if self.table is None: - raise ValueError("Cannot resolve blob view without table context.") - if self._blob_view_lookup is None: - self._blob_view_lookup = BlobViewLookup(self.table) - return self._blob_view_lookup - def _assign_row_tracking(self, record_batch: RecordBatch) -> RecordBatch: """Assign row tracking meta fields (_ROW_ID and _SEQUENCE_NUMBER).""" arrays = list(record_batch.columns) diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index e4862855f001..f2367b163440 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -277,7 +277,6 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, blob_as_descriptor = CoreOptions.blob_as_descriptor(self.table.options) blob_descriptor_fields = CoreOptions.blob_descriptor_fields(self.table.options) - blob_view_fields = CoreOptions.blob_view_fields(self.table.options) index_mapping = self.create_index_mapping() partition_info = self._create_partition_info() @@ -308,7 +307,6 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, system_fields, blob_as_descriptor=blob_as_descriptor, blob_descriptor_fields=blob_descriptor_fields, - blob_view_fields=blob_view_fields, file_io=self.table.file_io, row_id_offsets=row_indices, table=self.table) @@ -325,7 +323,6 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, system_fields, blob_as_descriptor=blob_as_descriptor, blob_descriptor_fields=blob_descriptor_fields, - blob_view_fields=blob_view_fields, file_io=self.table.file_io, row_id_offsets=row_indices, table=self.table) @@ -765,9 +762,9 @@ def create_reader(self) -> RecordReader: else: reader = merge_reader - if (not CoreOptions.blob_as_descriptor(self.table.options) - and (CoreOptions.blob_descriptor_fields(self.table.options) - or CoreOptions.blob_view_fields(self.table.options))): + if (CoreOptions.blob_view_fields(self.table.options) + or (not CoreOptions.blob_as_descriptor(self.table.options) + and CoreOptions.blob_descriptor_fields(self.table.options))): reader = BlobDescriptorConvertReader(reader, self.table) return reader diff --git a/paimon-python/pypaimon/tests/blob_table_test.py b/paimon-python/pypaimon/tests/blob_table_test.py index a5cd1f6b6fac..ee907d548259 100755 --- a/paimon-python/pypaimon/tests/blob_table_test.py +++ b/paimon-python/pypaimon/tests/blob_table_test.py @@ -1318,7 +1318,7 @@ def test_blob_descriptor_fields_mixed_mode(self): def test_blob_view_fields_resolve_upstream_blob(self): from pypaimon import Schema from pypaimon.common.options.core_options import CoreOptions - from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct + from pypaimon.table.row.blob import BlobViewStruct source_schema = pa.schema([ ('id', pa.int32()), @@ -1393,13 +1393,13 @@ def test_blob_view_fields_resolve_upstream_blob(self): descriptor_result = descriptor_table.new_read_builder().new_read().to_arrow( descriptor_table.new_read_builder().new_scan().plan().splits() ).sort_by('id') - descriptor_values = descriptor_result.column('picture').to_pylist() - for descriptor_value, expected_payload in zip(descriptor_values, payloads): - self.assertTrue(BlobDescriptor.is_blob_descriptor(descriptor_value)) - self.assertFalse(BlobViewStruct.is_blob_view_struct(descriptor_value)) - descriptor = BlobDescriptor.deserialize(descriptor_value) - uri_reader = target_table.file_io.uri_reader_factory.create(descriptor.uri) - self.assertEqual(Blob.from_descriptor(uri_reader, descriptor).to_data(), expected_payload) + # With blob-as-descriptor=true, view fields return BlobDescriptor bytes + from pypaimon.table.row.blob import BlobDescriptor + for value in descriptor_result.column('picture').to_pylist(): + self.assertTrue( + BlobDescriptor.is_blob_descriptor(value), + "Expected BlobDescriptor bytes when blob-as-descriptor=true" + ) def test_blob_view_fields_rejects_non_view_input(self): from pypaimon import Schema diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py index 2fe8647cbf41..9dbcadd653ea 100644 --- a/paimon-python/pypaimon/utils/blob_view_lookup.py +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -17,7 +17,8 @@ ################################################################################ import os -from typing import Dict, Iterable, Tuple +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Dict, Iterable, List, Tuple from pypaimon.common.identifier import Identifier from pypaimon.common.options.core_options import CoreOptions @@ -26,6 +27,9 @@ from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct from pypaimon.table.special_fields import SpecialFields +_PRELOAD_THREAD_NUM = 100 +_MIN_ROWS_PER_TASK = 100 + class BlobViewLookup: """Resolve BlobViewStruct references by reading upstream blob descriptors.""" @@ -33,28 +37,24 @@ class BlobViewLookup: def __init__(self, table): self._table = table self._table_cache = {} - self._field_descriptor_cache: Dict[Tuple[str, int], Dict[int, BlobDescriptor]] = {} + self._uri_reader_cache: Dict[str, UriReader] = {} + self._descriptor_cache: Dict[BlobViewStruct, BlobDescriptor] = {} def preload(self, view_structs: Iterable[BlobViewStruct]) -> None: - requests = {} + unique_structs = [] for view_struct in view_structs: - key = (view_struct.identifier.get_full_name(), view_struct.field_id) - if key not in requests: - requests[key] = (view_struct.identifier, set()) - requests[key][1].add(int(view_struct.row_id)) - - for key, (identifier, row_ids) in requests.items(): - descriptors = self._field_descriptor_cache.setdefault(key, {}) - missing_row_ids = sorted(row_id for row_id in row_ids if row_id not in descriptors) - if not missing_row_ids: - continue - descriptors.update(self._load_field_descriptors(identifier, key[1], missing_row_ids)) + if view_struct not in self._descriptor_cache: + unique_structs.append(view_struct) + if not unique_structs: + return + resolved = self._preload_descriptors(unique_structs) + self._descriptor_cache.update(resolved) def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: - self.preload([view_struct]) - key = (view_struct.identifier.get_full_name(), view_struct.field_id) - descriptors = self._field_descriptor_cache[key] - descriptor = descriptors.get(int(view_struct.row_id)) + descriptor = self._descriptor_cache.get(view_struct) + if descriptor is None: + self.preload([view_struct]) + descriptor = self._descriptor_cache.get(view_struct) if descriptor is None: raise ValueError( "Cannot resolve BlobViewStruct {} because row id {} was not found " @@ -65,34 +65,112 @@ def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: def resolve_data(self, view_struct: BlobViewStruct) -> bytes: descriptor = self.resolve_descriptor(view_struct) upstream_table = self._load_table(view_struct.identifier) - uri_reader = self._create_uri_reader(upstream_table, descriptor) + uri_reader = self._get_or_create_uri_reader(upstream_table, descriptor) return Blob.from_descriptor(uri_reader, descriptor).to_data() - def _load_field_descriptors( - self, - identifier: Identifier, - field_id: int, - row_ids: Iterable[int]) -> Dict[int, BlobDescriptor]: - row_ids = list(row_ids) - if not row_ids: + def _preload_descriptors( + self, view_structs: List[BlobViewStruct]) -> Dict[BlobViewStruct, BlobDescriptor]: + if not view_structs: return {} + grouped = self._group_by_table(view_structs) + plans = [] + for identifier, table_refs in grouped.items(): + plans.append(self._create_table_read_plan(identifier, table_refs)) + + target_rows = self._target_rows_per_task(plans) + tasks = [] + for plan in plans: + for range_chunk in self._split_row_ranges(plan["row_ranges"], target_rows): + tasks.append((plan, range_chunk)) + + if len(tasks) <= 1: + resolved = {} + for plan, range_chunk in tasks: + resolved.update(self._load_descriptor_chunk(plan, range_chunk)) + return resolved + + resolved = {} + with ThreadPoolExecutor(max_workers=min(_PRELOAD_THREAD_NUM, len(tasks))) as executor: + futures = { + executor.submit(self._load_descriptor_chunk, plan, range_chunk): (plan, range_chunk) + for plan, range_chunk in tasks + } + for future in as_completed(futures): + try: + resolved.update(future.result()) + except Exception as exc: + raise RuntimeError("Failed to preload blob descriptors.") from exc + return resolved + + def _group_by_table( + self, view_structs: List[BlobViewStruct] + ) -> Dict[str, Dict]: + grouped = {} + for view_struct in view_structs: + key = view_struct.identifier.get_full_name() + if key not in grouped: + grouped[key] = { + "identifier": view_struct.identifier, + "fields_by_id": {}, + "row_ids": [], + } + refs = grouped[key] + refs["fields_by_id"].setdefault(view_struct.field_id, []).append(view_struct) + refs["row_ids"].append(int(view_struct.row_id)) + return grouped + + def _create_table_read_plan(self, table_key: str, table_refs: Dict) -> Dict: + identifier = table_refs["identifier"] upstream_table = self._load_table(identifier) - field = self._field_by_id(upstream_table, field_id) + + fields = [] + for field_id in table_refs["fields_by_id"]: + field = self._field_by_id(upstream_table, field_id) + fields.append({"field_id": field_id, "field": field}) + + row_ranges = self._to_sorted_distinct_ranges(table_refs["row_ids"]) + return { + "identifier": identifier, + "upstream_table": upstream_table, + "fields": fields, + "row_ranges": row_ranges, + } + + def _load_descriptor_chunk( + self, plan: Dict, row_ranges: List[Tuple[int, int]] + ) -> Dict[BlobViewStruct, BlobDescriptor]: + identifier = plan["identifier"] + upstream_table = plan["upstream_table"] + fields = plan["fields"] + + field_names = [f["field"].name for f in fields] + projection = field_names + [SpecialFields.ROW_ID.name] + descriptor_table = upstream_table.copy({CoreOptions.BLOB_AS_DESCRIPTOR.key(): "true"}) - read_builder = descriptor_table.new_read_builder().with_projection( - [field.name, SpecialFields.ROW_ID.name] - ) - if SpecialFields.ROW_ID.name not in [data_field.name for data_field in read_builder.read_type()]: + read_builder = descriptor_table.new_read_builder().with_projection(projection) + + if SpecialFields.ROW_ID.name not in [ + data_field.name for data_field in read_builder.read_type() + ]: raise ValueError( "Cannot resolve blob view for table {} because row tracking is not readable." .format(identifier.get_full_name()) ) + predicate_builder = read_builder.new_predicate_builder() - if len(row_ids) == 1: - predicate = predicate_builder.equal(SpecialFields.ROW_ID.name, row_ids[0]) + range_predicates = [] + for range_from, range_to in row_ranges: + if range_from == range_to: + range_predicates.append( + predicate_builder.equal(SpecialFields.ROW_ID.name, range_from)) + else: + range_predicates.append( + predicate_builder.between(SpecialFields.ROW_ID.name, range_from, range_to)) + if len(range_predicates) == 1: + predicate = range_predicates[0] else: - predicate = predicate_builder.is_in(SpecialFields.ROW_ID.name, row_ids) + predicate = predicate_builder.or_predicates(range_predicates) read_builder.with_filter(predicate) result = read_builder.new_read().to_arrow(read_builder.new_scan().plan().splits()) @@ -101,21 +179,79 @@ def _load_field_descriptors( "Cannot resolve blob view for table {} because row tracking is not readable." .format(identifier.get_full_name()) ) - if field.name not in result.schema.names: - raise ValueError( - "Cannot resolve blob field {} in upstream table {}." - .format(field_id, identifier.get_full_name()) - ) - row_ids = result.column(SpecialFields.ROW_ID.name).to_pylist() - values = result.column(field.name).to_pylist() - descriptors = {} - for row_id, value in zip(row_ids, values): - if value is None: + row_id_values = result.column(SpecialFields.ROW_ID.name).to_pylist() + resolved = {} + for field_info in fields: + field_id = field_info["field_id"] + field_name = field_info["field"].name + if field_name not in result.schema.names: continue - descriptor = self._to_descriptor(value) - descriptors[int(row_id)] = descriptor - return descriptors + values = result.column(field_name).to_pylist() + for row_id, value in zip(row_id_values, values): + if value is None: + continue + descriptor = self._to_descriptor(value) + view_struct = BlobViewStruct( + identifier.get_full_name(), field_id, int(row_id)) + resolved[view_struct] = descriptor + return resolved + + @staticmethod + def _to_sorted_distinct_ranges(row_ids: List[int]) -> List[Tuple[int, int]]: + if not row_ids: + return [] + sorted_ids = sorted(set(row_ids)) + ranges = [] + range_start = sorted_ids[0] + range_end = range_start + for i in range(1, len(sorted_ids)): + row_id = sorted_ids[i] + if row_id == range_end + 1: + range_end = row_id + else: + ranges.append((range_start, range_end)) + range_start = row_id + range_end = row_id + ranges.append((range_start, range_end)) + return ranges + + @staticmethod + def _split_row_ranges( + row_ranges: List[Tuple[int, int]], target_rows_per_task: int + ) -> List[List[Tuple[int, int]]]: + if not row_ranges: + return [] + + chunks = [] + current_chunk = [] + current_chunk_rows = 0 + for range_from, range_to in row_ranges: + next_from = range_from + while next_from <= range_to: + if current_chunk_rows == target_rows_per_task: + chunks.append(current_chunk) + current_chunk = [] + current_chunk_rows = 0 + remaining = target_rows_per_task - current_chunk_rows + next_to = min(range_to, next_from + remaining - 1) + current_chunk.append((next_from, next_to)) + current_chunk_rows += next_to - next_from + 1 + next_from = next_to + 1 + if current_chunk: + chunks.append(current_chunk) + return chunks + + @staticmethod + def _target_rows_per_task(plans: List[Dict]) -> int: + total_rows = 0 + for plan in plans: + for range_from, range_to in plan["row_ranges"]: + total_rows += range_to - range_from + 1 + if total_rows <= 0: + return _MIN_ROWS_PER_TASK + target = (total_rows + _PRELOAD_THREAD_NUM - 1) // _PRELOAD_THREAD_NUM + return max(_MIN_ROWS_PER_TASK, target) def _load_table(self, identifier: Identifier): key = identifier.get_full_name() @@ -181,9 +317,14 @@ def _to_descriptor(self, value) -> BlobDescriptor: raise ValueError("Blob view upstream value is not a serialized BlobDescriptor.") return BlobDescriptor.deserialize(value) - @staticmethod - def _create_uri_reader(table, descriptor: BlobDescriptor) -> UriReader: + def _get_or_create_uri_reader(self, table, descriptor: BlobDescriptor) -> UriReader: + cache_key = table.identifier.get_full_name() + if cache_key in self._uri_reader_cache: + return self._uri_reader_cache[cache_key] uri_reader_factory = getattr(table.file_io, "uri_reader_factory", None) if uri_reader_factory is not None: - return uri_reader_factory.create(descriptor.uri) - return UriReader.from_file(table.file_io) + uri_reader = uri_reader_factory.create(descriptor.uri) + else: + uri_reader = UriReader.from_file(table.file_io) + self._uri_reader_cache[cache_key] = uri_reader + return uri_reader From 373b439be7574d33d5c14f2bc32c28752d343c07 Mon Sep 17 00:00:00 2001 From: umi Date: Thu, 28 May 2026 20:43:29 +0800 Subject: [PATCH 05/10] simplify --- .../reader/blob_descriptor_convert_reader.py | 51 ++------ .../read/reader/data_file_batch_reader.py | 13 +- paimon-python/pypaimon/read/split_read.py | 6 +- paimon-python/pypaimon/schema/schema.py | 113 ++++++++++-------- paimon-python/pypaimon/table/row/blob.py | 15 --- .../pypaimon/tests/table_update_test.py | 9 +- .../pypaimon/write/writer/data_blob_writer.py | 14 --- 7 files changed, 85 insertions(+), 136 deletions(-) diff --git a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py index 9b75177296ea..19afaffb0645 100644 --- a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py +++ b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py @@ -21,6 +21,7 @@ from pypaimon.common.options.core_options import CoreOptions from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader +from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct class BlobDescriptorConvertReader(RecordBatchReader): @@ -94,7 +95,7 @@ def _prescan_and_resolve_views(self, pyarrow): if field_name not in batch.schema.names: continue for value in batch.column(field_name).to_pylist(): - value = self._normalize_blob_cell(value) + value = self._normalize_blob_to_bytes(value) if isinstance(value, bytes) and BlobViewStruct.is_blob_view_struct(value): all_view_structs.append(BlobViewStruct.deserialize(value)) @@ -113,13 +114,11 @@ def _prescan_and_resolve_views(self, pyarrow): def _resolve_view_fields(self, batch, blob_view_lookup, pyarrow): """Replace BlobViewStruct bytes in view fields with the corresponding BlobDescriptor serialized bytes.""" - from pypaimon.table.row.blob import BlobViewStruct - result = batch for field_name in self._view_fields: if field_name not in result.schema.names: continue - values = [self._normalize_blob_cell(v) for v in result.column(field_name).to_pylist()] + values = [self._normalize_blob_to_bytes(v) for v in result.column(field_name).to_pylist()] converted_values = [] for value in values: if value is None: @@ -148,57 +147,33 @@ def _resolve_view_fields(self, batch, blob_view_lookup, pyarrow): # ------------------------------------------------------------------ def _resolve_blob_data(self, batch, pyarrow): - """If blob-as-descriptor is true, return batch as-is. Otherwise resolve - all BlobDescriptor bytes in descriptor fields and view fields into real - blob data bytes.""" if self._blob_as_descriptor: return batch - from pypaimon.table.row.blob import Blob, BlobDescriptor - - all_fields = self._descriptor_fields | self._view_fields - result = batch - for field_name in all_fields: - if field_name not in result.schema.names: + all_inline_blob_fields = self._descriptor_fields | self._view_fields + for field_name in all_inline_blob_fields: + if field_name not in batch.schema.names: continue - values = [self._normalize_blob_cell(v) for v in result.column(field_name).to_pylist()] + values = [self._normalize_blob_to_bytes(v) for v in batch.column(field_name).to_pylist()] converted_values = [] for value in values: - if value is None: - converted_values.append(None) - continue - if not isinstance(value, bytes): - converted_values.append(value) - continue - if not BlobDescriptor.is_blob_descriptor(value): - converted_values.append(value) - continue - descriptor = BlobDescriptor.deserialize(value) - if descriptor.serialize() != value: - converted_values.append(value) - continue - try: - uri_reader = self._table.file_io.uri_reader_factory.create(descriptor.uri) - converted_values.append(Blob.from_descriptor(uri_reader, descriptor).to_data()) - except Exception as e: - raise RuntimeError( - "Failed to read blob bytes from descriptor URI." - ) from e + blob = Blob.from_bytes(value, self._table.file_io) + converted_values.append(blob.to_data() if blob else None) - column_idx = result.schema.names.index(field_name) - result = result.set_column( + column_idx = batch.schema.names.index(field_name) + batch = batch.set_column( column_idx, pyarrow.field(field_name, pyarrow.large_binary(), nullable=True), pyarrow.array(converted_values, type=pyarrow.large_binary()), ) - return result + return batch # ------------------------------------------------------------------ # Utilities # ------------------------------------------------------------------ @staticmethod - def _normalize_blob_cell(value): + def _normalize_blob_to_bytes(value): if value is None: return None if hasattr(value, 'as_py'): diff --git a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py index 79d6b4f8f2a9..64da0cc8400e 100644 --- a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py +++ b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py @@ -26,8 +26,6 @@ from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader from pypaimon.schema.data_types import DataField, PyarrowFieldParser from pypaimon.table.row.blob import Blob -from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct -from pypaimon.table.row.blob import Blob, BlobDescriptor from pypaimon.table.special_fields import SpecialFields @@ -44,10 +42,8 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p system_fields: dict, blob_as_descriptor: bool = False, blob_descriptor_fields: Optional[set] = None, - blob_view_fields: Optional[set] = None, file_io: Optional[FileIO] = None, - row_id_offsets: Optional[List[int]] = None, - table=None): + row_id_offsets: Optional[List[int]] = None): self.format_reader = format_reader self.index_mapping = index_mapping self.partition_info = partition_info @@ -61,7 +57,6 @@ def __init__(self, format_reader: RecordBatchReader, index_mapping: List[int], p self.system_fields = system_fields self.blob_as_descriptor = blob_as_descriptor self.blob_descriptor_fields = blob_descriptor_fields or set() - self.blob_view_fields = blob_view_fields or set() self.file_io = file_io self.blob_field_names = { field.name @@ -85,7 +80,7 @@ def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch if self.partition_info is None and self.index_mapping is None: if self.row_tracking_enabled and self.system_fields: record_batch = self._assign_row_tracking(record_batch) - return self._convert_inline_blob_columns(record_batch) + return record_batch inter_arrays = [] inter_names = [] @@ -142,11 +137,11 @@ def read_arrow_batch(self, start_idx=None, end_idx=None) -> Optional[RecordBatch if self.row_tracking_enabled and self.system_fields: record_batch = self._assign_row_tracking(record_batch) - record_batch = self._convert_inline_blob_columns(record_batch) + record_batch = self._convert_descriptor_stored_blob_columns(record_batch) return record_batch - def _convert_inline_blob_columns(self, record_batch: RecordBatch) -> RecordBatch: + def _convert_descriptor_stored_blob_columns(self, record_batch: RecordBatch) -> RecordBatch: if isinstance(self.format_reader, FormatBlobReader): return record_batch if not self.descriptor_blob_fields: diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index f2367b163440..fed25204c0af 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -308,8 +308,7 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, blob_as_descriptor=blob_as_descriptor, blob_descriptor_fields=blob_descriptor_fields, file_io=self.table.file_io, - row_id_offsets=row_indices, - table=self.table) + row_id_offsets=row_indices) else: reader = DataFileBatchReader( format_reader, @@ -324,8 +323,7 @@ def file_reader_supplier(self, file: DataFileMeta, for_merge_read: bool, blob_as_descriptor=blob_as_descriptor, blob_descriptor_fields=blob_descriptor_fields, file_io=self.table.file_io, - row_id_offsets=row_indices, - table=self.table) + row_id_offsets=row_indices) # For non-Vortex formats, wrap with RowIdFilterRecordBatchReader if row_ranges is not None and row_indices is None: diff --git a/paimon-python/pypaimon/schema/schema.py b/paimon-python/pypaimon/schema/schema.py index c9425c286e55..e758fc262512 100644 --- a/paimon-python/pypaimon/schema/schema.py +++ b/paimon-python/pypaimon/schema/schema.py @@ -62,59 +62,8 @@ def from_pyarrow_schema(pa_schema: pa.Schema, partition_keys: Optional[List[str] if field.name in pk_set: field.type.nullable = False - # Check if Blob type exists in the schema - blob_names = [ - field.name for field in fields - if 'blob' in str(field.type).lower() - ] - - if blob_names: - if options is None: - options = {} - - if len(fields) <= len(blob_names): - raise ValueError( - "Table with BLOB type column must have other normal columns." - ) - - blob_field_names = { - field.name for field in fields if 'blob' in str(field.type).lower() - } - core_options = CoreOptions.from_dict(options) - descriptor_fields = core_options.blob_descriptor_fields() - view_fields = core_options.blob_view_fields() - unknown_inline_fields = descriptor_fields.union(view_fields).difference(blob_field_names) - if unknown_inline_fields: - raise ValueError( - "Fields in 'blob-descriptor-field' or 'blob-view-field' must be blob fields " - "in schema. Unknown fields: {}".format(sorted(unknown_inline_fields)) - ) - - overlapping_inline_fields = descriptor_fields.intersection(view_fields) - if overlapping_inline_fields: - raise ValueError( - "Fields in 'blob-descriptor-field' and 'blob-view-field' must not overlap. " - "Overlapping fields: {}".format(sorted(overlapping_inline_fields)) - ) - - required_options = { - CoreOptions.ROW_TRACKING_ENABLED.key(): 'true', - CoreOptions.DATA_EVOLUTION_ENABLED.key(): 'true' - } - - missing_options = [] - for key, expected_value in required_options.items(): - if key not in options or options[key] != expected_value: - missing_options.append(f"{key}='{expected_value}'") - - if missing_options: - raise ValueError( - f"Schema contains Blob type but is missing required options: {', '.join(missing_options)}. " - f"Please add these options to the schema." - ) - - if primary_keys is not None: - raise ValueError("Blob type is not supported with primary key.") + # Validate Blob type fields in the schema + Schema._validate_blob_fields(fields, options, primary_keys) # Check if Vector type with dedicated file format vector_names = [ @@ -153,3 +102,61 @@ def from_pyarrow_schema(pa_schema: pa.Schema, partition_keys: Optional[List[str] ) return Schema(fields, partition_keys, primary_keys, options, comment) + + @staticmethod + def _validate_blob_fields(fields, options, primary_keys): + """Validate blob field configurations in the schema.""" + blob_names = [ + field.name for field in fields + if 'blob' in str(field.type).lower() + ] + + if not blob_names: + return + + if options is None: + options = {} + + if len(fields) <= len(blob_names): + raise ValueError( + "Table with BLOB type column must have other normal columns." + ) + + blob_field_names = { + field.name for field in fields if 'blob' in str(field.type).lower() + } + core_options = CoreOptions.from_dict(options) + descriptor_fields = core_options.blob_descriptor_fields() + view_fields = core_options.blob_view_fields() + unknown_inline_fields = descriptor_fields.union(view_fields).difference(blob_field_names) + if unknown_inline_fields: + raise ValueError( + "Fields in 'blob-descriptor-field' or 'blob-view-field' must be blob fields " + "in schema. Unknown fields: {}".format(sorted(unknown_inline_fields)) + ) + + overlapping_inline_fields = descriptor_fields.intersection(view_fields) + if overlapping_inline_fields: + raise ValueError( + "Fields in 'blob-descriptor-field' and 'blob-view-field' must not overlap. " + "Overlapping fields: {}".format(sorted(overlapping_inline_fields)) + ) + + required_options = { + CoreOptions.ROW_TRACKING_ENABLED.key(): 'true', + CoreOptions.DATA_EVOLUTION_ENABLED.key(): 'true' + } + + missing_options = [] + for key, expected_value in required_options.items(): + if key not in options or options[key] != expected_value: + missing_options.append(f"{key}='{expected_value}'") + + if missing_options: + raise ValueError( + f"Schema contains Blob type but is missing required options: {', '.join(missing_options)}. " + f"Please add these options to the schema." + ) + + if primary_keys is not None: + raise ValueError("Blob type is not supported with primary key.") diff --git a/paimon-python/pypaimon/table/row/blob.py b/paimon-python/pypaimon/table/row/blob.py index 37d25335b63a..7dfb71726bba 100644 --- a/paimon-python/pypaimon/table/row/blob.py +++ b/paimon-python/pypaimon/table/row/blob.py @@ -412,21 +412,6 @@ def from_bytes(data: Optional[bytes], file_io=None, allow_blob_data: bool = True def from_view(view_struct: BlobViewStruct) -> 'Blob': return BlobView(view_struct) - @staticmethod - def from_bytes_with_reader( - data: bytes, - uri_reader: Optional[UriReader], - file_io=None, - allow_blob_data: bool = True) -> Optional['Blob']: - if data is None: - return None - if BlobViewStruct.is_blob_view_struct(data): - return Blob.from_view(BlobViewStruct.deserialize(data)) - if BlobDescriptor.is_blob_descriptor(data) or not allow_blob_data: - descriptor = BlobDescriptor.deserialize(data) - return Blob.from_descriptor(uri_reader or UriReader.from_file(file_io), descriptor) - return Blob.from_data(data) - @staticmethod def serialize_blob(blob: 'Blob') -> bytes: if isinstance(blob, BlobView): diff --git a/paimon-python/pypaimon/tests/table_update_test.py b/paimon-python/pypaimon/tests/table_update_test.py index 153982bc9057..53a84666d17f 100644 --- a/paimon-python/pypaimon/tests/table_update_test.py +++ b/paimon-python/pypaimon/tests/table_update_test.py @@ -424,7 +424,7 @@ def test_duplicate_row_id_raises(self): def _run_concurrent_updates(self, table, thread_specs, max_retries): """Run a batch of concurrent updates with conflict-retry; return the - order in which worker threads observed successful commits.""" + commit order (``thread_index`` of the winning commit appended last).""" errors = [] completion_order = [] lock = threading.Lock() @@ -482,9 +482,12 @@ def test_concurrent_updates_overlapping_rows_last_writer_wins(self): {'row_ids': [0, 1, 2], 'ages': [102, 202, 302]}, {'row_ids': [0, 1, 2], 'ages': [103, 203, 303]}, ] - self._run_concurrent_updates(table, specs, max_retries=30) + completion_order = self._run_concurrent_updates( + table, specs, max_retries=30 + ) + winner = specs[completion_order[-1]]['ages'] ages = self._read_all(table)['age'].to_pylist() - self.assertIn(ages[:3], [spec['ages'] for spec in specs]) + self.assertEqual(winner, ages[:3]) # Rows 3 & 4 must remain at seed values self.assertEqual([40, 45], ages[3:]) diff --git a/paimon-python/pypaimon/write/writer/data_blob_writer.py b/paimon-python/pypaimon/write/writer/data_blob_writer.py index cf86036f132b..9bb25f518b22 100644 --- a/paimon-python/pypaimon/write/writer/data_blob_writer.py +++ b/paimon-python/pypaimon/write/writer/data_blob_writer.py @@ -96,20 +96,6 @@ def __init__(self, table, partition: Tuple, bucket: int, max_seq_number: int, op f"Unknown fields: {sorted(unknown_descriptor_fields)}" ) - unknown_view_fields = self.blob_view_fields.difference(set(self.blob_column_names)) - if unknown_view_fields: - raise ValueError( - "Fields in 'blob-view-field' must be blob fields in schema. " - f"Unknown fields: {sorted(unknown_view_fields)}" - ) - - overlapping_inline_fields = self.blob_descriptor_fields.intersection(self.blob_view_fields) - if overlapping_inline_fields: - raise ValueError( - "Fields in 'blob-descriptor-field' and 'blob-view-field' must not overlap. " - f"Overlapping fields: {sorted(overlapping_inline_fields)}" - ) - # Blob fields that should still be written to `.blob` files. self.blob_file_column_names = [ col for col in self.blob_column_names if col not in self.blob_inline_fields From 670454237402f83940644511d3bbc4b7fb33aad5 Mon Sep 17 00:00:00 2001 From: umi Date: Fri, 29 May 2026 14:30:51 +0800 Subject: [PATCH 06/10] prescan --- .../reader/blob_descriptor_convert_reader.py | 146 +++++++------- paimon-python/pypaimon/read/split_read.py | 40 +++- .../pypaimon/utils/blob_view_lookup.py | 179 +++++++++--------- 3 files changed, 202 insertions(+), 163 deletions(-) diff --git a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py index 19afaffb0645..456ae35248d9 100644 --- a/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py +++ b/paimon-python/pypaimon/read/reader/blob_descriptor_convert_reader.py @@ -15,110 +15,109 @@ # specific language governing permissions and limitations # under the License. -from typing import Optional +from typing import Callable, Optional, Set +import pyarrow from pyarrow import RecordBatch from pypaimon.common.options.core_options import CoreOptions from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader -from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct +from pypaimon.table.row.blob import Blob, BlobViewStruct class BlobDescriptorConvertReader(RecordBatchReader): """Resolves BlobView and BlobDescriptor fields in record batches. Processing is split into two clear stages: - Stage 1 (BlobView resolution): If view fields exist, prescan all batches, - collect BlobViewStructs, bulk-preload their descriptors from - upstream tables, and replace view field values with the - corresponding BlobDescriptor serialized bytes. + Stage 1 (BlobView resolution): If view fields exist, use a lightweight + prescan reader (only projecting view columns) to collect + BlobViewStructs, bulk-preload their descriptors, then read + full data from the main reader and replace view field values + with the corresponding BlobDescriptor serialized bytes. Stage 2 (BlobData resolution): Controlled by blob-as-descriptor option. If false, resolve all BlobDescriptor bytes (from both descriptor fields and view fields) into real blob data bytes. If true, return as-is. """ - def __init__(self, inner: RecordBatchReader, table): + def __init__(self, inner: RecordBatchReader, table, + prescan_reader_factory: Optional[Callable[[Set[str]], RecordBatchReader]] = None): + """ + Args: + inner: The main data reader (reads all columns). + table: The table instance. + prescan_reader_factory: Optional factory that creates a lightweight + reader projecting only the specified field names. Used for + prescan to collect BlobViewStructs without reading all columns. + Signature: (field_names: Set[str]) -> RecordBatchReader + """ self._inner = inner self._table = table + self._prescan_reader_factory = prescan_reader_factory self._descriptor_fields = CoreOptions.blob_descriptor_fields(table.options) self.file_io = inner.file_io self.blob_field_indices = inner.blob_field_indices self._view_fields = CoreOptions.blob_view_fields(table.options) self._descriptor_fields = CoreOptions.blob_descriptor_fields(table.options) self._blob_as_descriptor = CoreOptions.blob_as_descriptor(table.options) - self._cached_batches = None - self._batch_index = 0 + self._prescan_done = False + self._blob_view_lookup = None def read_arrow_batch(self) -> Optional[RecordBatch]: - import pyarrow - # Stage 1: obtain batch (prescan for view fields, or direct read) - if self._view_fields: - batch = self._read_with_prescan(pyarrow) - else: - batch = self._inner.read_arrow_batch() + # Ensure prescan is done before reading (only needed for view fields) + if self._view_fields and not self._prescan_done: + self._prescan_view_structs() + + batch = self._inner.read_arrow_batch() if batch is None: return None - # Stage 2: resolve BlobDescriptor -> real bytes (if blob-as-descriptor=false) - return self._resolve_blob_data(batch, pyarrow) + # Resolve view fields using the preloaded lookup + if self._view_fields and self._blob_view_lookup is not None: + batch = self._resolve_view_fields(batch, self._blob_view_lookup) + # Resolve BlobDescriptor -> real bytes (if blob-as-descriptor=false) + return self._resolve_blob_data(batch) # ------------------------------------------------------------------ - # Stage 1: BlobView prescan and resolution + # Stage 1: BlobView prescan (lightweight, only reads view columns) # ------------------------------------------------------------------ - def _read_with_prescan(self, pyarrow): - """Return the next batch from cache (view fields already resolved to - BlobDescriptor bytes).""" - if self._cached_batches is None: - self._prescan_and_resolve_views(pyarrow) - if self._batch_index >= len(self._cached_batches): - return None - batch = self._cached_batches[self._batch_index] - self._batch_index += 1 - return batch - - def _prescan_and_resolve_views(self, pyarrow): - """Prescan all batches, collect BlobViewStructs, bulk-preload - descriptors, then replace view field values with BlobDescriptor bytes.""" + def _prescan_view_structs(self): + """Use a lightweight prescan reader (projecting only view columns) to + collect all BlobViewStructs and bulk-preload their descriptors.""" from pypaimon.table.row.blob import BlobViewStruct from pypaimon.utils.blob_view_lookup import BlobViewLookup - # Step 1: cache all batches and collect BlobViewStructs - raw_batches = [] + self._prescan_done = True all_view_structs = [] - while True: - batch = self._inner.read_arrow_batch() - if batch is None: - break - raw_batches.append(batch) - for field_name in self._view_fields: - if field_name not in batch.schema.names: - continue - for value in batch.column(field_name).to_pylist(): - value = self._normalize_blob_to_bytes(value) - if isinstance(value, bytes) and BlobViewStruct.is_blob_view_struct(value): - all_view_structs.append(BlobViewStruct.deserialize(value)) - # Step 2: bulk-preload BlobViewStruct -> BlobDescriptor mapping - blob_view_lookup = None + prescan_reader = self._prescan_reader_factory(self._view_fields) + try: + while True: + batch = prescan_reader.read_arrow_batch() + if batch is None: + break + for field_name in self._view_fields: + if field_name not in batch.schema.names: + continue + for value in batch.column(field_name).to_pylist(): + value = self._normalize_blob_to_bytes(value) + if isinstance(value, bytes) and BlobViewStruct.is_blob_view_struct(value): + all_view_structs.append(BlobViewStruct.deserialize(value)) + finally: + prescan_reader.close() + + # Bulk-preload BlobViewStruct -> BlobDescriptor mapping if all_view_structs: - blob_view_lookup = BlobViewLookup(self._table) - blob_view_lookup.preload(all_view_structs) + self._blob_view_lookup = BlobViewLookup(self._table) + self._blob_view_lookup.preload(all_view_structs) - # Step 3: resolve view fields in each batch - self._cached_batches = [] - for batch in raw_batches: - batch = self._resolve_view_fields(batch, blob_view_lookup, pyarrow) - self._cached_batches.append(batch) - - def _resolve_view_fields(self, batch, blob_view_lookup, pyarrow): + def _resolve_view_fields(self, batch, blob_view_lookup): """Replace BlobViewStruct bytes in view fields with the corresponding BlobDescriptor serialized bytes.""" - result = batch for field_name in self._view_fields: - if field_name not in result.schema.names: + if field_name not in batch.schema.names: continue - values = [self._normalize_blob_to_bytes(v) for v in result.column(field_name).to_pylist()] + values = [self._normalize_blob_to_bytes(v) for v in batch.column(field_name).to_pylist()] converted_values = [] for value in values: if value is None: @@ -134,19 +133,19 @@ def _resolve_view_fields(self, batch, blob_view_lookup, pyarrow): descriptor = blob_view_lookup.resolve_descriptor(view_struct) converted_values.append(descriptor.serialize()) - column_idx = result.schema.names.index(field_name) - result = result.set_column( + column_idx = batch.schema.names.index(field_name) + batch = batch.set_column( column_idx, pyarrow.field(field_name, pyarrow.large_binary(), nullable=True), pyarrow.array(converted_values, type=pyarrow.large_binary()), ) - return result + return batch # ------------------------------------------------------------------ # Stage 2: BlobData resolution (unified exit) # ------------------------------------------------------------------ - def _resolve_blob_data(self, batch, pyarrow): + def _resolve_blob_data(self, batch): if self._blob_as_descriptor: return batch @@ -186,3 +185,22 @@ def _normalize_blob_to_bytes(value): def close(self): self._inner.close() + + +class _CachedBatchReader(RecordBatchReader): + """A simple reader that replays pre-cached RecordBatches. + Used as fallback when no prescan_reader_factory is provided.""" + + def __init__(self, batches): + self._batches = batches + self._index = 0 + + def read_arrow_batch(self) -> Optional[RecordBatch]: + if self._index >= len(self._batches): + return None + batch = self._batches[self._index] + self._index += 1 + return batch + + def close(self): + self._batches = None diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index fed25204c0af..aeddc4032d22 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -729,15 +729,27 @@ def _push_down_predicate(self) -> Optional[Predicate]: return None def create_reader(self) -> RecordReader: + reader = self._create_raw_reader() + + if (CoreOptions.blob_view_fields(self.table.options) + or (not CoreOptions.blob_as_descriptor(self.table.options) + and CoreOptions.blob_descriptor_fields(self.table.options))): + reader = BlobDescriptorConvertReader( + reader, self.table, + prescan_reader_factory=lambda names: self._create_prescan_reader(names)) + + return reader + + def _create_raw_reader(self) -> RecordReader: + """Core read logic: split_by_row_id -> suppliers -> ConcatBatchReader -> filter. + Does NOT include BlobView wrapping to avoid recursion during prescan.""" files = self.split.files suppliers = [] - # Split files by row ID split_by_row_id = self._split_by_row_id(files) for need_merge_files in split_by_row_id: if len(need_merge_files) == 1 or not self.read_fields: - # No need to merge fields, just create a single file reader suppliers.append( lambda f=need_merge_files[0]: self._create_file_reader(f, self._get_final_read_data_fields()) ) @@ -760,13 +772,27 @@ def create_reader(self) -> RecordReader: else: reader = merge_reader - if (CoreOptions.blob_view_fields(self.table.options) - or (not CoreOptions.blob_as_descriptor(self.table.options) - and CoreOptions.blob_descriptor_fields(self.table.options))): - reader = BlobDescriptorConvertReader(reader, self.table) - return reader + def _create_prescan_reader(self, field_names): + """Create a prescan reader by constructing a new DataEvolutionSplitRead + instance that only projects the specified field names.""" + from pypaimon.read.reader.iface.record_batch_reader import EmptyRecordBatchReader + + prescan_fields = [f for f in self.read_fields if f.name in field_names] + if not prescan_fields: + return EmptyRecordBatchReader() + + prescan_read = DataEvolutionSplitRead( + table=self.table, + predicate=self.predicate, + read_type=prescan_fields, + split=self.split, + row_tracking_enabled=False, + ) + prescan_read.row_ranges = self.row_ranges + return prescan_read._create_raw_reader() + def _split_by_row_id(self, files: List[DataFileMeta]) -> List[List[DataFileMeta]]: """Split files by firstRowId for data evolution.""" diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py index 9dbcadd653ea..bfe75de83567 100644 --- a/paimon-python/pypaimon/utils/blob_view_lookup.py +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -26,32 +26,57 @@ from pypaimon.schema.schema_manager import SchemaManager from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct from pypaimon.table.special_fields import SpecialFields +from pypaimon.utils.range import Range _PRELOAD_THREAD_NUM = 100 _MIN_ROWS_PER_TASK = 100 +class TableReferences: + """Groups BlobViewStruct references by upstream table.""" + + def __init__(self, identifier: Identifier): + self.identifier: Identifier = identifier + self.references_by_field: Dict[int, List[BlobViewStruct]] = {} + self.row_ids: List[int] = [] + + def add(self, view_struct: BlobViewStruct) -> None: + self.references_by_field.setdefault(view_struct.field_id, []).append(view_struct) + self.row_ids.append(int(view_struct.row_id)) + + +class TableReadPlan: + """A plan for reading blob descriptors from one upstream table.""" + + def __init__(self, identifier: Identifier, upstream_table, + fields: List, row_ranges: List[Range]): + self.identifier: Identifier = identifier + self.upstream_table = upstream_table + self.fields: List = fields + self.row_ranges: List[Range] = row_ranges + + class BlobViewLookup: """Resolve BlobViewStruct references by reading upstream blob descriptors.""" def __init__(self, table): self._table = table - self._table_cache = {} + self._table_cache: Dict[str, object] = {} self._uri_reader_cache: Dict[str, UriReader] = {} self._descriptor_cache: Dict[BlobViewStruct, BlobDescriptor] = {} def preload(self, view_structs: Iterable[BlobViewStruct]) -> None: - unique_structs = [] + unique_structs: List[BlobViewStruct] = [] for view_struct in view_structs: if view_struct not in self._descriptor_cache: unique_structs.append(view_struct) if not unique_structs: return - resolved = self._preload_descriptors(unique_structs) + resolved: Dict[BlobViewStruct, BlobDescriptor] = self._preload_descriptors(unique_structs) self._descriptor_cache.update(resolved) def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: - descriptor = self._descriptor_cache.get(view_struct) + descriptor: BlobDescriptor = self._descriptor_cache.get(view_struct) if descriptor is None: self.preload([view_struct]) descriptor = self._descriptor_cache.get(view_struct) @@ -69,19 +94,19 @@ def resolve_data(self, view_struct: BlobViewStruct) -> bytes: return Blob.from_descriptor(uri_reader, descriptor).to_data() def _preload_descriptors( - self, view_structs: List[BlobViewStruct]) -> Dict[BlobViewStruct, BlobDescriptor]: + self, view_structs: List[BlobViewStruct]) -> Dict[BlobViewStruct, BlobDescriptor]: if not view_structs: return {} - grouped = self._group_by_table(view_structs) - plans = [] - for identifier, table_refs in grouped.items(): - plans.append(self._create_table_read_plan(identifier, table_refs)) + grouped: Dict[str, TableReferences] = self._group_by_table(view_structs) + plans: List[TableReadPlan] = [] + for table_refs in grouped.values(): + plans.append(self._create_table_read_plan(table_refs)) - target_rows = self._target_rows_per_task(plans) - tasks = [] + target_rows: int = self._target_rows_per_task(plans) + tasks: List[Tuple[TableReadPlan, List[Tuple[int, int]]]] = [] for plan in plans: - for range_chunk in self._split_row_ranges(plan["row_ranges"], target_rows): + for range_chunk in self._split_row_ranges(plan.row_ranges, target_rows): tasks.append((plan, range_chunk)) if len(tasks) <= 1: @@ -104,48 +129,35 @@ def _preload_descriptors( return resolved def _group_by_table( - self, view_structs: List[BlobViewStruct] - ) -> Dict[str, Dict]: - grouped = {} + self, view_structs: List[BlobViewStruct] + ) -> Dict[str, TableReferences]: + grouped: Dict[str, TableReferences] = {} for view_struct in view_structs: key = view_struct.identifier.get_full_name() if key not in grouped: - grouped[key] = { - "identifier": view_struct.identifier, - "fields_by_id": {}, - "row_ids": [], - } - refs = grouped[key] - refs["fields_by_id"].setdefault(view_struct.field_id, []).append(view_struct) - refs["row_ids"].append(int(view_struct.row_id)) + grouped[key] = TableReferences(view_struct.identifier) + grouped[key].add(view_struct) return grouped - def _create_table_read_plan(self, table_key: str, table_refs: Dict) -> Dict: - identifier = table_refs["identifier"] - upstream_table = self._load_table(identifier) + def _create_table_read_plan(self, table_refs: TableReferences) -> TableReadPlan: + upstream_table = self._load_table(table_refs.identifier) - fields = [] - for field_id in table_refs["fields_by_id"]: - field = self._field_by_id(upstream_table, field_id) - fields.append({"field_id": field_id, "field": field}) + fields: List = [] + for field_id in table_refs.references_by_field: + fields.append(self._field_by_id(upstream_table, field_id)) - row_ranges = self._to_sorted_distinct_ranges(table_refs["row_ids"]) - return { - "identifier": identifier, - "upstream_table": upstream_table, - "fields": fields, - "row_ranges": row_ranges, - } + row_ranges: List[Tuple[int, int]] = self._to_sorted_distinct_ranges(table_refs.row_ids) + return TableReadPlan(table_refs.identifier, upstream_table, fields, row_ranges) def _load_descriptor_chunk( - self, plan: Dict, row_ranges: List[Tuple[int, int]] + self, plan: TableReadPlan, row_ranges: List[Range] ) -> Dict[BlobViewStruct, BlobDescriptor]: - identifier = plan["identifier"] - upstream_table = plan["upstream_table"] - fields = plan["fields"] + identifier: Identifier = plan.identifier + upstream_table = plan.upstream_table + fields: List = plan.fields - field_names = [f["field"].name for f in fields] - projection = field_names + [SpecialFields.ROW_ID.name] + field_names: List[str] = [f.name for f in fields] + projection: List[str] = field_names + [SpecialFields.ROW_ID.name] descriptor_table = upstream_table.copy({CoreOptions.BLOB_AS_DESCRIPTOR.key(): "true"}) read_builder = descriptor_table.new_read_builder().with_projection(projection) @@ -159,14 +171,14 @@ def _load_descriptor_chunk( ) predicate_builder = read_builder.new_predicate_builder() - range_predicates = [] - for range_from, range_to in row_ranges: - if range_from == range_to: + range_predicates: List = [] + for r in row_ranges: + if r.from_ == r.to: range_predicates.append( - predicate_builder.equal(SpecialFields.ROW_ID.name, range_from)) + predicate_builder.equal(SpecialFields.ROW_ID.name, r.from_)) else: range_predicates.append( - predicate_builder.between(SpecialFields.ROW_ID.name, range_from, range_to)) + predicate_builder.between(SpecialFields.ROW_ID.name, r.from_, r.to)) if len(range_predicates) == 1: predicate = range_predicates[0] else: @@ -180,62 +192,45 @@ def _load_descriptor_chunk( .format(identifier.get_full_name()) ) - row_id_values = result.column(SpecialFields.ROW_ID.name).to_pylist() - resolved = {} - for field_info in fields: - field_id = field_info["field_id"] - field_name = field_info["field"].name - if field_name not in result.schema.names: + row_id_values: List = result.column(SpecialFields.ROW_ID.name).to_pylist() + resolved: Dict[BlobViewStruct, BlobDescriptor] = {} + for field in fields: + if field.name not in result.schema.names: continue - values = result.column(field_name).to_pylist() + values = result.column(field.name).to_pylist() for row_id, value in zip(row_id_values, values): if value is None: continue descriptor = self._to_descriptor(value) view_struct = BlobViewStruct( - identifier.get_full_name(), field_id, int(row_id)) + identifier.get_full_name(), field.id, int(row_id)) resolved[view_struct] = descriptor return resolved @staticmethod - def _to_sorted_distinct_ranges(row_ids: List[int]) -> List[Tuple[int, int]]: - if not row_ids: - return [] - sorted_ids = sorted(set(row_ids)) - ranges = [] - range_start = sorted_ids[0] - range_end = range_start - for i in range(1, len(sorted_ids)): - row_id = sorted_ids[i] - if row_id == range_end + 1: - range_end = row_id - else: - ranges.append((range_start, range_end)) - range_start = row_id - range_end = row_id - ranges.append((range_start, range_end)) - return ranges + def _to_sorted_distinct_ranges(row_ids: List[int]) -> List[Range]: + return Range.to_ranges(row_ids) @staticmethod def _split_row_ranges( - row_ranges: List[Tuple[int, int]], target_rows_per_task: int - ) -> List[List[Tuple[int, int]]]: + row_ranges: List[Range], target_rows_per_task: int + ) -> List[List[Range]]: if not row_ranges: return [] - chunks = [] - current_chunk = [] - current_chunk_rows = 0 - for range_from, range_to in row_ranges: - next_from = range_from - while next_from <= range_to: + chunks: List[List[Range]] = [] + current_chunk: List[Range] = [] + current_chunk_rows: int = 0 + for r in row_ranges: + next_from = r.from_ + while next_from <= r.to: if current_chunk_rows == target_rows_per_task: chunks.append(current_chunk) current_chunk = [] current_chunk_rows = 0 remaining = target_rows_per_task - current_chunk_rows - next_to = min(range_to, next_from + remaining - 1) - current_chunk.append((next_from, next_to)) + next_to = min(r.to, next_from + remaining - 1) + current_chunk.append(Range(next_from, next_to)) current_chunk_rows += next_to - next_from + 1 next_from = next_to + 1 if current_chunk: @@ -243,18 +238,18 @@ def _split_row_ranges( return chunks @staticmethod - def _target_rows_per_task(plans: List[Dict]) -> int: - total_rows = 0 + def _target_rows_per_task(plans: List[TableReadPlan]) -> int: + total_rows: int = 0 for plan in plans: - for range_from, range_to in plan["row_ranges"]: - total_rows += range_to - range_from + 1 + for r in plan.row_ranges: + total_rows += r.count() if total_rows <= 0: return _MIN_ROWS_PER_TASK target = (total_rows + _PRELOAD_THREAD_NUM - 1) // _PRELOAD_THREAD_NUM return max(_MIN_ROWS_PER_TASK, target) def _load_table(self, identifier: Identifier): - key = identifier.get_full_name() + key: str = identifier.get_full_name() if key in self._table_cache: return self._table_cache[key] @@ -283,9 +278,9 @@ def _load_filesystem_table(self, identifier: Identifier): return FileStoreTable(self._table.file_io, identifier, table_path, table_schema) def _filesystem_table_path(self, identifier: Identifier) -> str: - current_table_path = self._table.table_path.rstrip("/") - current_db_path = os.path.dirname(current_table_path) - warehouse = os.path.dirname(current_db_path) + current_table_path: str = self._table.table_path.rstrip("/") + current_db_path: str = os.path.dirname(current_table_path) + warehouse: str = os.path.dirname(current_db_path) return "{}/{}.db/{}".format( warehouse.rstrip("/"), identifier.get_database_name(), @@ -318,7 +313,7 @@ def _to_descriptor(self, value) -> BlobDescriptor: return BlobDescriptor.deserialize(value) def _get_or_create_uri_reader(self, table, descriptor: BlobDescriptor) -> UriReader: - cache_key = table.identifier.get_full_name() + cache_key: str = table.identifier.get_full_name() if cache_key in self._uri_reader_cache: return self._uri_reader_cache[cache_key] uri_reader_factory = getattr(table.file_io, "uri_reader_factory", None) From a26f9a861806106e5d4238a47a1f3e88dd9aa0d4 Mon Sep 17 00:00:00 2001 From: umi Date: Fri, 29 May 2026 14:33:19 +0800 Subject: [PATCH 07/10] fix --- paimon-python/pypaimon/utils/blob_view_lookup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py index bfe75de83567..4e01413d1456 100644 --- a/paimon-python/pypaimon/utils/blob_view_lookup.py +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -94,7 +94,7 @@ def resolve_data(self, view_struct: BlobViewStruct) -> bytes: return Blob.from_descriptor(uri_reader, descriptor).to_data() def _preload_descriptors( - self, view_structs: List[BlobViewStruct]) -> Dict[BlobViewStruct, BlobDescriptor]: + self, view_structs: List[BlobViewStruct]) -> Dict[BlobViewStruct, BlobDescriptor]: if not view_structs: return {} From 96f39a6cf66cf6e3fca09d40856a6071e2b123c4 Mon Sep 17 00:00:00 2001 From: umi Date: Fri, 29 May 2026 15:27:04 +0800 Subject: [PATCH 08/10] fix --- paimon-python/pypaimon/read/split_read.py | 5 +++-- paimon-python/pypaimon/table/row/blob.py | 16 ++-------------- paimon-python/pypaimon/tests/blob_test.py | 6 ------ 3 files changed, 5 insertions(+), 22 deletions(-) diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index aeddc4032d22..ce609b05fed9 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -741,15 +741,16 @@ def create_reader(self) -> RecordReader: return reader def _create_raw_reader(self) -> RecordReader: - """Core read logic: split_by_row_id -> suppliers -> ConcatBatchReader -> filter. - Does NOT include BlobView wrapping to avoid recursion during prescan.""" + """Core read logic: split_by_row_id -> suppliers -> ConcatBatchReader -> filter.""" files = self.split.files suppliers = [] + # Split files by row ID split_by_row_id = self._split_by_row_id(files) for need_merge_files in split_by_row_id: if len(need_merge_files) == 1 or not self.read_fields: + # No need to merge fields, just create a single file reader suppliers.append( lambda f=need_merge_files[0]: self._create_file_reader(f, self._get_final_read_data_fields()) ) diff --git a/paimon-python/pypaimon/table/row/blob.py b/paimon-python/pypaimon/table/row/blob.py index 7dfb71726bba..78f9df47c8d8 100644 --- a/paimon-python/pypaimon/table/row/blob.py +++ b/paimon-python/pypaimon/table/row/blob.py @@ -393,8 +393,6 @@ def from_bytes(data: Optional[bytes], file_io=None, allow_blob_data: bool = True if not isinstance(data, (bytes, bytearray)): raise TypeError(f"Blob.from_bytes expects bytes, got {type(data)}") data = bytes(data) - if BlobViewStruct.is_blob_view_struct(data): - return Blob.from_view(BlobViewStruct.deserialize(data)) is_descriptor = BlobDescriptor.is_blob_descriptor(data) if not allow_blob_data and not is_descriptor: raise ValueError( @@ -408,16 +406,6 @@ def from_bytes(data: Optional[bytes], file_io=None, allow_blob_data: bool = True return BlobRef(uri_reader, descriptor) return BlobData(data) - @staticmethod - def from_view(view_struct: BlobViewStruct) -> 'Blob': - return BlobView(view_struct) - - @staticmethod - def serialize_blob(blob: 'Blob') -> bytes: - if isinstance(blob, BlobView): - return blob.view_struct.serialize() - return blob.to_descriptor().serialize() - class _PlaceholderBlob(Blob): @@ -509,8 +497,8 @@ def __hash__(self) -> int: class BlobView(Blob): def __init__(self, view_struct: BlobViewStruct): - self._view_struct = view_struct - self._resolved_blob = None + self._view_struct: BlobViewStruct = view_struct + self._resolved_blob: Optional[BlobRef] = None @property def view_struct(self) -> BlobViewStruct: diff --git a/paimon-python/pypaimon/tests/blob_test.py b/paimon-python/pypaimon/tests/blob_test.py index 31acf497016d..56f74a2f6269 100644 --- a/paimon-python/pypaimon/tests/blob_test.py +++ b/paimon-python/pypaimon/tests/blob_test.py @@ -180,12 +180,6 @@ def test_blob_view_struct_roundtrip(self): self.assertEqual(restored.field_id, 7) self.assertEqual(restored.row_id, 42) - blob = Blob.from_bytes(serialized) - self.assertIsInstance(blob, BlobView) - self.assertEqual(Blob.serialize_blob(blob), serialized) - with self.assertRaises(RuntimeError): - blob.to_data() - def test_blob_data_interface_compliance(self): """Test that BlobData properly implements Blob interface.""" test_data = b"interface test data" From 44638810bb0242dc8c688eccdc546f72e5cc4ac7 Mon Sep 17 00:00:00 2001 From: umi Date: Fri, 29 May 2026 17:56:42 +0800 Subject: [PATCH 09/10] refine --- .../pypaimon/catalog/filesystem_catalog.py | 6 +- .../pypaimon/utils/blob_view_lookup.py | 144 +++++------------- 2 files changed, 44 insertions(+), 106 deletions(-) diff --git a/paimon-python/pypaimon/catalog/filesystem_catalog.py b/paimon-python/pypaimon/catalog/filesystem_catalog.py index 86e2f775e769..b7356b45955b 100644 --- a/paimon-python/pypaimon/catalog/filesystem_catalog.py +++ b/paimon-python/pypaimon/catalog/filesystem_catalog.py @@ -142,11 +142,11 @@ def _load_data_table(self, identifier: Identifier) -> FileStoreTable: table_schema = self.get_table_schema(identifier) # Create catalog environment for filesystem catalog - # Filesystem catalog doesn't support version management by default + from pypaimon.catalog.filesystem_catalog_loader import FileSystemCatalogLoader catalog_environment = CatalogEnvironment( identifier=identifier, - uuid=None, # Filesystem catalog doesn't track table UUIDs - catalog_loader=None, # No catalog loader for filesystem + uuid=None, + catalog_loader=FileSystemCatalogLoader(self.catalog_context), supports_version_management=False ) diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py index 4e01413d1456..94524ac4dc4b 100644 --- a/paimon-python/pypaimon/utils/blob_view_lookup.py +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -16,14 +16,12 @@ # limitations under the License. ################################################################################ -import os from concurrent.futures import ThreadPoolExecutor, as_completed -from typing import Dict, Iterable, List, Tuple +from typing import Dict, List, Tuple from pypaimon.common.identifier import Identifier from pypaimon.common.options.core_options import CoreOptions from pypaimon.common.uri_reader import UriReader -from pypaimon.schema.schema_manager import SchemaManager from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct from pypaimon.table.special_fields import SpecialFields from pypaimon.utils.range import Range @@ -61,42 +59,12 @@ class BlobViewLookup: def __init__(self, table): self._table = table - self._table_cache: Dict[str, object] = {} self._uri_reader_cache: Dict[str, UriReader] = {} self._descriptor_cache: Dict[BlobViewStruct, BlobDescriptor] = {} - def preload(self, view_structs: Iterable[BlobViewStruct]) -> None: - unique_structs: List[BlobViewStruct] = [] - for view_struct in view_structs: - if view_struct not in self._descriptor_cache: - unique_structs.append(view_struct) - if not unique_structs: - return - resolved: Dict[BlobViewStruct, BlobDescriptor] = self._preload_descriptors(unique_structs) - self._descriptor_cache.update(resolved) - - def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: - descriptor: BlobDescriptor = self._descriptor_cache.get(view_struct) - if descriptor is None: - self.preload([view_struct]) - descriptor = self._descriptor_cache.get(view_struct) - if descriptor is None: - raise ValueError( - "Cannot resolve BlobViewStruct {} because row id {} was not found " - "in upstream table.".format(view_struct, view_struct.row_id) - ) - return descriptor - - def resolve_data(self, view_struct: BlobViewStruct) -> bytes: - descriptor = self.resolve_descriptor(view_struct) - upstream_table = self._load_table(view_struct.identifier) - uri_reader = self._get_or_create_uri_reader(upstream_table, descriptor) - return Blob.from_descriptor(uri_reader, descriptor).to_data() - - def _preload_descriptors( - self, view_structs: List[BlobViewStruct]) -> Dict[BlobViewStruct, BlobDescriptor]: + def preload(self, view_structs: List[BlobViewStruct]): if not view_structs: - return {} + return grouped: Dict[str, TableReferences] = self._group_by_table(view_structs) plans: List[TableReadPlan] = [] @@ -104,18 +72,16 @@ def _preload_descriptors( plans.append(self._create_table_read_plan(table_refs)) target_rows: int = self._target_rows_per_task(plans) - tasks: List[Tuple[TableReadPlan, List[Tuple[int, int]]]] = [] + tasks: List[Tuple[TableReadPlan, List[Range]]] = [] for plan in plans: for range_chunk in self._split_row_ranges(plan.row_ranges, target_rows): tasks.append((plan, range_chunk)) if len(tasks) <= 1: - resolved = {} for plan, range_chunk in tasks: - resolved.update(self._load_descriptor_chunk(plan, range_chunk)) - return resolved + self._descriptor_cache.update(self._load_descriptor_chunk(plan, range_chunk)) + return - resolved = {} with ThreadPoolExecutor(max_workers=min(_PRELOAD_THREAD_NUM, len(tasks))) as executor: futures = { executor.submit(self._load_descriptor_chunk, plan, range_chunk): (plan, range_chunk) @@ -123,13 +89,21 @@ def _preload_descriptors( } for future in as_completed(futures): try: - resolved.update(future.result()) + self._descriptor_cache.update(future.result()) except Exception as exc: raise RuntimeError("Failed to preload blob descriptors.") from exc - return resolved + + def resolve_descriptor(self, view_struct: BlobViewStruct) -> BlobDescriptor: + descriptor: BlobDescriptor = self._descriptor_cache.get(view_struct) + if descriptor is None: + raise ValueError( + "Cannot resolve BlobViewStruct {} because row id {} was not found " + "in upstream table.".format(view_struct, view_struct.row_id) + ) + return descriptor def _group_by_table( - self, view_structs: List[BlobViewStruct] + self, view_structs: List[BlobViewStruct] ) -> Dict[str, TableReferences]: grouped: Dict[str, TableReferences] = {} for view_struct in view_structs: @@ -146,11 +120,10 @@ def _create_table_read_plan(self, table_refs: TableReferences) -> TableReadPlan: for field_id in table_refs.references_by_field: fields.append(self._field_by_id(upstream_table, field_id)) - row_ranges: List[Tuple[int, int]] = self._to_sorted_distinct_ranges(table_refs.row_ids) - return TableReadPlan(table_refs.identifier, upstream_table, fields, row_ranges) + return TableReadPlan(table_refs.identifier, upstream_table, fields, Range.to_ranges(table_refs.row_ids)) def _load_descriptor_chunk( - self, plan: TableReadPlan, row_ranges: List[Range] + self, plan: TableReadPlan, row_ranges: List[Range] ) -> Dict[BlobViewStruct, BlobDescriptor]: identifier: Identifier = plan.identifier upstream_table = plan.upstream_table @@ -207,34 +180,46 @@ def _load_descriptor_chunk( resolved[view_struct] = descriptor return resolved - @staticmethod - def _to_sorted_distinct_ranges(row_ids: List[int]) -> List[Range]: - return Range.to_ranges(row_ids) - @staticmethod def _split_row_ranges( - row_ranges: List[Range], target_rows_per_task: int + row_ranges: List[Range], target_rows_per_task: int ) -> List[List[Range]]: + """ + Split row ranges into multiple chunks for parallel task processing. + """ if not row_ranges: return [] chunks: List[List[Range]] = [] current_chunk: List[Range] = [] current_chunk_rows: int = 0 + for r in row_ranges: next_from = r.from_ + # Process current range until all rows are allocated while next_from <= r.to: + # If current chunk is full, save it and start a new one if current_chunk_rows == target_rows_per_task: chunks.append(current_chunk) current_chunk = [] current_chunk_rows = 0 + + # Calculate remaining capacity in current chunk remaining = target_rows_per_task - current_chunk_rows + # Determine the end position for this allocation (don't exceed range boundary) next_to = min(r.to, next_from + remaining - 1) + + # Add the allocated range to current chunk current_chunk.append(Range(next_from, next_to)) current_chunk_rows += next_to - next_from + 1 + + # Move to next unallocated position next_from = next_to + 1 + + # Don't forget the last chunk if it has any ranges if current_chunk: chunks.append(current_chunk) + return chunks @staticmethod @@ -245,50 +230,15 @@ def _target_rows_per_task(plans: List[TableReadPlan]) -> int: total_rows += r.count() if total_rows <= 0: return _MIN_ROWS_PER_TASK - target = (total_rows + _PRELOAD_THREAD_NUM - 1) // _PRELOAD_THREAD_NUM - return max(_MIN_ROWS_PER_TASK, target) - - def _load_table(self, identifier: Identifier): - key: str = identifier.get_full_name() - if key in self._table_cache: - return self._table_cache[key] - - catalog_loader = self._table.catalog_environment.catalog_loader - if catalog_loader is not None: - catalog = catalog_loader.load() - table = catalog.get_table(identifier) - else: - table = self._load_filesystem_table(identifier) - - self._table_cache[key] = table - return table - def _load_filesystem_table(self, identifier: Identifier): - from pypaimon.table.file_store_table import FileStoreTable + return max(_MIN_ROWS_PER_TASK, (total_rows + _PRELOAD_THREAD_NUM - 1) // _PRELOAD_THREAD_NUM) - table_path = self._filesystem_table_path(identifier) - schema_manager = SchemaManager( - self._table.file_io, - table_path, - branch=identifier.get_branch_name_or_default(), - ) - table_schema = schema_manager.latest() - if table_schema is None: - raise ValueError("Cannot find upstream table at path: {}".format(table_path)) - return FileStoreTable(self._table.file_io, identifier, table_path, table_schema) - - def _filesystem_table_path(self, identifier: Identifier) -> str: - current_table_path: str = self._table.table_path.rstrip("/") - current_db_path: str = os.path.dirname(current_table_path) - warehouse: str = os.path.dirname(current_db_path) - return "{}/{}.db/{}".format( - warehouse.rstrip("/"), - identifier.get_database_name(), - identifier.get_table_name(), - ) + def _load_table(self, identifier: Identifier): + catalog = self._table.catalog_environment.catalog_loader.load() + return catalog.get_table(identifier) @staticmethod - def _field_by_id(table, field_id: int): + def _field_by_id(table, field_id: int) -> 'DataField': for field in table.table_schema.fields: if field.id == field_id: return field @@ -311,15 +261,3 @@ def _to_descriptor(self, value) -> BlobDescriptor: if not BlobDescriptor.is_blob_descriptor(value): raise ValueError("Blob view upstream value is not a serialized BlobDescriptor.") return BlobDescriptor.deserialize(value) - - def _get_or_create_uri_reader(self, table, descriptor: BlobDescriptor) -> UriReader: - cache_key: str = table.identifier.get_full_name() - if cache_key in self._uri_reader_cache: - return self._uri_reader_cache[cache_key] - uri_reader_factory = getattr(table.file_io, "uri_reader_factory", None) - if uri_reader_factory is not None: - uri_reader = uri_reader_factory.create(descriptor.uri) - else: - uri_reader = UriReader.from_file(table.file_io) - self._uri_reader_cache[cache_key] = uri_reader - return uri_reader From 46455e23096ae9f0ed69c263cdc7686a56f9d327 Mon Sep 17 00:00:00 2001 From: umi Date: Fri, 29 May 2026 17:57:57 +0800 Subject: [PATCH 10/10] fmt --- paimon-python/pypaimon/tests/blob_test.py | 2 +- paimon-python/pypaimon/utils/blob_view_lookup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/paimon-python/pypaimon/tests/blob_test.py b/paimon-python/pypaimon/tests/blob_test.py index 56f74a2f6269..47180a60d58c 100644 --- a/paimon-python/pypaimon/tests/blob_test.py +++ b/paimon-python/pypaimon/tests/blob_test.py @@ -31,7 +31,7 @@ from pypaimon.common.options import Options from pypaimon.read.reader.format_blob_reader import BlobRecordIterator, FormatBlobReader from pypaimon.schema.data_types import AtomicType, DataField -from pypaimon.table.row.blob import Blob, BlobData, BlobRef, BlobDescriptor, BlobView, BlobViewStruct +from pypaimon.table.row.blob import Blob, BlobData, BlobRef, BlobDescriptor, BlobViewStruct from pypaimon.table.row.generic_row import GenericRowDeserializer, GenericRowSerializer, GenericRow from pypaimon.table.row.row_kind import RowKind diff --git a/paimon-python/pypaimon/utils/blob_view_lookup.py b/paimon-python/pypaimon/utils/blob_view_lookup.py index 94524ac4dc4b..264652183d54 100644 --- a/paimon-python/pypaimon/utils/blob_view_lookup.py +++ b/paimon-python/pypaimon/utils/blob_view_lookup.py @@ -22,7 +22,7 @@ from pypaimon.common.identifier import Identifier from pypaimon.common.options.core_options import CoreOptions from pypaimon.common.uri_reader import UriReader -from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct +from pypaimon.table.row.blob import BlobDescriptor, BlobViewStruct from pypaimon.table.special_fields import SpecialFields from pypaimon.utils.range import Range