This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 9c7233535f [python] Add high-level multimodal column enrichment APIs
(#10958)
9c7233535f is described below
commit 9c7233535f47fe7885c98d22a966fcc51f23b855
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 3 12:10:33 2026 +0800
[python] Add high-level multimodal column enrichment APIs (#10958)
---
docs/docs/pypaimon/data-evolution.md | 7 +-
docs/docs/pypaimon/multimodal-api.mdx | 2 +-
docs/docs/pypaimon/multimodal-tables.mdx | 103 +++++
paimon-python/README.md | 50 +++
.../python/read/reader/format_pyarrow_reader.py | 16 +-
.../read/reader/parquet_page_index_reader.py | 17 +
.../pypaimon/execution/python/read/split_read.py | 15 +
.../execution/python/write/format_file_writer.py | 17 +
.../execution/python/write/writer/data_writer.py | 2 +
.../python/write/writer/single_file_writer.py | 6 +-
.../execution/python/write/writer/vector_writer.py | 4 +-
paimon-python/pypaimon/multimodal/__init__.py | 3 +
paimon-python/pypaimon/multimodal/columns.py | 271 +++++++++++++
paimon-python/pypaimon/multimodal/table.py | 36 ++
paimon-python/pypaimon/schema/arrow_schema.py | 25 ++
.../pypaimon/tests/multimodal_columns_test.py | 434 +++++++++++++++++++++
.../pypaimon/tests/parquet_vector_write_test.py | 137 +++++++
17 files changed, 1136 insertions(+), 9 deletions(-)
diff --git a/docs/docs/pypaimon/data-evolution.md
b/docs/docs/pypaimon/data-evolution.md
index faa94834d3..d2e791d3fc 100644
--- a/docs/docs/pypaimon/data-evolution.md
+++ b/docs/docs/pypaimon/data-evolution.md
@@ -26,9 +26,10 @@ under the License.
Data evolution lets you update selected columns while preserving the remaining
columns and media payloads. This page covers the lower-level Python update and
-commit APIs; use [Multimodal Tables](./multimodal-tables#update) for the
compact
-interface. See [Data Evolution](../multimodal-table/data-evolution) for the
storage
-model.
+commit APIs; use [Multimodal Tables](./multimodal-tables#update) for compact
row
+updates and [Column Enrichment](./multimodal-tables#column-enrichment) for
label
+and feature backfills. See [Data Evolution](../multimodal-table/data-evolution)
+for the storage model.
| You have⦠| Use |
| --- | --- |
diff --git a/docs/docs/pypaimon/multimodal-api.mdx
b/docs/docs/pypaimon/multimodal-api.mdx
index e74e8cba4e..59ed81c460 100644
--- a/docs/docs/pypaimon/multimodal-api.mdx
+++ b/docs/docs/pypaimon/multimodal-api.mdx
@@ -36,7 +36,7 @@ Start with [Multimodal Tables](./multimodal-tables) to
connect, define a schema,
| Retrieve text and vector candidates | [Search](./multimodal-search) |
| Store media | [BLOB storage](./blob), [object API](./blob-store), [video
frames](./video) |
| Import robotics datasets | [HDF5 and ROSBag](./dataset-ingestion),
[LeRobot](./lerobot) |
-| Update selected columns | [Data evolution](./data-evolution) |
+| Backfill labels and features | [Column
enrichment](./multimodal-tables#column-enrichment) |
| Train and process data | [PyTorch](./pytorch), [Ray Data](./ray-data),
[Daft](./daft) |
diff --git a/docs/docs/pypaimon/multimodal-tables.mdx
b/docs/docs/pypaimon/multimodal-tables.mdx
index 73073cea91..dbb7e5c718 100644
--- a/docs/docs/pypaimon/multimodal-tables.mdx
+++ b/docs/docs/pypaimon/multimodal-tables.mdx
@@ -259,6 +259,109 @@ On a frame table, updating ordinary columns leaves the
configured
`video-frame-field` untouched. Replacing that field requires the specialized
`replace_video()` API described in [Video Frame
Storage](./video#update-frame-rows-and-replace-a-video).
+## Column Enrichment
+
+Use `pypaimon.multimodal` to backfill labels or features on a Data Evolution
+append table without managing row IDs and commit messages. These tables have no
+primary key, use `bucket=-1`, and enable both row tracking and data evolution.
+The multimodal connection sets these options when creating a table.
+
+```python
+import pyarrow as pa
+import pyarrow.compute as pc
+import pypaimon.multimodal as pmm
+
+connection = pmm.connect(options={"warehouse": "/tmp/column-enrichment"})
+frames = connection.create_table(
+ "frames",
+ schema=pa.schema([("sample_id", pa.int64()), ("image",
pa.large_binary())]),
+ data=[{"sample_id": 1, "image": b"first"},
+ {"sample_id": 2, "image": b"second"}],
+)
+
+# Import external labels. The nullable label column is created automatically.
+result = frames.merge_columns(
+ pa.table({"sample_id": [2], "label": ["pedestrian"]}), on="sample_id")
+print(result.added_columns) # ('label',); the first row's label remains NULL
+
+# Derive a new column. Only image is passed to the function; row IDs are
internal.
+def image_sizes(batch):
+ return pa.table({"image_size":
pc.binary_length(batch["image"]).cast(pa.int64())})
+
+result = frames.add_columns(
+ schema=pa.schema([("image_size", pa.int64())]),
+ inputs=["image"], fn=image_sizes, batch_size=128)
+print(result.updated_rows) # 2
+
+# A schema-only addition does not backfill values or create a data snapshot.
+frames.add_columns(pa.schema([("caption", pa.string())]))
+```
+
+For embeddings, declare a fixed-size list such as
+`pa.list_(pa.float32(), 768)` and return arrays of that type. The function
returns
+an Arrow Table or RecordBatch containing exactly the declared output columns,
+with the same row count and order as its input. Inputs are RecordBatches of at
+most `batch_size` rows. Functions should be deterministic and side-effect-free.
+Ordinary BLOB inputs are bytes; video-frame inputs retain their descriptor
+semantics and need decoding in the function. With no `fn`, omit `inputs`.
+New columns must be nullable; existing column names are rejected by
`add_columns`.
+
+`merge_columns` accepts the same key forms as `merge`: a name, a list of names,
+or a mapping from target names to source names. It updates only non-key columns
+present in the source and never inserts rows. Omitted columns keep their
values;
+explicit NULL values clear nullable columns. New columns are nullable and use
the
+source's Arrow types; existing output types must match the table types.
Matching
+and key type conversion follow ordinary `merge` semantics: unmatched source
rows
+are ignored, NULL keys do not match, and one source row can update multiple
target
+rows with the same key. Multiple source rows matching the same target row are
+rejected by the MERGE executor. Partition and match keys cannot be updated;
+use `replace_video` to replace configured video-frame columns.
+
+`merge_columns` delegates matching and updates to the standard MERGE executor.
+With a compatible `pypaimon_rust` runtime and `write.native.enabled=true`,
+supported tables use native MERGE without a separate Python target-key scan.
+`add_columns` can use the native shard reader and writer with the same option;
+the supplied `fn` still runs in Python. Unsupported native routes select Python
+before execution.
+
+Both methods retain files for untouched columns. Computing an image embedding
+still reads the image, but does not rewrite it. Normal partial updates write
the
+selected columns over affected file row-ID ranges; they are not single-cell
+physical writes. `add_columns` buffers outputs per original file group so a
+small function batch does not repeatedly rewrite the same group.
+
+These are local, single-writer operations on a current full-table view.
+As with other table methods, reopen the table after external schema changes.
+Time-travel and incremental table views are rejected. `merge_columns`
materializes
+the source as an Arrow table; target matching is handled by the selected MERGE
+executor. The read snapshot is fixed for the
+operation. Coordinate writers for the entire call.
+The APIs do not provide automatic retries, checkpoints, or distributed jobs.
+
+Successful calls return `ColumnUpdateResult` with added column names,
+the source and final data snapshot IDs, and the schema ID. `updated_rows` is
the
+backfilled row count for `add_columns` (zero for schema-only additions) and
`None`
+for `merge_columns`, because MERGE does not return logical row counts.
Schema-only changes
+leave the data snapshot ID unchanged. Schema publication and data publication
+are separate operations. Failures during schema publication or data preparation
+and commit raise
+`ColumnUpdateError`, retaining the original exception as `__cause__` and
exposing:
+
+| Attribute | Meaning |
+| --- | --- |
+| `phase` | The stage that failed: schema, compute, write, commit, result, or
close |
+| `schema_changed` | `True` if schema publication succeeded, `False` if it did
not start, or `None` if its outcome is unknown |
+| `schema_id` | The last known schema ID |
+| `source_snapshot_id` | The snapshot used to match or compute rows |
+| `commit_outcome` | `not_started`, `unknown`, or `committed` |
+
+Input validation errors remain ordinary exceptions. Failed
+computation can leave new columns visible as NULL, without publishing any data
+updates. Prepared files are retained on failure; ordinary orphan-file
maintenance
+can remove abandoned files. If publication has an unknown outcome, inspect the
+table before deciding whether to retry. Do not automatically retry the function
+or delete prepared files after a commit error.
+
## Delete
`delete` removes rows matched by a SQL-like predicate. It uses the same
diff --git a/paimon-python/README.md b/paimon-python/README.md
index 4bcdd29995..3685996cf6 100644
--- a/paimon-python/README.md
+++ b/paimon-python/README.md
@@ -125,6 +125,56 @@ finally:
For stream updates, use `table.new_stream_write_builder()` and pass the stream
commit identifier to `new_update().new_update_by_row_id(commit_identifier)`.
+# Multimodal column enrichment
+
+Multimodal Data Evolution tables provide two local column-enrichment methods:
+
+```python
+# labels is a typed Arrow table containing sample_id and the columns to fill.
+# New columns are added automatically; existing media columns retain their
files.
+result = table.merge_columns(labels, on="sample_id")
+
+# Compute new nullable columns from selected inputs, in input row order.
+result = table.add_columns(
+ schema=feature_schema, inputs=["image"], fn=compute_features,
batch_size=128)
+
+# Without fn, only the schema is changed; existing rows read as NULL.
+result = table.add_columns(schema=nullable_columns)
+```
+
+`table` is a `pypaimon.multimodal.MultimodalTable`. `merge_columns` uses
ordinary
+update-only MERGE semantics: unmatched source rows are ignored, NULL keys do
not
+match, and one source row can update multiple target rows. Multiple source rows
+matching the same target row are rejected by the MERGE executor. Key type
+conversion follows `merge`.
+Outputs must have the declared/existing types. A fixed-size Arrow list declares
+a VECTOR column, for example `pa.list_(pa.float32(), 768)` for an embedding.
+
+These methods require a current full-table view and a single writer during the
+operation. They do not provide distributed execution or automatic retries.
+`add_columns` reads only its inputs, materializing ordinary BLOB inputs as
bytes;
+video-frame columns keep their descriptor semantics. Function calls have at
most
+`batch_size` rows; outputs are buffered per original file group before writing.
+`merge_columns` materializes the source as an Arrow table and delegates target
+matching and updates to the standard MERGE backend. Supported routes use native
+MERGE when `write.native.enabled=true` and a compatible `pypaimon_rust` is
available.
+`add_columns` can use the native shard reader and writer; its `fn` runs in
Python.
+
+`ColumnUpdateResult` reports `updated_rows`, `added_columns`,
`source_snapshot_id`,
+`snapshot_id`, and `schema_id`. `updated_rows` is the backfilled row count for
+`add_columns` (zero for schema-only additions) and `None` for `merge_columns`.
+Schema publication and data
+commit are separate. A schema-only call does not create a data snapshot.
+Failures during publication or data preparation raise `ColumnUpdateError` with
`phase`,
+`schema_changed`, `schema_id`, `source_snapshot_id`, and `commit_outcome`;
+the original exception remains in `__cause__`. New columns can remain visible
as
+NULL after failed computation. If schema publication or data commit has an
+unknown outcome, inspect the table before retrying. Prepared files are
preserved
+on failure and may require ordinary orphan-file maintenance.
+
+See [Multimodal Column
Enrichment](../docs/docs/pypaimon/multimodal-tables.mdx#column-enrichment) for a
+complete example and the column update contract.
+
# Parquet page-index reads
For row-tracking tables with a Parquet OffsetIndex, PyPaimon can read a
diff --git
a/paimon-python/pypaimon/execution/python/read/reader/format_pyarrow_reader.py
b/paimon-python/pypaimon/execution/python/read/reader/format_pyarrow_reader.py
index f303b358f7..7ea1e87872 100644
---
a/paimon-python/pypaimon/execution/python/read/reader/format_pyarrow_reader.py
+++
b/paimon-python/pypaimon/execution/python/read/reader/format_pyarrow_reader.py
@@ -53,6 +53,7 @@ from pypaimon.data.variant_shredding import (
)
from pypaimon.execution.python.read.variant_shredding import
assemble_shredded_column
from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader
+from pypaimon.schema.arrow_schema import parquet_storage_schema
from pypaimon.schema.data_types import (
ArrayType,
AtomicType,
@@ -468,6 +469,8 @@ class FormatPyArrowReader(RecordBatchReader):
self._has_nested_path = has_nested_path
file_schema = self.dataset.schema
+ physical_parquet_schema = parquet_storage_schema(file_schema) if
file_format == 'parquet' else file_schema
+ has_fixed_size_lists = not file_schema.equals(physical_parquet_schema)
has_logical_map = any(
isinstance(field.type, MapType)
or is_map_selected_keys_field(field)
@@ -573,6 +576,7 @@ class FormatPyArrowReader(RecordBatchReader):
self._orc_file = None
self._orc_source = None
if (self._bounded_variant_read
+ or has_fixed_size_lists
or self._selected_parquet_row_groups is not None
or (file_format == 'parquet'
and self._selected_shared_map_paths)):
@@ -580,7 +584,17 @@ class FormatPyArrowReader(RecordBatchReader):
# ParquetFile(filesystem=...) is unavailable in PyArrow 6.
self._parquet_source = _open_pyarrow_input_file(file_io,
file_path, file_size)
try:
- self._parquet_file = pq.ParquetFile(self._parquet_source)
+ metadata = None
+ if has_fixed_size_lists:
+ # Native/older writers can retain fixed-size lists in
+ # ARROW:schema. Preserve every physical footer field,
+ # including INT96/DECIMAL encodings and page-index offsets.
+ from
pypaimon.execution.python.read.reader.parquet_page_index_reader import (
+ parquet_metadata_with_arrow_schema,
+ )
+ fragment = next(iter(self.dataset.get_fragments()))
+ metadata =
parquet_metadata_with_arrow_schema(fragment.metadata, physical_parquet_schema)
+ self._parquet_file = pq.ParquetFile(self._parquet_source,
metadata=metadata)
if (self._selected_parquet_row_groups is not None
and options is not None
and options.parquet_column_index_enabled()
diff --git
a/paimon-python/pypaimon/execution/python/read/reader/parquet_page_index_reader.py
b/paimon-python/pypaimon/execution/python/read/reader/parquet_page_index_reader.py
index 53f2839248..479e8f54dc 100644
---
a/paimon-python/pypaimon/execution/python/read/reader/parquet_page_index_reader.py
+++
b/paimon-python/pypaimon/execution/python/read/reader/parquet_page_index_reader.py
@@ -391,6 +391,23 @@ def _get(fields, field, default=None):
return fields[field][1] if field in fields else default
+def parquet_metadata_with_arrow_schema(metadata, schema):
+ """Replace only ARROW:schema, retaining physical types and row-group
metadata."""
+ output = pa.BufferOutputStream()
+ metadata.write_metadata_file(output)
+ serialized = output.getvalue().to_pybytes()
+ length = struct.unpack("<I", serialized[-8:-4])[0]
+ footer = _Compact(serialized[-8 - length:-8], length).value(12)
+ encoded_schema = base64.b64encode(schema.serialize().to_pybytes())
+ entries = _get(footer, 5, (12, []))[1]
+ entries = [entry for entry in entries if _get(entry, 1) != b"ARROW:schema"]
+ entries.append({1: (8, b"ARROW:schema"), 2: (8, encoded_schema)})
+ footer[5] = (9, (12, entries))
+ encoded = _encode(12, footer)
+ data = b"PAR1" + encoded + struct.pack("<I", len(encoded)) + b"PAR1"
+ return pq.read_metadata(pa.BufferReader(data))
+
+
def _read_exact(source, offset, length):
if offset < 4 or length <= 0:
raise ValueError("Invalid Parquet page-index byte range")
diff --git a/paimon-python/pypaimon/execution/python/read/split_read.py
b/paimon-python/pypaimon/execution/python/read/split_read.py
index 3d4b1be412..0ff4a8422c 100644
--- a/paimon-python/pypaimon/execution/python/read/split_read.py
+++ b/paimon-python/pypaimon/execution/python/read/split_read.py
@@ -1734,6 +1734,21 @@ class DataEvolutionSplitRead(SplitRead):
if not field.type.nullable:
raise ValueError(f"Field {field} is not null but can't
find any file contains it.")
+ if not any(reader is not None for reader in file_record_readers):
+ # A projection of newly added columns still has one NULL per live
+ # row. Use a normal file's row IDs as the cardinality anchor,
without
+ # reading unrelated BLOBs, and retain range/deletion filtering.
+ anchor = next(file for file in need_merge_files
+ if not DataFileMeta.is_blob_file(file.file_name)
+ and not DataFileMeta.is_vector_file(file.file_name))
+ saved_fields = self.read_fields
+ try:
+ self.read_fields = [SpecialFields.ROW_ID]
+ file_record_readers[0] = self._create_file_reader(
+ anchor, [SpecialFields.ROW_ID.name], deletion_vector)
+ finally:
+ self.read_fields = saved_fields
+
# Bunch readers use runtime nullability after schema evolution. Keep
# the same nested types when assembling their columns into one batch.
output_schema = read_arrow_schema(all_read_fields)
diff --git
a/paimon-python/pypaimon/execution/python/write/format_file_writer.py
b/paimon-python/pypaimon/execution/python/write/format_file_writer.py
index 007fdf708e..ff15365d60 100644
--- a/paimon-python/pypaimon/execution/python/write/format_file_writer.py
+++ b/paimon-python/pypaimon/execution/python/write/format_file_writer.py
@@ -27,9 +27,26 @@ import pyarrow as pa
from pypaimon.execution.python.write.blob_format_writer import BlobFormatWriter
from pypaimon.execution.python.write.writer.format_row_writer import
FormatRowWriter
from pypaimon.filesystem.vortex_utils import to_vortex_specified
+from pypaimon.schema.arrow_schema import parquet_storage_schema
from pypaimon.schema.data_types import AtomicType, DataField,
PyarrowFieldParser
+def parquet_write_schema(schema):
+ """Keep vector dimensions in Paimon rather than Parquet's Arrow metadata.
+
+ PyArrow cannot restore nullable fixed-size lists from Parquet reliably.
+ Use physical variable-size lists, including for streaming writers whose
+ later batches may contain NULLs. Preserve unrelated field/schema metadata.
+ """
+ return parquet_storage_schema(schema)
+
+
+def parquet_write_data(data, schema=None):
+ """Convert vectors to their Parquet representation without dropping
metadata."""
+ schema = parquet_write_schema(data.schema) if schema is None else schema
+ return data if data.schema.equals(schema, check_metadata=True) else
data.cast(schema)
+
+
def write_row_file(file_io, path, data, fields=None, zstd_level=1):
try:
if fields is None:
diff --git
a/paimon-python/pypaimon/execution/python/write/writer/data_writer.py
b/paimon-python/pypaimon/execution/python/write/writer/data_writer.py
index 5141e9e402..2d19c10e21 100644
--- a/paimon-python/pypaimon/execution/python/write/writer/data_writer.py
+++ b/paimon-python/pypaimon/execution/python/write/writer/data_writer.py
@@ -467,6 +467,8 @@ class DataWriter(ABC):
self.committed_changelog_files.append(changelog_meta)
def _write_parquet_data(self, path, data):
+ from pypaimon.execution.python.write.format_file_writer import
parquet_write_data
+ data = parquet_write_data(data)
if self._map_shared_shredding.is_active():
return self._map_shared_shredding.write_parquet(
self.file_io, path, data, self.compression, self.zstd_level)
diff --git
a/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
b/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
index 5abe7e90b5..bc9947d6af 100644
--- a/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
+++ b/paimon-python/pypaimon/execution/python/write/writer/single_file_writer.py
@@ -20,6 +20,7 @@ from contextlib import suppress
import pyarrow.parquet as pq
from pypaimon.common.options.core_options import CoreOptions
+from pypaimon.execution.python.write.format_file_writer import
parquet_write_data, parquet_write_schema
class SingleFileWriter:
@@ -40,6 +41,7 @@ class SingleFileWriter:
self._closed = False
self.row_count = 0
self.column_stats = {}
+ self._physical_schema = parquet_write_schema(schema)
kwargs = dict(parquet_options or {}, compression=compression)
if compression.lower() == 'zstd':
@@ -47,7 +49,7 @@ class SingleFileWriter:
try:
self._stream = file_io.new_output_stream(path)
self._owns_file = True
- self._writer = pq.ParquetWriter(self._stream, schema, **kwargs)
+ self._writer = pq.ParquetWriter(self._stream,
self._physical_schema, **kwargs)
except Exception:
self.abort()
raise
@@ -59,7 +61,7 @@ class SingleFileWriter:
kwargs = {}
if row_group_size is not None:
kwargs['row_group_size'] = row_group_size
- self._writer.write_table(data, **kwargs)
+ self._writer.write_table(parquet_write_data(data,
self._physical_schema), **kwargs)
self.row_count += data.num_rows
for field in self._stats_fields:
current = self._stats_collector(data, field.name)
diff --git
a/paimon-python/pypaimon/execution/python/write/writer/vector_writer.py
b/paimon-python/pypaimon/execution/python/write/writer/vector_writer.py
index c248f99341..c690526517 100644
--- a/paimon-python/pypaimon/execution/python/write/writer/vector_writer.py
+++ b/paimon-python/pypaimon/execution/python/write/writer/vector_writer.py
@@ -21,7 +21,7 @@ from typing import List, Tuple
import pyarrow as pa
from pypaimon.execution.python.write.format_file_writer import (
- write_vortex_file
+ parquet_write_data, write_vortex_file
)
from pypaimon.common.options.core_options import CoreOptions
from pypaimon.data.timestamp import Timestamp
@@ -92,7 +92,7 @@ class VectorWriter(AppendOnlyDataWriter):
external_path_str = file_path if is_external_path else None
if self.vector_file_format == CoreOptions.FILE_FORMAT_PARQUET:
- self.file_io.write_parquet(file_path, data,
+ self.file_io.write_parquet(file_path, parquet_write_data(data),
compression=self.compression,
zstd_level=self.zstd_level,
**self.parquet_writer_options)
diff --git a/paimon-python/pypaimon/multimodal/__init__.py
b/paimon-python/pypaimon/multimodal/__init__.py
index 25cfc784c5..9a5bde9cc6 100644
--- a/paimon-python/pypaimon/multimodal/__init__.py
+++ b/paimon-python/pypaimon/multimodal/__init__.py
@@ -25,6 +25,7 @@ from pypaimon.multimodal.blob_store import (
PutObjectResult,
)
from pypaimon.multimodal.connection import MultimodalConnection, connect
+from pypaimon.multimodal.columns import ColumnUpdateError, ColumnUpdateResult
from pypaimon.multimodal.hdf5 import (
Hdf5File,
Hdf5LoadResult,
@@ -64,6 +65,8 @@ __all__ = [
"BlobDescriptor",
"BlobObject",
"BlobStore",
+ "ColumnUpdateError",
+ "ColumnUpdateResult",
"Hdf5File",
"Hdf5LoadResult",
"MultimodalConnection",
diff --git a/paimon-python/pypaimon/multimodal/columns.py
b/paimon-python/pypaimon/multimodal/columns.py
new file mode 100644
index 0000000000..4e69310d11
--- /dev/null
+++ b/paimon-python/pypaimon/multimodal/columns.py
@@ -0,0 +1,271 @@
+# 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.
+
+"""Local column enrichment over Data Evolution tables."""
+
+from dataclasses import dataclass
+from typing import Optional, Tuple
+
+import pyarrow as pa
+
+from pypaimon.common.options.core_options import CoreOptions
+from pypaimon.multimodal.table import (
+ _cast_merge_on_columns, _normalize_merge_on, _target_schema,
+ _to_arrow_table, _validate_merge_on,
+)
+from pypaimon.schema.data_types import PyarrowFieldParser
+from pypaimon.schema.schema_change import SchemaChange
+from pypaimon.snapshot.time_travel_util import SCAN_KEYS
+from pypaimon.table.data_evolution_merge_into import WhenMatched, source_col
+from pypaimon.table.special_fields import SpecialFields
+from pypaimon.write.update_validation import _authorize_update
+
+
+@dataclass(frozen=True)
+class ColumnUpdateResult:
+ """Schema and data versions produced by a successful column operation.
+
+ ``updated_rows`` is available for ``add_columns`` and is ``None`` for
+ ``merge_columns``, whose MERGE executor does not return logical row counts.
+ """
+
+ source_snapshot_id: Optional[int]
+ snapshot_id: Optional[int]
+ schema_id: int
+ updated_rows: Optional[int]
+ added_columns: Tuple[str, ...]
+
+
+class ColumnUpdateError(RuntimeError):
+ """A failed enrichment, with its last known publication state.
+
+ ``schema_changed=None`` means the schema request had an unknown outcome.
+ ``commit_outcome`` is ``not_started``, ``unknown``, or ``committed``. Never
+ retry blindly after an unknown outcome; inspect the table first. The
+ original failure is retained as ``__cause__``.
+ """
+
+ def __init__(self, operation):
+ self.phase = operation.phase
+ self.schema_changed = operation.schema_changed
+ self.schema_id = operation.raw.table_schema.id
+ self.source_snapshot_id = operation.source_snapshot_id
+ self.commit_outcome = operation.commit_outcome
+ super().__init__(
+ "Column update failed during %s (schema_changed=%s, schema_id=%s, "
+ "source_snapshot_id=%s, commit_outcome=%s)."
+ % (self.phase, self.schema_changed, self.schema_id,
+ self.source_snapshot_id, self.commit_outcome))
+
+
+def _validate_update(table):
+ selectors = SCAN_KEYS + CoreOptions.INCREMENTAL_SCAN_KEYS + [
+ CoreOptions.SCAN_FILE_CREATION_TIME_MILLIS.key(),
+ CoreOptions.SCAN_CREATION_TIME_MILLIS.key(),
+ ]
+ if (hasattr(table, "_read_snapshot")
+ or any(table.table_schema.options.get(key) is not None for key in
selectors)
+ or table.table_schema.options.get("scan.mode", "default")
+ not in ("default", "latest", "latest-full")):
+ raise ValueError("Column updates require a current full-table view.")
+ _authorize_update(table)
+
+
+class _ColumnUpdate:
+ def __init__(self, owner, raw):
+ self.owner = owner
+ self.raw = raw
+ self.snapshot = raw.snapshot_manager().get_latest_snapshot()
+ self.source_snapshot_id = None if self.snapshot is None else
self.snapshot.id
+ self.added_columns = ()
+ self.schema_changed = False
+ self.commit_outcome = "not_started"
+ self.phase = "schema"
+ self.resources = []
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, error, traceback):
+ for resource in reversed(self.resources):
+ try:
+ resource.close()
+ except Exception as close_error:
+ if error is None:
+ self.phase = "close"
+ error = close_error
+ if error is not None and isinstance(error, Exception):
+ raise ColumnUpdateError(self) from error
+ return False
+
+ def keep(self, resource):
+ self.resources.append(resource)
+ return resource
+
+ def add_schema(self, fields):
+ if not fields:
+ return
+ changes = [SchemaChange.add_column(
+ field.name, PyarrowFieldParser.to_paimon_type(field.type, True),
+ comment=(field.metadata or {}).get(b"description",
b"").decode("utf-8") or None,
+ ) for field in fields]
+ self.schema_changed = None
+ self.owner.catalog.alter_table(self.owner.identifier, changes)
+ self.schema_changed = True
+ # Only this operation's schema addition needs a new table definition.
+ # Ordinary calls keep the caller's existing handle, like
add/update/merge.
+ raw =
self.owner.catalog.get_table(self.owner.identifier).copy_without_time_travel(
+ getattr(self.raw, "_applied_dynamic_options", {}))
+ _authorize_update(raw)
+ self.raw = self.owner.raw_table = self.owner.table = raw
+ self.added_columns = tuple(field.name for field in fields)
+
+ def finish(self, updated_rows, commit=None, messages=()):
+ if messages:
+ self.phase = "commit"
+ self.commit_outcome = "unknown"
+ commit.commit(messages)
+ self.commit_outcome = "committed"
+ self.phase = "result"
+ snapshot = self.raw.snapshot_manager().get_latest_snapshot()
+ return ColumnUpdateResult(
+ self.source_snapshot_id, None if snapshot is None else snapshot.id,
+ self.raw.table_schema.id, updated_rows, self.added_columns)
+
+
+def _validate_names(names, label):
+ if (not names or any(not isinstance(name, str) or not name for name in
names)
+ or len(names) != len(set(names))):
+ raise ValueError("%s must contain nonempty, unique column names." %
label)
+ reserved = set(names).intersection(SpecialFields.SYSTEM_FIELD_NAMES)
+ if reserved:
+ raise ValueError("%s cannot contain system columns: %s" % (label,
sorted(reserved)))
+
+
+def _canonical_field(field):
+ data_type = PyarrowFieldParser.to_paimon_type(field.type, field.nullable)
+ return field.with_type(PyarrowFieldParser.from_paimon_type(data_type))
+
+
+def _normalize_output(data, schema):
+ if not isinstance(data, (pa.Table, pa.RecordBatch)):
+ raise ValueError("Column function must return a pyarrow.Table or
RecordBatch.")
+ if (len(data.schema.names) != len(schema.names)
+ or set(data.schema.names) != set(schema.names)):
+ raise ValueError("Output must contain exactly the declared columns:
%s" % schema.names)
+ arrays = []
+ for field in schema:
+ array = data[field.name]
+ if not pa.types.is_null(array.type):
+ source_type = _canonical_field(pa.field(field.name,
array.type)).type
+ if source_type != field.type:
+ raise ValueError("Incompatible type for column %s: %s != %s"
+ % (field.name, array.type, field.type))
+ if not field.nullable and array.null_count:
+ raise ValueError("Cannot write null to non-null column %s." %
field.name)
+ arrays.append(array.cast(field.type))
+ return pa.Table.from_arrays(arrays, schema=schema)
+
+
+def merge_columns(owner, data, *, on):
+ raw = owner.raw_table
+ _validate_update(raw)
+ data = _to_arrow_table(data)
+ _validate_names(data.column_names, "Source")
+ target_keys, source_keys = _normalize_merge_on(on, "merge_columns")
+ target_schema = _target_schema(raw)
+ _validate_merge_on(target_schema, data, target_keys, source_keys,
"merge_columns")
+ data = _cast_merge_on_columns(data, target_schema, target_keys,
source_keys)
+ output_names = [name for name in data.column_names if name not in
source_keys]
+ _validate_names(output_names, "Output")
+ if set(output_names).intersection(raw.partition_keys + target_keys):
+ raise ValueError("merge_columns cannot update partition or match
keys.")
+ if set(output_names).intersection(raw.options.video_frame_fields()):
+ raise ValueError("Use replace_video() to update video-frame columns.")
+ fields = [target_schema.field(name) if name in target_schema.names
+ else
_canonical_field(data.schema.field(name)).with_nullable(True)
+ for name in output_names]
+ output = _normalize_output(data.select(output_names), pa.schema(fields))
+ source = data
+ for field, column in zip(output.schema, output.columns):
+ source = source.set_column(source.schema.get_field_index(field.name),
field, column)
+ with _ColumnUpdate(owner, raw) as operation:
+ operation.add_schema([field for field in fields if field.name not in
target_schema.names])
+ if source.num_rows == 0:
+ return operation.finish(None)
+ operation.phase = "write"
+ builder =
operation.raw._copy_with_snapshot(operation.snapshot).new_batch_write_builder()
+ commit = operation.keep(builder.new_commit())
+ messages = builder.new_update().merge_into(
+ source, on=dict(zip(target_keys, source_keys)),
+ when_matched=[WhenMatched.update({name: source_col(name) for name
in output_names})])
+ return operation.finish(None, commit=commit, messages=messages)
+
+
+def add_columns(owner, schema, *, inputs, fn, batch_size):
+ if not isinstance(schema, pa.Schema):
+ raise ValueError("schema must be a pyarrow.Schema.")
+ _validate_names(schema.names, "Schema")
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or
batch_size <= 0:
+ raise ValueError("batch_size must be a positive integer.")
+ if any(not field.nullable for field in schema):
+ raise ValueError("New columns must be nullable until backfill is
complete.")
+ fields = [_canonical_field(field) for field in schema]
+ raw = owner.raw_table
+ _validate_update(raw)
+ existing = set(schema.names).intersection(raw.field_names)
+ if existing:
+ raise ValueError("Column already exists: %s" % sorted(existing))
+ if fn is None:
+ if inputs is not None:
+ raise ValueError("inputs requires fn.")
+ else:
+ if not callable(fn) or inputs is None:
+ raise ValueError("A callable fn and explicit inputs are required
for backfill.")
+ inputs = [inputs] if isinstance(inputs, str) else list(inputs)
+ _validate_names(inputs, "inputs")
+ missing = set(inputs).difference(raw.field_names)
+ if missing:
+ raise ValueError("Input columns do not exist: %s" %
sorted(missing))
+ with _ColumnUpdate(owner, raw) as operation:
+ operation.add_schema(fields)
+ if fn is None:
+ return operation.finish(0)
+ operation.phase = "compute"
+ table = operation.raw.copy_without_time_travel({
+ "blob-as-descriptor": "false", "read.batch-size": str(batch_size),
+ })._copy_with_snapshot(operation.snapshot)
+ builder = table.new_batch_write_builder()
+ commit = operation.keep(builder.new_commit())
+ update = builder.new_update().with_update_type(schema.names)
+ update.with_read_projection(inputs)
+ shard = operation.keep(update.new_shard_updator(0, 1))
+ updated_rows = 0
+ for batch in shard.arrow_reader():
+ for start in range(0, batch.num_rows, batch_size):
+ operation.phase = "compute"
+ piece = batch.slice(start, batch_size)
+ output = _normalize_output(fn(piece), pa.schema(fields))
+ if output.num_rows != piece.num_rows:
+ raise ValueError("Column function must return one output
row per input row, in input order.")
+ operation.phase = "write"
+ for output_batch in
output.to_batches(max_chunksize=batch_size):
+ shard.update_by_arrow_batch(output_batch)
+ updated_rows += output.num_rows
+ operation.phase = "write"
+ messages = shard.prepare_commit()
+ return operation.finish(updated_rows, commit=commit, messages=messages)
diff --git a/paimon-python/pypaimon/multimodal/table.py
b/paimon-python/pypaimon/multimodal/table.py
index 045ae6a04b..c5fe9ed2f1 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -503,6 +503,42 @@ class MultimodalTable:
def merge(self, on):
return _MergeBuilder(self, on)
+ def merge_columns(self, data, *, on):
+ """Match external column values without inserting rows or rewriting
other columns.
+
+ Missing output columns are added as nullable columns using the input
+ Arrow types. Matching follows an update-only MERGE: unmatched source
+ rows are ignored, one source row may update multiple target rows, and
+ multiple source rows matching the same target row are rejected.
+ Existing output types must match the table types. Execution reuses
+ the standard MERGE backend, including native execution when enabled.
+ Schema publication and data commit are separate operations. Requires
+ a current full-table view and a single writer for the operation.
+ Returns :class:`pypaimon.multimodal.ColumnUpdateResult` with
+ ``updated_rows=None`` because MERGE does not return logical row counts.
+ """
+ from pypaimon.multimodal.columns import merge_columns
+ return merge_columns(self, data, on=on)
+
+ def add_columns(self, schema, *, inputs=None, fn=None, batch_size=1024):
+ """Add nullable columns, optionally computing their values in batches.
+
+ ``schema`` declares new columns. If supplied, ``fn`` receives an
+ Arrow RecordBatch containing only ``inputs`` and returns a Table or
+ RecordBatch of the declared columns in the same row order and count.
+ Ordinary BLOB inputs are payload bytes. Video-frame inputs retain
+ their descriptor semantics; decoding belongs in the function.
+ The function may run repeatedly and must be side-effect-free.
+
+ Outputs are grouped by the original file row-ID ranges before being
+ written. Untouched columns, including media, retain their files.
+ Schema publication precedes computation; failures leave new columns
+ visible as NULL. Requires a current full-table view and a single
+ writer. Returns :class:`pypaimon.multimodal.ColumnUpdateResult`.
+ """
+ from pypaimon.multimodal.columns import add_columns
+ return add_columns(self, schema, inputs=inputs, fn=fn,
batch_size=batch_size)
+
def map_with_blobs(self, dataset, columns, fn, **kwargs):
from pypaimon.ray import map_with_blobs
diff --git a/paimon-python/pypaimon/schema/arrow_schema.py
b/paimon-python/pypaimon/schema/arrow_schema.py
index 5f47b6e9ec..abaeefd4f7 100644
--- a/paimon-python/pypaimon/schema/arrow_schema.py
+++ b/paimon-python/pypaimon/schema/arrow_schema.py
@@ -23,6 +23,31 @@ import pyarrow.compute as pc
from pypaimon.schema.data_types import ArrayType, MapType, PyarrowFieldParser,
RowType
+def parquet_storage_schema(schema):
+ """Represent vectors as variable-size lists while preserving Arrow
metadata.
+
+ Paimon carries vector dimensions in its table schema. PyArrow cannot
+ reliably restore nullable fixed-size lists from Parquet's Arrow metadata.
+ """
+ def physical_type(data_type):
+ if pa.types.is_struct(data_type):
+ return pa.struct([field.with_type(physical_type(field.type)) for
field in data_type])
+ if (pa.types.is_list(data_type) or pa.types.is_large_list(data_type)
+ or pa.types.is_fixed_size_list(data_type)):
+ field =
data_type.value_field.with_type(physical_type(data_type.value_type))
+ return pa.large_list(field) if pa.types.is_large_list(data_type)
else pa.list_(field)
+ if pa.types.is_map(data_type):
+ sorted_keys = data_type == pa.map_(data_type.key_field,
data_type.item_field, keys_sorted=True)
+ return pa.map_(
+
data_type.key_field.with_type(physical_type(data_type.key_type)),
+
data_type.item_field.with_type(physical_type(data_type.item_type)),
+ keys_sorted=sorted_keys)
+ return data_type
+
+ return pa.schema([field.with_type(physical_type(field.type)) for field in
schema],
+ metadata=schema.metadata)
+
+
def _read_arrow_type(data_type):
if isinstance(data_type, RowType):
return pa.struct([pa.field(field.name, _read_arrow_type(field.type))
for field in data_type.fields])
diff --git a/paimon-python/pypaimon/tests/multimodal_columns_test.py
b/paimon-python/pypaimon/tests/multimodal_columns_test.py
new file mode 100644
index 0000000000..ebe3b4cccd
--- /dev/null
+++ b/paimon-python/pypaimon/tests/multimodal_columns_test.py
@@ -0,0 +1,434 @@
+# 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.
+
+from unittest.mock import patch
+
+import pyarrow as pa
+import pytest
+
+import pypaimon.multimodal as pmm
+from pypaimon.manifest.schema.data_file_meta import DataFileMeta
+from pypaimon.write.table_commit import BatchTableCommit
+
+
[email protected]
+def frames(tmp_path):
+ connection = pmm.connect(options={"warehouse": str(tmp_path /
"warehouse")})
+ return connection.create_table(
+ "frames",
+ schema=pa.schema([
+ ("id", pa.int64()), ("label", pa.string()),
+ ("image", pa.large_binary()),
+ ]),
+ data=[{"id": i, "label": "old", "image": bytes([i]) * 100}
+ for i in range(5)],
+ options={"file.format": "parquet", "read.batch-size": "2"},
+ )
+
+
+def _snapshot(table):
+ return table.raw_table.snapshot_manager().get_latest_snapshot().id
+
+
+def _files(table):
+ return {file.file_name: file
+ for split in
table.raw_table.new_read_builder().new_scan().plan_all().splits()
+ for file in split.files}
+
+
+def _blobs(table):
+ return {name for name in _files(table) if DataFileMeta.is_blob_file(name)}
+
+
+def _rows(table, columns):
+ return sorted(table.scan().select(columns).to_list(), key=lambda row:
row["id"])
+
+
+def
test_merge_columns_adds_typed_features_without_reading_or_rewriting_media(frames):
+ snapshot = _snapshot(frames)
+ files = set(_files(frames))
+ blobs = _blobs(frames)
+ features = pa.table({
+ "id": [3, 1],
+ "embedding": pa.array([[3.0, 4.0], [1.0, 2.0]],
+ type=pa.list_(pa.float32(), 2)),
+ })
+ with patch.object(frames.raw_table.file_io, "read_ranges_coalesced",
+ side_effect=AssertionError("must not fetch media")):
+ result = frames.merge_columns(features, on="id")
+
+ assert result.source_snapshot_id == snapshot
+ assert result.snapshot_id > snapshot
+ assert result.schema_id == frames.raw_table.table_schema.id
+ assert result.updated_rows is None
+ assert result.added_columns == ("embedding",)
+ assert _rows(frames, ["id", "label", "embedding"]) == [
+ {"id": i, "label": "old", "embedding":
+ [float(i), float(i + 1)] if i in (1, 3) else None}
+ for i in range(5)
+ ]
+ assert _blobs(frames) == blobs
+ assert files.issubset(_files(frames))
+ assert frames.scan(snapshot_id=snapshot).select(["id",
"label"]).to_arrow().num_rows == 5
+
+
+def
test_merge_columns_preserves_omitted_values_and_writes_explicit_null(frames):
+ frames.merge_columns(pa.table({"id": [1, 3], "label": [None, "new"]}),
on="id")
+
+ assert _rows(frames, ["id", "label"]) == [
+ {"id": i, "label": None if i == 1 else "new" if i == 3 else "old"}
+ for i in range(5)
+ ]
+ _, blobs = frames.scan().select(["id", "image"]).read_blobs()
+ assert blobs["image"] == [bytes([i]) * 100 for i in range(5)]
+
+
+def test_merge_columns_rejects_multiple_sources_for_the_same_target(frames):
+ snapshot = _snapshot(frames)
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ frames.merge_columns(pa.table({
+ "id": [1, 1], "new_label": ["first", "second"],
+ }), on="id")
+
+ assert failure.value.phase == "write"
+ assert failure.value.schema_changed is True
+ assert failure.value.commit_outcome == "not_started"
+ assert "multiple source rows" in str(failure.value.__cause__)
+ assert _snapshot(frames) == snapshot
+ assert
frames.scan().select(["new_label"]).to_arrow()["new_label"].to_pylist() ==
[None] * 5
+
+
+def
test_merge_columns_ignores_unmatched_and_null_keys_and_supports_key_mapping(frames):
+ result = frames.merge_columns(
+ pa.table({"source_id": pa.array([2, 99, 99, None], type=pa.int32()),
+ "label": ["new", "missing", "duplicate unmatched", "null"]}),
+ on={"id": "source_id"})
+
+ assert result.updated_rows is None
+ assert _rows(frames, ["id", "label"])[2] == {"id": 2, "label": "new"}
+ assert len(_rows(frames, ["id"])) == 5
+
+
+def test_merge_columns_updates_all_target_rows_with_the_same_key(frames):
+ frames.add([{"id": 1, "label": "duplicate", "image": b"other"}])
+ snapshot = _snapshot(frames)
+ frames.merge_columns(pa.table({"id": [1], "label": ["new"]}), on="id")
+ assert _snapshot(frames) > snapshot
+ assert frames.scan().where("id = 1").select(["label"]).to_list() == [
+ {"label": "new"}, {"label": "new"}]
+
+
+def
test_merge_columns_rejects_incompatible_types_before_schema_changes(frames):
+ snapshot = _snapshot(frames)
+ with pytest.raises(ValueError, match="label"):
+ frames.merge_columns(pa.table({
+ "id": [0], "new_label": ["new"], "label": [123],
+ }), on="id")
+ assert _snapshot(frames) == snapshot
+ assert "new_label" not in
frames.catalog.get_table(frames.identifier).field_names
+
+
+def test_add_columns_batches_payloads_and_writes_each_file_group_once(frames):
+ snapshot = _snapshot(frames)
+ files = set(_files(frames))
+ blobs = _blobs(frames)
+ batches = []
+
+ def embed(batch):
+ assert batch.schema.names == ["image"]
+ batches.append(batch.num_rows)
+ return pa.table({"embedding": pa.array(
+ [[float(image[0]), float(len(image))] for image in
batch["image"].to_pylist()],
+ type=pa.list_(pa.float32(), 2))})
+
+ result = frames.add_columns(
+ schema=pa.schema([("embedding", pa.list_(pa.float32(), 2))]),
+ inputs=["image"], fn=embed, batch_size=2)
+
+ assert sum(batches) == 5
+ assert max(batches) <= 2
+ assert (result.updated_rows, result.source_snapshot_id) == (5, snapshot)
+ assert result.added_columns == ("embedding",)
+ assert _rows(frames, ["id", "embedding"]) == [
+ {"id": i, "embedding": [float(i), 100.0]} for i in range(5)]
+ assert _blobs(frames) == blobs
+ assert files.issubset(_files(frames))
+ feature_files = [file for name, file in _files(frames).items() if name not
in files]
+ assert len(feature_files) == 1
+ assert feature_files[0].write_cols == ["embedding"]
+
+
+def test_add_columns_schema_only_updates_the_existing_facade(frames):
+ snapshot = _snapshot(frames)
+ files = set(_files(frames))
+ result = frames.add_columns(pa.schema([("caption", pa.string())]))
+
+ assert result.updated_rows == 0
+ assert result.snapshot_id == snapshot
+ assert set(_files(frames)) == files
+ assert frames.scan().select(["caption"]).to_arrow()["caption"].to_pylist()
== [None] * 5
+ frames.merge_columns(pa.table({"id": [0], "caption": ["hello"]}), on="id")
+ assert _rows(frames, ["id", "caption"])[0] == {"id": 0, "caption": "hello"}
+
+
+def test_add_columns_preserves_deleted_rows_and_crosses_file_groups(frames):
+ frames.add([{"id": 5, "label": "old", "image": b"five"}])
+ frames.delete("id = 1")
+ result = frames.add_columns(
+ pa.schema([("doubled", pa.int64())]), inputs=["id"],
+ fn=lambda batch: pa.table({"doubled": [i * 2 for i in
batch["id"].to_pylist()]}),
+ batch_size=1)
+
+ assert result.updated_rows == 5
+ assert _rows(frames, ["id", "doubled"]) == [
+ {"id": i, "doubled": i * 2} for i in (0, 2, 3, 4, 5)]
+
+
[email protected]("output", [
+ lambda batch: pa.table({"feature": [1]}),
+ lambda batch: pa.table({"wrong": [1] * batch.num_rows}),
+ lambda batch: pa.table({"feature": ["invalid"] * batch.num_rows}),
+])
+def
test_add_columns_reports_schema_publication_but_never_commits_bad_outputs(frames,
output):
+ snapshot = _snapshot(frames)
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ frames.add_columns(pa.schema([("feature", pa.int64())]),
+ inputs=["id"], fn=output, batch_size=2)
+
+ assert failure.value.phase == "compute"
+ assert failure.value.schema_changed is True
+ assert failure.value.commit_outcome == "not_started"
+ assert failure.value.__cause__ is not None
+ assert _snapshot(frames) == snapshot
+ assert frames.scan().select(["feature"]).to_arrow()["feature"].to_pylist()
== [None] * 5
+
+
+def test_add_columns_rejects_existing_columns_before_calling_user_code(frames):
+ def compute(batch):
+ raise AssertionError("must not run")
+
+ with pytest.raises(ValueError, match="already exists"):
+ frames.add_columns(pa.schema([("label", pa.string())]),
inputs=["image"], fn=compute)
+
+
+def test_merge_columns_preserves_files_if_commit_response_is_lost(frames):
+ commit = BatchTableCommit.commit
+
+ def lost_response(self, messages, *args, **kwargs):
+ commit(self, messages, *args, **kwargs)
+ raise OSError("lost commit response")
+
+ with patch.object(BatchTableCommit, "commit", lost_response), patch.object(
+ BatchTableCommit, "abort", side_effect=AssertionError("must
preserve files")):
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ frames.merge_columns(pa.table({"id": [0], "label":
["committed"]}), on="id")
+
+ assert failure.value.phase == "commit"
+ assert failure.value.commit_outcome == "unknown"
+ assert isinstance(failure.value.__cause__, OSError)
+ assert _rows(frames, ["id", "label"])[0]["label"] == "committed"
+
+
+def
test_merge_columns_matches_composite_keys_without_materializing_payloads(frames):
+ frames.add([{"id": 0, "label": "second", "image": b"another"}])
+ result = frames.merge_columns(pa.table({
+ "source_id": [0], "source_label": ["second"], "caption": ["matched"],
+ }), on={"id": "source_id", "label": "source_label"})
+
+ assert result.updated_rows is None
+ rows = frames.scan().select(["id", "label", "caption"]).where("id =
0").to_list()
+ assert sorted(rows, key=lambda row: row["label"]) == [
+ {"id": 0, "label": "old", "caption": None},
+ {"id": 0, "label": "second", "caption": "matched"},
+ ]
+
+
+def test_merge_columns_all_ignored_rows_do_not_create_a_data_snapshot(frames):
+ snapshot = _snapshot(frames)
+ result = frames.merge_columns(pa.table({"id": [99], "label": ["absent"]}),
+ on="id")
+ assert result.updated_rows is None
+ assert result.snapshot_id == snapshot
+ assert _snapshot(frames) == snapshot
+
+
+def test_column_enrichment_on_an_empty_table(tmp_path):
+ connection = pmm.connect(options={"warehouse": str(tmp_path /
"warehouse")})
+ table = connection.create_table("frames", schema=pa.schema([("id",
pa.int64())]),
+ options={"file.format": "parquet"})
+
+ def never_called(batch):
+ raise AssertionError("empty tables have no batches")
+
+ result = table.add_columns(pa.schema([("feature", pa.int64())]),
+ inputs=["id"], fn=never_called)
+ assert result.source_snapshot_id is None
+ assert result.snapshot_id is None
+ assert result.updated_rows == 0
+ result = table.merge_columns(pa.table({"id": [1], "feature": [2]}),
+ on="id")
+ assert result.updated_rows is None
+ assert result.snapshot_id is None
+
+
[email protected]("schema, kwargs", [
+ (pa.schema([("label", pa.string())]), {}),
+ (pa.schema([("feature", pa.int64())]), {"inputs": ["absent"], "fn": lambda
batch: batch}),
+ (pa.schema([pa.field("feature", pa.int64(), nullable=False)]), {}),
+ (pa.schema([("_ROW_ID", pa.int64())]), {}),
+ (pa.schema([("feature", pa.int64())]), {"batch_size": 0}),
+])
+def test_add_columns_validation_never_publishes_schema(frames, schema, kwargs):
+ schema_id = frames.raw_table.table_schema.id
+ with pytest.raises(ValueError):
+ frames.add_columns(schema, **kwargs)
+ assert frames.catalog.get_table(frames.identifier).table_schema.id ==
schema_id
+
+
+def test_enrichment_rejects_historical_views(frames):
+ historical = frames.copy({"scan.snapshot-id": str(_snapshot(frames))})
+ with pytest.raises(ValueError, match="current full-table"):
+ historical.add_columns(pa.schema([("feature", pa.int64())]))
+ with pytest.raises(ValueError, match="current full-table"):
+ historical.merge_columns(pa.table({"id": [0], "label": ["old"]}),
on="id")
+
+
+def test_add_columns_keeps_published_schema_if_schema_response_is_lost(frames):
+ alter_table = frames.catalog.alter_table
+
+ def lost_response(*args, **kwargs):
+ alter_table(*args, **kwargs)
+ raise OSError("lost schema response")
+
+ with patch.object(frames.catalog, "alter_table", lost_response):
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ frames.add_columns(pa.schema([("feature", pa.int64())]))
+
+ assert failure.value.phase == "schema"
+ assert failure.value.schema_changed is None
+ assert failure.value.commit_outcome == "not_started"
+ assert "feature" in frames.catalog.get_table(frames.identifier).field_names
+
+
+def test_schema_only_projection_retains_live_rows_and_row_id_filters(frames):
+ frames.delete("id = 1")
+ frames.add_columns(pa.schema([("feature", pa.int64())]))
+ assert frames.scan().select(["feature"]).to_arrow()["feature"].to_pylist()
== [None] * 4
+ rows = frames.take_row_ids([1, 2,
3]).select(["feature"]).with_row_id().to_list()
+ assert sorted(rows, key=lambda row: row["_ROW_ID"]) == [
+ {"feature": None, "_ROW_ID": 2}, {"feature": None, "_ROW_ID": 3},
+ ]
+
+
+def test_merge_columns_can_clear_and_replace_a_partly_filled_vector(frames):
+ vector_type = pa.list_(pa.float32(), 2)
+ frames.merge_columns(pa.table({"id": [1], "embedding": pa.array([[1.,
2.]], type=vector_type)}), on="id")
+ frames.merge_columns(pa.table({"id": [1, 2], "embedding": pa.array([None,
[3., 4.]], type=vector_type)}), on="id")
+ assert _rows(frames, ["id", "embedding"]) == [
+ {"id": i, "embedding": [3., 4.] if i == 2 else None} for i in range(5)]
+
+
[email protected]("with_media", [False, True])
+def test_merge_columns_inline_nullable_vectors_are_readable(tmp_path,
with_media):
+ from pypaimon import Schema
+
+ connection = pmm.connect(options={"warehouse": str(tmp_path /
"warehouse")})
+ schema = pa.schema([("id", pa.int64())] +
+ ([("image", pa.large_binary())] if with_media else []))
+ connection.catalog.create_database("default", True)
+ connection.catalog.create_table("default.inline",
Schema.from_pyarrow_schema(schema, options={
+ "file.format": "parquet", "data-evolution.enabled": "true",
"row-tracking.enabled": "true",
+ }), False)
+ table = connection.get_table("inline")
+ table.add([dict({"id": i}, **({"image": b"media"} if with_media else {}))
for i in range(3)])
+ vector_type = pa.list_(pa.float32(), 2)
+ table.merge_columns(pa.table({"id": [1], "embedding": pa.array([[1., 2.]],
type=vector_type)}), on="id")
+ table.merge_columns(pa.table({"id": [1, 2], "embedding": pa.array([None,
[3., 4.]], type=vector_type)}), on="id")
+
+ assert _rows(table, ["id", "embedding"]) == [
+ {"id": i, "embedding": [3., 4.] if i == 2 else None} for i in range(3)]
+
+
+def test_merge_columns_keeps_the_callers_table_handle(frames):
+ raw_table = frames.raw_table
+ frames.merge_columns(pa.table({"id": [1], "label": ["new"]}), on="id")
+
+ assert frames.raw_table is raw_table
+ assert frames.table is raw_table
+ assert _rows(frames, ["id", "label"])[1] == {"id": 1, "label": "new"}
+
+
+def
test_merge_columns_empty_source_can_add_schema_without_a_data_snapshot(frames):
+ snapshot = _snapshot(frames)
+ result = frames.merge_columns(
+ pa.table({"id": pa.array([], type=pa.int64()), "caption": pa.array([],
type=pa.string())}),
+ on="id")
+
+ assert result.updated_rows is None
+ assert result.added_columns == ("caption",)
+ assert result.snapshot_id == snapshot
+ assert frames.scan().select(["caption"]).to_arrow()["caption"].to_pylist()
== [None] * 5
+
+
[email protected]_plan
[email protected]("native_read", [False, True])
+def
test_column_enrichment_uses_native_merge_and_shard_without_rewriting_media(frames,
native_read):
+ table = frames.copy({"write.native.enabled": "true",
+ "read.native.enabled": str(native_read).lower()})
+ blobs = _blobs(table)
+ snapshot = _snapshot(table)
+ vector_type = pa.list_(pa.float32(), 2)
+ with patch("pypaimon.execution.python.write.merge_into._build_tables",
+ side_effect=AssertionError("must use native MERGE")):
+ result = table.merge_columns(pa.table({
+ "id": [3, 99], "embedding": pa.array([[3., 4.], [99., 100.]],
type=vector_type),
+ }), on="id")
+ assert result.updated_rows is None
+ assert result.added_columns == ("embedding",)
+ assert _rows(table, ["id", "embedding"]) == [
+ {"id": i, "embedding": [3., 4.] if i == 3 else None} for i in range(5)]
+
+ with
patch("pypaimon.execution.python.write.table_update.ShardTableUpdator.arrow_reader",
+ side_effect=AssertionError("must use native shard")):
+ result = table.add_columns(
+ pa.schema([("image_size", pa.int64())]), inputs=["image"],
+ fn=lambda batch: pa.table({"image_size": [len(value) for value in
batch["image"].to_pylist()]}),
+ batch_size=2)
+ assert result.updated_rows == 5
+ assert _rows(table, ["id", "image_size"]) == [{"id": i, "image_size": 100}
for i in range(5)]
+ assert _blobs(table) == blobs
+ assert table.scan(snapshot_id=snapshot).select(["id",
"label"]).to_arrow().num_rows == 5
+
+
[email protected]_plan
+def test_native_merge_columns_uses_standard_merge_cardinality(frames):
+ frames.add([{"id": 1, "label": "duplicate", "image": b"other"}])
+ table = frames.copy({"write.native.enabled": "true"})
+ with patch("pypaimon.execution.python.write.merge_into._build_tables",
+ side_effect=AssertionError("must use native MERGE")):
+ table.merge_columns(pa.table({
+ "id": pa.array([1, 99, 99, None], type=pa.int64()),
+ "label": ["new", "missing", "duplicate unmatched", "null"],
+ }), on="id")
+ assert table.scan().where("id = 1").select(["label"]).to_list() == [
+ {"label": "new"}, {"label": "new"}]
+ snapshot = _snapshot(table)
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ table.merge_columns(pa.table({"id": [1, 1], "label": ["first",
"second"]}), on="id")
+ assert "multiple source rows" in str(failure.value.__cause__)
+ assert failure.value.commit_outcome == "not_started"
+ assert _snapshot(table) == snapshot
diff --git a/paimon-python/pypaimon/tests/parquet_vector_write_test.py
b/paimon-python/pypaimon/tests/parquet_vector_write_test.py
new file mode 100644
index 0000000000..0d5f8f5012
--- /dev/null
+++ b/paimon-python/pypaimon/tests/parquet_vector_write_test.py
@@ -0,0 +1,137 @@
+# 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 inspect
+from decimal import Decimal
+
+import pyarrow as pa
+import pyarrow.dataset as ds
+import pyarrow.parquet as pq
+import pytest
+
+from pypaimon.execution.python.write.writer.single_file_writer import
SingleFileWriter
+from pypaimon.execution.python.read.reader.format_pyarrow_reader import
FormatPyArrowReader
+from pypaimon.filesystem.local_file_io import LocalFileIO
+from pypaimon.schema.data_types import PyarrowFieldParser
+
+
[email protected]("wrapper", ["vector", "row", "array", "map"])
+def test_streamed_nullable_vectors_preserve_values_and_metadata(tmp_path,
wrapper):
+ vector = pa.list_(pa.field("element", pa.float32(), metadata={b"child":
b"retained"}), 2)
+ if wrapper == "vector":
+ data_type, values = vector, [[1., 2.], None, [3., 4.]]
+ elif wrapper == "row":
+ data_type = pa.struct([pa.field("vector", vector, metadata={b"nested":
b"retained"})])
+ values = [{"vector": [1., 2.]}, {"vector": None}, None]
+ elif wrapper == "array":
+ data_type = pa.list_(vector)
+ values = [[[1., 2.]], [None, [3., 4.]], None]
+ else:
+ data_type = pa.map_(pa.string(), vector, keys_sorted=True)
+ values = [[("a", [1., 2.])], [("b", None)], None]
+ schema = pa.schema([pa.field("feature", data_type, metadata={b"field":
b"retained"})],
+ metadata={b"dataset": b"retained"})
+ data = pa.Table.from_arrays([pa.array(values, type=data_type)],
schema=schema)
+ path = str(tmp_path / "vectors.parquet")
+ writer = SingleFileWriter(LocalFileIO.create(), path, schema, "parquet",
"zstd", 1, [], None)
+ try:
+ # The schema is fixed while the first batch has no NULL vector. A later
+ # batch must remain readable without losing any schema/field metadata.
+ writer.write(data.slice(0, 1))
+ writer.write(data.slice(1))
+ finally:
+ writer.close()
+
+ physical = pq.read_table(path)
+ assert physical.schema.metadata == schema.metadata
+ assert physical.schema.field("feature").metadata ==
schema.field("feature").metadata
+ assert physical.cast(schema).to_pylist() == data.to_pylist()
+ if wrapper == "vector":
+ assert physical.schema.field("feature").type.value_field.metadata ==
{b"child": b"retained"}
+ elif wrapper == "row":
+ assert physical.schema.field("feature").type.field("vector").metadata
== {b"nested": b"retained"}
+
+
[email protected]("wrapper", ["vector", "row", "array", "map"])
[email protected]("selection", ["all", "filter", "rows"])
[email protected]("compliant_lists", [False, True])
+def test_read_nullable_vectors_from_fixed_size_list_parquet_metadata(tmp_path,
wrapper, selection, compliant_lists):
+ vector = pa.list_(pa.field("component", pa.float32(), metadata={b"child":
b"retained"}), 2)
+ if wrapper == "vector":
+ data_type, values = vector, [[1., 2.], None, [3., 4.]]
+ elif wrapper == "row":
+ data_type = pa.struct([pa.field("vector", vector)])
+ values = [{"vector": [1., 2.]}, {"vector": None}, None]
+ elif wrapper == "array":
+ data_type = pa.list_(vector)
+ values = [[[1., 2.]], [[3., 4.]], None]
+ else:
+ data_type = pa.map_(pa.string(), vector, keys_sorted=True)
+ values = [[("a", [1., 2.])], [("b", None)], None]
+ schema = pa.schema([pa.field("id", pa.int64()),
+ pa.field("feature", data_type,
metadata={b"PARQUET:field_id": b"7"})])
+ data = pa.Table.from_arrays([pa.array([0, 1, 2]), pa.array(values,
type=data_type)], schema=schema)
+ path = str(tmp_path / "fixed-size.parquet")
+ # Model native/older writers that preserve fixed-size Arrow metadata.
+ pq.write_table(data, path, row_group_size=2,
use_compliant_nested_type=compliant_lists)
+ reader = FormatPyArrowReader(
+ LocalFileIO.create(), "parquet", path,
PyarrowFieldParser.to_paimon_schema(schema),
+ ds.field("id") >= 1 if selection == "filter" else None,
+ batch_size=1, row_indices=[1, 2] if selection == "rows" else None)
+ try:
+ batches = []
+ while True:
+ batch = reader.read_arrow_batch()
+ if batch is None:
+ break
+ assert batch.num_rows <= 1
+ batches.append(batch)
+ finally:
+ reader.close()
+ expected = data if selection == "all" else data.slice(1)
+ assert pa.Table.from_batches(batches).to_pylist() == expected.to_pylist()
+
+
[email protected]("physical_options", [
+ {"use_deprecated_int96_timestamps": True},
+ {"store_decimal_as_integer": True},
+ {"use_deprecated_int96_timestamps": True, "store_decimal_as_integer":
True},
+])
+def
test_vector_footer_override_preserves_timestamp_and_decimal_encodings(tmp_path,
physical_options):
+ if any(name not in inspect.signature(pq.ParquetWriter).parameters for name
in physical_options):
+ pytest.skip("Parquet physical encoding option is unavailable in this
PyArrow version")
+ schema = pa.schema([("feature", pa.list_(pa.float32(), 2)),
+ ("time", pa.timestamp("us")), ("amount",
pa.decimal128(12, 2))])
+ data = pa.Table.from_arrays([
+ pa.array([[1., 2.], None, [3., 4.]],
type=schema.field("feature").type),
+ pa.array([0, 1000, 2000], type=schema.field("time").type),
+ pa.array([Decimal("1.25"), None, Decimal("3.50")],
type=schema.field("amount").type),
+ ], schema=schema)
+ path = str(tmp_path / "physical-encodings.parquet")
+ pq.write_table(data, path, row_group_size=2, **physical_options)
+ reader = FormatPyArrowReader(
+ LocalFileIO.create(), "parquet", path,
PyarrowFieldParser.to_paimon_schema(schema), None, batch_size=1)
+ try:
+ batches = []
+ while True:
+ batch = reader.read_arrow_batch()
+ if batch is None:
+ break
+ batches.append(batch)
+ finally:
+ reader.close()
+ assert pa.Table.from_batches(batches).to_pylist() == data.to_pylist()