JingsongLi commented on code in PR #10570:
URL: https://github.com/apache/paimon/pull/10570#discussion_r4284923208
##########
paimon-python/pypaimon/write/file_store_commit.py:
##########
@@ -86,6 +86,80 @@ def _reject_compact_increment(messages: List[CommitMessage]):
'Committing a compact increment requires a separate COMPACT
snapshot.')
+def _delete_abort_paths(table, paths):
+ for path_to_delete in paths:
+ try:
+ table.file_io.delete_quietly(str(path_to_delete))
+ except Exception as error:
+ logger.warning(
+ "Failed to clean up file %s during abort: %s",
+ path_to_delete,
+ error,
+ )
+
+
+def _protected_managed_packs(table, paths):
+ """Keep a pack when a blobref outside this abort still names it.
+
+ One pack can be listed on every data file that referenced it. Deleting it
+ with the first aborted file would make the other files unreadable.
+ """
+ from pypaimon.blob.managed_blob_reference_file import
ManagedBlobReferenceFile
+
+ pack_suffix = ManagedBlobReferenceFile.MANAGED_BLOB_SUFFIX
+ ref_suffix = ManagedBlobReferenceFile.REFERENCE_FILE_SUFFIX
+ deleting = {str(path) for path in paths}
+ packs_by_dir = {}
+ for path in deleting:
+ if not path.endswith(pack_suffix):
+ continue
+ parent, _, name = path.rpartition("/")
+ if parent and name:
+ packs_by_dir.setdefault(parent, {})[name] = path
+ if not packs_by_dir:
+ return set()
+
+ list_status = getattr(table.file_io, "list_status", None)
+ if list_status is None:
+ return set()
+
+ protected = set()
+ for parent, packs in packs_by_dir.items():
+ try:
+ statuses = list(list_status(parent))
+ except TypeError:
+ continue
+ except Exception as error:
Review Comment:
Verified fixed at c7f4414 in the Python abort path: a real three-file
shared-pack fixture passed 9 cases / 144 assertions, including
missing/failed/partial listings and unreadable sidecars; partial abort
preserves committed payloads and full abort still cleans up. Resolving this
original issue. The separate Java extra_files cleanup gap is reported in the
new review.
##########
paimon-python/pypaimon/blob/primary_key_blob_externalizer.py:
##########
@@ -0,0 +1,258 @@
+# 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.
+
+"""Externalize primary-key BLOB values into managed packs before the data
file."""
+
+import pyarrow as pa
+
+from pypaimon.blob.managed_blob_reference_collector import _map_items
+from pypaimon.schema.data_types import (
+ AtomicType,
+ DataField,
+ is_array_blob_type,
+ is_blob_type,
+ is_map_blob_type,
+)
+from pypaimon.table.row.blob import BlobDescriptor
+from pypaimon.table.row.generic_row import GenericRow
+from pypaimon.table.row.row_kind import RowKind
+from pypaimon.write.blob_format_writer import BlobFormatWriter
+
+
+class PrimaryKeyBlobExternalizer:
+ """Write managed BLOB payloads to ``.managed.blob`` packs and store
descriptors.
+
+ Retract rows drop their payload, matching ``PrimaryKeyBlobExternalizer`` in
+ Java. Packs stay owned by this writer until ``prepare_commit``.
+ """
+
+ _RETRACT_KINDS = frozenset({
+ RowKind.UPDATE_BEFORE.value,
+ RowKind.DELETE.value,
+ })
+
+ def __init__(
+ self,
+ file_io,
+ new_pack_path,
+ value_fields,
+ managed_blob_fields,
+ target_file_size,
+ copy_buffer_size,
+ uri_reader_factory=None,
+ table_path=None):
+ if target_file_size <= 0:
+ raise ValueError(
+ "Managed BLOB target file size must be positive, but was %s."
+ % target_file_size)
+ self._file_io = file_io
+ self._uri_reader_factory = uri_reader_factory
+ self._table_path = None if table_path is None else str(table_path)
+ self._uncommitted = []
+ self._referenced_pack_names = []
+ self._writers = {}
+ self._field_specs = []
+ for field in value_fields:
+ if field.name not in managed_blob_fields:
+ continue
+ if is_blob_type(field.type):
+ kind = "scalar"
+ elif is_array_blob_type(field.type):
+ kind = "array"
+ elif is_map_blob_type(field.type):
+ kind = "map"
+ else:
+ continue
+ self._field_specs.append((field.name, kind))
+ self._writers[field.name] = _ManagedBlobPackWriter(
+ file_io, new_pack_path, target_file_size, copy_buffer_size,
+ self._uncommitted)
+
+ def externalize_table(self, data: pa.Table) -> pa.Table:
+ self._referenced_pack_names = []
+ if not self._field_specs:
+ return data
+ try:
+ if "_VALUE_KIND" in data.schema.names:
+ kinds = data.column("_VALUE_KIND").to_pylist()
+ else:
+ kinds = [RowKind.INSERT.value] * data.num_rows
+ for field_name, field_kind in self._field_specs:
+ if field_name not in data.schema.names:
+ continue
+ # TODO: to_pylist() materializes the whole BLOB column.
+ values = data.column(field_name).to_pylist()
+ replaced = []
+ for index, value in enumerate(values):
+ if kinds[index] in self._RETRACT_KINDS:
+ replaced.append(None)
+ else:
+ replaced.append(
+ self._externalize_value(value, field_kind,
field_name))
+ field = data.schema.field(field_name)
+ column_index = data.schema.get_field_index(field_name)
+ data = data.set_column(
+ column_index, field, pa.array(replaced, type=field.type))
+ return data
+ except Exception:
Review Comment:
Verified fixed at c7f4414 for the original failure/retry path: both one
shared open pack and rolling 32-byte packs survived a later partial
externalization failure, retry -> commit, and scalar/array/map payload
readback. Explicit abort before prepare also cleaned owned packs. Resolving
this original issue.
##########
paimon-python/pypaimon/read/table_read.py:
##########
@@ -886,6 +887,7 @@ def _arrow_batch_generator(self, splits: List[Split],
schema: pyarrow.Schema,
batch = batch.slice(0, remaining)
batch = self._serialize_blob_views_as_descriptors(
batch, reader)
+ batch = self._materialize_managed_blob_batch(batch)
Review Comment:
Still reproducible at c7f4414 when projection is involved. With committed
(id=1,payload=b"visible"),(id=2,payload=b"other") and native write/read/scan
disabled, equal("payload",b"visible") works without projection, but
with_projection(["id"]) returns [1,2] instead of [1], and
with_projection(["payload","id"]) or ["id","payload"] returns no rows instead
of id=1. Both to_arrow and to_iterator behave this way (likewise for b"other").
_managed_blob_specs uses the output adapter schema, so projected-out predicate
columns are never materialized/filtered; the outer-projection fallback can also
reapply the original predicate to descriptor bytes before materialization.
Please retain predicate dependencies in the internal read schema and ensure
filtering occurs once, on resolved payload values, before output projection.
##########
paimon-python/pypaimon/blob/primary_key_blob_externalizer.py:
##########
@@ -0,0 +1,258 @@
+# 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.
+
+"""Externalize primary-key BLOB values into managed packs before the data
file."""
+
+import pyarrow as pa
+
+from pypaimon.blob.managed_blob_reference_collector import _map_items
+from pypaimon.schema.data_types import (
+ AtomicType,
+ DataField,
+ is_array_blob_type,
+ is_blob_type,
+ is_map_blob_type,
+)
+from pypaimon.table.row.blob import BlobDescriptor
+from pypaimon.table.row.generic_row import GenericRow
+from pypaimon.table.row.row_kind import RowKind
+from pypaimon.write.blob_format_writer import BlobFormatWriter
+
+
+class PrimaryKeyBlobExternalizer:
+ """Write managed BLOB payloads to ``.managed.blob`` packs and store
descriptors.
+
+ Retract rows drop their payload, matching ``PrimaryKeyBlobExternalizer`` in
+ Java. Packs stay owned by this writer until ``prepare_commit``.
+ """
+
+ _RETRACT_KINDS = frozenset({
+ RowKind.UPDATE_BEFORE.value,
+ RowKind.DELETE.value,
+ })
+
+ def __init__(
+ self,
+ file_io,
+ new_pack_path,
+ value_fields,
+ managed_blob_fields,
+ target_file_size,
+ copy_buffer_size,
+ uri_reader_factory=None,
+ table_path=None):
+ if target_file_size <= 0:
+ raise ValueError(
+ "Managed BLOB target file size must be positive, but was %s."
+ % target_file_size)
+ self._file_io = file_io
+ self._uri_reader_factory = uri_reader_factory
+ self._table_path = None if table_path is None else str(table_path)
+ self._uncommitted = []
+ self._referenced_pack_names = []
+ self._writers = {}
+ self._field_specs = []
+ for field in value_fields:
+ if field.name not in managed_blob_fields:
+ continue
+ if is_blob_type(field.type):
+ kind = "scalar"
+ elif is_array_blob_type(field.type):
+ kind = "array"
+ elif is_map_blob_type(field.type):
+ kind = "map"
+ else:
+ continue
+ self._field_specs.append((field.name, kind))
+ self._writers[field.name] = _ManagedBlobPackWriter(
+ file_io, new_pack_path, target_file_size, copy_buffer_size,
+ self._uncommitted)
+
+ def externalize_table(self, data: pa.Table) -> pa.Table:
+ self._referenced_pack_names = []
+ if not self._field_specs:
+ return data
+ try:
+ if "_VALUE_KIND" in data.schema.names:
+ kinds = data.column("_VALUE_KIND").to_pylist()
+ else:
+ kinds = [RowKind.INSERT.value] * data.num_rows
+ for field_name, field_kind in self._field_specs:
+ if field_name not in data.schema.names:
+ continue
+ # TODO: to_pylist() materializes the whole BLOB column.
+ values = data.column(field_name).to_pylist()
+ replaced = []
+ for index, value in enumerate(values):
+ if kinds[index] in self._RETRACT_KINDS:
+ replaced.append(None)
+ else:
+ replaced.append(
+ self._externalize_value(value, field_kind,
field_name))
+ field = data.schema.field(field_name)
+ column_index = data.schema.get_field_index(field_name)
+ data = data.set_column(
+ column_index, field, pa.array(replaced, type=field.type))
+ return data
+ except Exception:
+ self.abort()
+ raise
+
+ def finish_current(self):
+ for writer in self._writers.values():
+ writer.close_current()
+
+ def prepare_commit(self):
+ try:
+ self.finish_current()
+ # Clear in place. Each pack writer holds this same list.
+ self._uncommitted.clear()
+ except Exception:
+ self.abort()
+ raise
+
+ def take_referenced_pack_names(self):
+ """Pack file names referenced by the data file just externalized."""
+ names = self._referenced_pack_names
+ self._referenced_pack_names = []
+ return names
+
+ def abort(self):
+ for writer in self._writers.values():
+ writer.abort_current()
+ for path in list(self._uncommitted):
+ self._file_io.delete_quietly(path)
+ self._uncommitted.clear()
+
+ def _externalize_value(self, value, field_kind, field_name):
+ if hasattr(value, "as_py"):
+ value = value.as_py()
+ if value is None:
+ return None
+ if field_kind == "scalar":
+ return self._write_descriptor(field_name, value)
+ if field_kind == "array":
+ if isinstance(value, (bytes, bytearray, str)) or not
hasattr(value, "__iter__"):
+ raise ValueError(
+ "ARRAY<BLOB> field '%s' must be a list of blob values." %
field_name)
+ return [
+ None if element is None else
self._write_descriptor(field_name, element)
+ for element in value
+ ]
+ if field_kind == "map":
+ externalized = []
+ for key, map_value in _map_items(value):
+ if map_value is None:
+ externalized.append((key, None))
+ else:
+ externalized.append(
+ (key, self._write_descriptor(field_name, map_value)))
+ if isinstance(value, dict):
+ return dict(externalized)
+ return externalized
+ return value
+
+ def _write_descriptor(self, field_name, raw):
+ blob = BlobFormatWriter._to_blob(raw, self._uri_reader_factory)
+ descriptor = self._writers[field_name].write(blob)
+ uri = self._table_relative_uri(descriptor.uri)
+ name = uri.replace('\\', '/').rsplit('/', 1)[-1]
+ if name not in self._referenced_pack_names:
+ self._referenced_pack_names.append(name)
+ return BlobDescriptor(uri, descriptor.offset,
descriptor.length).serialize()
+
+ def _table_relative_uri(self, uri):
+ """Pack location relative to the table directory.
+
+ Append dedicated-blob descriptors still store the writer path.
+ """
+ root = self._table_path
+ if not root:
+ return uri
+ normalized = uri.replace('\\', '/')
+ prefix = root.replace('\\', '/').rstrip('/') + '/'
+ if normalized.startswith(prefix):
Review Comment:
Verified fixed at c7f4414: real managed PK writes now support row-iterator
get_blob(...).to_data() against table-relative descriptors, and the relevant
URI/Blob/reader regressions pass. Resolving this original issue.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]