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 cd3657822f [python] Support multimodal column updates by row ID 
(#11044)
cd3657822f is described below

commit cd3657822f175edd83df922c06e53be06e78a063
Author: QuakeWang <[email protected]>
AuthorDate: Tue Nov 10 21:24:37 2026 +0800

    [python] Support multimodal column updates by row ID (#11044)
---
 docs/docs/pypaimon/multimodal-tables.mdx           |  68 ++-
 paimon-python/README.md                            |  26 +-
 .../execution/python/read/scanner/file_scanner.py  |   3 +-
 paimon-python/pypaimon/multimodal/columns.py       |  58 ++-
 paimon-python/pypaimon/multimodal/table.py         |  55 ++-
 .../pypaimon/tests/multimodal_columns_test.py      | 535 ++++++++++++++++++++-
 .../pypaimon/tests/multimodal_table_test.py        | 157 ++++++
 paimon-python/pypaimon/tests/range_test.py         |   5 +
 8 files changed, 894 insertions(+), 13 deletions(-)

diff --git a/docs/docs/pypaimon/multimodal-tables.mdx 
b/docs/docs/pypaimon/multimodal-tables.mdx
index a1744441d7..943121ff28 100644
--- a/docs/docs/pypaimon/multimodal-tables.mdx
+++ b/docs/docs/pypaimon/multimodal-tables.mdx
@@ -255,8 +255,27 @@ docs.update(
     where="id = 2",
     values={"category": "docs"},
 )
+
+# Target a row using a row ID obtained from this table.
+docs.update(where="_ROW_ID = 42", values={"category": "docs"})
 ```
 
+On row-tracking tables, `update` accepts `_ROW_ID` conditions, including `IN`
+and combinations with business-column predicates using `AND` or `OR`.
+Only matching visible rows are updated; missing or deleted row IDs do not
+match, and no rows are inserted. `_ROW_ID` cannot be assigned a new value.
+The method returns the table and uses the existing predicate-update backend.
+For external per-row values with strict matching of every supplied ID, use
+`update_columns_by_row_id` instead.
+Updates with `_ROW_ID` predicates require the handle's schema to match the
+current target branch. Reopen the table after schema changes or a branch copy
+with a different schema; mismatches are rejected before writing.
+
+`_ROW_ID` conditions are currently supported only by `update`, not by
+`delete` or `scan().where(...)`. Calling `with_row_id()` on a scan adds the
+ID to its output; it does not enable `_ROW_ID` string conditions. Use
+`take_row_ids(...)` for lookups by row ID.
+
 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).
@@ -301,6 +320,12 @@ frames.add_columns(pa.schema([("caption", pa.string())]))
 # Recompute an existing column without changing its schema.
 result = frames.compute_columns(
     ["image_size"], inputs=["image"], fn=image_sizes, batch_size=128)
+
+# Import annotations carrying row IDs from this table, in any order.
+result = frames.update_columns_by_row_id(pa.table({
+    "_ROW_ID": pa.array([1, 0], type=pa.int64()),
+    "label": ["vehicle", "pedestrian"],
+}), columns=["label"])
 ```
 
 For embeddings, declare a fixed-size list such as
@@ -334,14 +359,41 @@ 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.
 
+`update_columns_by_row_id(data, *, columns)` accepts one local Arrow Table
+and requires an explicit output column name or sequence of names. The input
+must contain `_ROW_ID` and each selected output column exactly once. Only
+selected columns are written; extra input columns are ignored, so carrying old
+values for other columns does not overwrite their current values.
+IDs must be unique, non-NULL,
+non-negative integers representable as int64. All IDs must identify visible 
rows
+in the captured snapshot; missing or deleted IDs reject the entire call before
+writing. Input order does not affect matching, even when business keys repeat.
+Outputs must be existing, non-partition columns with the table's types and
+nullability. Other system columns and video-frame outputs are rejected; use
+`replace_video` for video-frame columns. Omitted rows keep their values and
+explicit NULL values clear nullable outputs. No rows or columns are added.
+Empty input creates no data snapshot. The method does not remap historical row
+IDs or determine whether external annotations are stale.
+A table schema that differs from the current target branch is rejected before
+writing; reopen the table after external schema changes or a branch copy with
+a different schema.
+
+Rollback followed by a new append can reuse both row IDs and numeric snapshot
+IDs. Discard pending annotations from the rolled-back history before writing
+them back. A matching numeric snapshot ID alone does not establish that those
+annotations are still valid.
+
 `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` and `compute_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.
+`update_columns_by_row_id` uses the standard row-ID update backend with the 
same
+native selection rules. ID visibility checks and writing use the same captured
+snapshot, and all prepared updates are committed together.
 
-All three methods retain files for untouched columns. Computing an image 
embedding
+All four 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` and `compute_columns` buffer outputs per 
original
@@ -360,7 +412,8 @@ Successful calls return `ColumnUpdateResult` with added 
column names,
 the source and final data snapshot IDs, and the schema ID. `updated_rows` is 
the
 computed row count for `add_columns` (zero for schema-only additions) and
 `compute_columns`, and `None` for `merge_columns`, because MERGE does not 
return
-logical row counts. `compute_columns` returns `added_columns=()` and leaves
+logical row counts. `update_columns_by_row_id` reports the input row count in
+`updated_rows`. Both it and `compute_columns` return `added_columns=()` and 
leave
 the schema unchanged on success or failure. Schema-only changes
 leave the data snapshot ID unchanged. Schema publication and data publication
 are separate operations. Failures during schema publication or data preparation
@@ -369,13 +422,15 @@ and commit raise
 
 | Attribute | Meaning |
 | --- | --- |
-| `phase` | The stage that failed: schema, compute, write, commit, result, or 
close |
+| `phase` | The stage that failed: schema, validate, 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
+Input shape and type validation errors remain ordinary exceptions. Missing or
+deleted row IDs raise `ColumnUpdateError` with `phase="validate"` and
+`commit_outcome="not_started"`. 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
@@ -384,8 +439,9 @@ or delete prepared files after a commit error.
 
 ## Delete
 
-`delete` removes rows matched by a SQL-like predicate. It uses the same
-predicate syntax as `scan().where(...)` and `update(...)`. Row-level deletes
+`delete` removes rows matched by a SQL-like predicate on business columns.
+It shares business-column predicate syntax with `scan().where(...)` and
+`update(...)`; `_ROW_ID` conditions are supported only by `update`. Row-level 
deletes
 require `deletion-vectors.enabled` set to `true` when creating the table.
 On partitioned tables, a predicate that references only partition columns uses
 the partition drop path.
diff --git a/paimon-python/README.md b/paimon-python/README.md
index ffdec9cf9f..63f3c91f83 100644
--- a/paimon-python/README.md
+++ b/paimon-python/README.md
@@ -144,6 +144,9 @@ result = table.add_columns(schema=nullable_columns)
 # Fill existing columns, or recompute them after changing the model.
 result = table.compute_columns(
     ["embedding"], inputs=["image"], fn=compute_embeddings, batch_size=128)
+
+# Import external annotations carrying _ROW_ID and existing output columns.
+result = table.update_columns_by_row_id(annotations, columns=["label"])
 ```
 
 `table` is a `pypaimon.multimodal.MultimodalTable`. `merge_columns` uses 
ordinary
@@ -170,10 +173,31 @@ MERGE when `write.native.enabled=true` and a compatible 
`pypaimon_rust` is avail
 `add_columns` and `compute_columns` can use the native shard reader and writer;
 their `fn` runs in Python.
 
+`update_columns_by_row_id(data, *, columns)` accepts one Arrow Table and 
requires
+an explicit output column name or sequence of names. The input must contain
+`_ROW_ID` and each selected column exactly once. Extra input columns are 
ignored
+and cannot overwrite the corresponding current table values. `_ROW_ID` must 
contain
+unique, non-NULL, non-negative integers representable as int64. Every ID must
+identify a visible row in the captured snapshot; missing or deleted IDs reject
+the entire call before writing. Input order does not affect matching. Outputs
+must be existing, non-partition columns with the table's types and nullability;
+use `replace_video` for video-frame outputs. Omitted rows keep their values and
+untouched columns retain their files. The method uses the standard 
Python/native
+row-ID update backend and commits all updates together. Empty input creates no
+snapshot. A schema mismatch with the current target branch is rejected before
+writing; reopen the table after schema changes or copying to a branch with a
+different schema. It does not insert rows, add columns, remap
+historical IDs, or check whether external results are stale.
+
+Rollback followed by a new append can reuse both row IDs and numeric snapshot
+IDs. Discard pending annotations from the rolled-back history before writeback;
+a matching numeric snapshot ID alone does not prove that they remain valid.
+
 `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 `compute_columns`, and 
`None`
-for `merge_columns`. `compute_columns` always returns `added_columns=()`.
+for `merge_columns`. `update_columns_by_row_id` returns the input row count in
+`updated_rows`. Both it and `compute_columns` always return `added_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`,
diff --git 
a/paimon-python/pypaimon/execution/python/read/scanner/file_scanner.py 
b/paimon-python/pypaimon/execution/python/read/scanner/file_scanner.py
index b3caa043ca..b565f2147c 100755
--- a/paimon-python/pypaimon/execution/python/read/scanner/file_scanner.py
+++ b/paimon-python/pypaimon/execution/python/read/scanner/file_scanner.py
@@ -110,7 +110,8 @@ def _row_ranges_from_predicate(predicate: 
Optional[Predicate]) -> Optional[List]
         if p.method == 'between':
             if not p.literals or len(p.literals) < 2:
                 return []
-            return [Range(int(p.literals[0]), int(p.literals[1]))]
+            lower, upper = int(p.literals[0]), int(p.literals[1])
+            return [Range(lower, upper)] if lower <= upper else []
         return None
 
     return visit(predicate)
diff --git a/paimon-python/pypaimon/multimodal/columns.py 
b/paimon-python/pypaimon/multimodal/columns.py
index 1ae6412f86..7141461e19 100644
--- a/paimon-python/pypaimon/multimodal/columns.py
+++ b/paimon-python/pypaimon/multimodal/columns.py
@@ -21,11 +21,12 @@ from dataclasses import dataclass
 from typing import Optional, Tuple
 
 import pyarrow as pa
+import pyarrow.compute as pc
 
 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,
+    _to_arrow_table, _validate_merge_on, _validate_row_id_update_schema,
 )
 from pypaimon.schema.arrow_schema import normalize_arrow_write_nullability
 from pypaimon.schema.data_types import PyarrowFieldParser
@@ -33,6 +34,8 @@ 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.utils.range import Range
+from pypaimon.write.row_input import normalize_row_ids
 from pypaimon.write.update_validation import _authorize_update
 
 
@@ -40,7 +43,8 @@ from pypaimon.write.update_validation import _authorize_update
 class ColumnUpdateResult:
     """Schema and data versions produced by a successful column operation.
 
-    ``updated_rows`` is available for ``add_columns`` and ``compute_columns``
+    ``updated_rows`` is available for ``add_columns``, ``compute_columns``,
+    and ``update_columns_by_row_id``
     and is ``None`` for ``merge_columns``, whose MERGE executor does not return
     logical row counts.
     """
@@ -240,6 +244,56 @@ def merge_columns(owner, data, *, on):
         return operation.finish(None, commit=commit, messages=messages)
 
 
+def update_columns_by_row_id(owner, data, *, columns):
+    if not isinstance(data, pa.Table):
+        raise ValueError("data must be a pyarrow.Table.")
+    raw = owner.raw_table
+    _validate_update(raw)
+    if not raw.options.data_evolution_enabled() or not 
raw.options.row_tracking_enabled():
+        raise ValueError("Row ID column updates require a Data Evolution table 
with row tracking.")
+    _validate_row_id_update_schema(owner)
+    row_id = SpecialFields.ROW_ID.name
+    if data.column_names.count(row_id) != 1:
+        raise ValueError("Input must contain exactly one _ROW_ID column.")
+    columns = [columns] if isinstance(columns, str) else list(columns)
+    _validate_names(columns, "Output")
+    missing = set(columns).difference(raw.field_names)
+    if missing:
+        raise ValueError("Output columns do not exist: %s" % sorted(missing))
+    if set(columns).intersection(raw.partition_keys):
+        raise ValueError("update_columns_by_row_id cannot update partition 
columns.")
+    if set(columns).intersection(raw.options.video_frame_fields()):
+        raise ValueError("Use replace_video() to update video-frame columns.")
+    for name in columns:
+        if data.column_names.count(name) != 1:
+            raise ValueError("Input must contain exactly one %s column." % 
name)
+    row_ids = normalize_row_ids(data[row_id])
+    if len(pc.unique(row_ids)) != data.num_rows:
+        raise ValueError("Input data contains duplicate _ROW_ID values.")
+    if data.num_rows and pc.min(row_ids).as_py() < 0:
+        raise ValueError("_ROW_ID values must be non-negative.")
+    target_schema = _target_schema(raw)
+    schema = pa.schema([target_schema.field(name) for name in columns])
+    source = _normalize_output(data.select(columns), 
schema).append_column(row_id, row_ids)
+    with _ColumnUpdate(owner, raw) as operation:
+        if source.num_rows == 0:
+            return operation.finish(0)
+        operation.phase = "validate"
+        table = raw._copy_with_snapshot(operation.snapshot)
+        read = table.new_read_builder().with_projection([row_id])
+        # Read only the requested row IDs, retaining deletion-vector filtering.
+        plan = 
read.new_scan().with_row_ranges(Range.to_ranges(row_ids.to_pylist())).plan_all()
+        visible = read.new_read().to_arrow(plan.splits())[row_id]
+        missing = pc.is_null(pc.index_in(row_ids, value_set=visible))
+        if pc.any(missing).as_py():
+            raise ValueError("Row IDs not found or deleted: %s" % 
row_ids.filter(missing).to_pylist())
+        operation.phase = "write"
+        builder = table.new_batch_write_builder()
+        commit = operation.keep(builder.new_commit())
+        messages = 
builder.new_update().with_update_type(columns).update_by_arrow_with_row_id(source)
+        return operation.finish(source.num_rows, 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.")
diff --git a/paimon-python/pypaimon/multimodal/table.py 
b/paimon-python/pypaimon/multimodal/table.py
index fd2e99a9bf..45206596d1 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -24,6 +24,7 @@ import pyarrow as pa
 import pyarrow.compute as pc
 
 from pypaimon.common.options.core_options import CoreOptions
+from pypaimon.common.where_parser import parse_where_clause
 from pypaimon.multimodal.query import (
     BatchVectorQuery,
     HybridQuery,
@@ -40,6 +41,7 @@ from pypaimon.table.data_evolution_merge_into import (
     source_col as _source_col,
 )
 from pypaimon.table.special_fields import SpecialFields
+from pypaimon.write.update_validation import predicate_fields
 
 
 _ALL_SOURCE_COLUMNS = object()
@@ -415,6 +417,15 @@ class MultimodalTable:
         return self
 
     def update(self, where, values):
+        """Update visible rows matching a SQL-like predicate and return this 
table.
+
+        Row-tracking tables also accept ``_ROW_ID`` predicates. Missing or
+        deleted rows do not match. ``_ROW_ID`` is read-only. Use
+        ``update_columns_by_row_id`` for external per-row values with strict
+        ID matching. Row-ID predicates require a current table schema; reopen
+        the table after external schema changes or a branch copy with a
+        different schema.
+        """
         video_columns = self.raw_table.options.video_frame_fields()
         if isinstance(values, Mapping):
             assigned_video_columns = video_columns.intersection(values)
@@ -424,8 +435,12 @@ class MultimodalTable:
                     "replace_video() with a complete encoded video."
                     % sorted(assigned_video_columns)[0]
                 )
-        query = self.scan().where(where)
-        predicate = query._predicate
+        if isinstance(where, str) and 
self.raw_table.options.row_tracking_enabled():
+            predicate = parse_where_clause(where, 
SpecialFields.row_type_with_row_id(self.raw_table.fields))
+        else:
+            predicate = self.scan().where(where)._predicate
+        if predicate is not None and SpecialFields.ROW_ID.name in 
predicate_fields(predicate):
+            _validate_row_id_update_schema(self)
         write_builder = self.raw_table.new_batch_write_builder()
         table_update = write_builder.new_update()
         table_commit = write_builder.new_commit()
@@ -539,6 +554,35 @@ class MultimodalTable:
         from pypaimon.multimodal.columns import add_columns
         return add_columns(self, schema, inputs=inputs, fn=fn, 
batch_size=batch_size)
 
+    def update_columns_by_row_id(self, data, *, columns):
+        """Update existing columns from one local Arrow table containing 
``_ROW_ID``.
+
+        ``columns`` is a required column name or sequence of output names.
+        Only those columns are written; other input columns are ignored.
+        IDs must be unique, non-NULL, non-negative integers representable as
+        int64. Every ID must identify a visible row in the captured source
+        snapshot. Input order does not affect matching. Outputs must be 
existing,
+        non-partition columns with the table's types and nullability; use 
``replace_video``
+        for video-frame columns. Omitted rows keep their values, and untouched
+        columns retain their files. No columns or rows are added.
+
+        Validation and writing use one snapshot and the standard update 
backend.
+        All prepared updates are committed together. Requires a current
+        full-table Data Evolution view and a single writer for the entire call.
+        A schema mismatch with the current target branch is rejected before
+        writing; reopen the table after external schema changes or a branch
+        copy with a different schema.
+        IDs from historical results are not remapped or checked for staleness.
+        Rollback followed by an append can reuse row IDs and numeric snapshot
+        IDs. Discard pending annotations from the rolled-back history before
+        writing them back; a matching numeric snapshot ID does not prove 
validity.
+        Returns :class:`pypaimon.multimodal.ColumnUpdateResult` with the input
+        row count in ``updated_rows`` and ``added_columns=()``. Empty input
+        creates no data snapshot. There are no automatic retries.
+        """
+        from pypaimon.multimodal.columns import update_columns_by_row_id
+        return update_columns_by_row_id(self, data, columns=columns)
+
     def compute_columns(self, columns, *, inputs, fn, batch_size=1024):
         """Compute existing columns for all visible rows without changing the 
schema.
 
@@ -989,6 +1033,13 @@ def _time_travel_table(table, snapshot_id=None, 
tag_name=None):
     return table
 
 
+def _validate_row_id_update_schema(owner):
+    raw = owner.raw_table
+    current = owner.catalog.get_table(raw.identifier)
+    if current.table_schema.id != raw.table_schema.id or current.fields != 
raw.fields:
+        raise ValueError("Table schema has changed. Reopen the table before 
updating columns by row ID.")
+
+
 def _target_schema(table):
     return PyarrowFieldParser.from_paimon_schema(table.table_schema.fields)
 
diff --git a/paimon-python/pypaimon/tests/multimodal_columns_test.py 
b/paimon-python/pypaimon/tests/multimodal_columns_test.py
index bfd353b278..572ba8f3f4 100644
--- a/paimon-python/pypaimon/tests/multimodal_columns_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_columns_test.py
@@ -546,7 +546,7 @@ def 
test_compute_columns_rejects_video_frame_outputs(tmp_path):
         table.compute_columns(["video"], inputs=["id"], fn=lambda batch: batch)
 
 
[email protected]("method", ["merge_columns", "compute_columns"])
[email protected]("method", ["merge_columns", "compute_columns", 
"update_columns_by_row_id"])
 def test_column_updates_preserve_files_if_commit_response_is_lost(frames, 
method):
     commit = BatchTableCommit.commit
 
@@ -559,6 +559,8 @@ def 
test_column_updates_preserve_files_if_commit_response_is_lost(frames, method
         with pytest.raises(pmm.ColumnUpdateError) as failure:
             if method == "merge_columns":
                 frames.merge_columns(pa.table({"id": [0], "label": 
["committed"]}), on="id")
+            elif method == "update_columns_by_row_id":
+                frames.update_columns_by_row_id(pa.table({"_ROW_ID": [0], 
"label": ["committed"]}), columns=["label"])
             else:
                 frames.compute_columns(["label"], inputs=["id"], fn=lambda 
batch: pa.table({
                     "label": ["committed"] * batch.num_rows}))
@@ -652,6 +654,8 @@ def test_enrichment_rejects_historical_views(frames):
         historical.merge_columns(pa.table({"id": [0], "label": ["old"]}), 
on="id")
     with pytest.raises(ValueError, match="current full-table"):
         historical.compute_columns(["label"], inputs=["label"], fn=lambda 
batch: batch)
+    with pytest.raises(ValueError, match="current full-table"):
+        historical.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "label": 
["old"]}), columns=["label"])
 
 
 @pytest.mark.parametrize("options", [
@@ -796,3 +800,532 @@ def 
test_native_merge_columns_uses_standard_merge_cardinality(frames):
     assert "multiple source rows" in str(failure.value.__cause__)
     assert failure.value.commit_outcome == "not_started"
     assert _snapshot(table) == snapshot
+
+
[email protected]("id_type", [pa.int8(), pa.int64(), pa.uint64()])
+def 
test_update_columns_by_row_id_matches_duplicate_keys_without_rewriting_media(frames,
 id_type):
+    frames.add([{"id": 1, "label": "duplicate", "image": b"other"}])
+    raw = frames.raw_table
+    snapshot = _snapshot(frames)
+    schema_id = raw.table_schema.id
+    files, blobs = set(_files(frames)), _blobs(frames)
+    data = pa.table({"label": ["second", "first"], "_ROW_ID": pa.chunked_array(
+        [[5], [1]], type=id_type)})
+    with patch.object(raw.file_io, "read_ranges_coalesced",
+                      side_effect=AssertionError("must not fetch media")):
+        result = frames.update_columns_by_row_id(data, columns="label")
+
+    assert isinstance(result, pmm.ColumnUpdateResult)
+    assert result.source_snapshot_id == snapshot
+    assert result.snapshot_id == snapshot + 1
+    assert result.schema_id == schema_id
+    assert result.updated_rows == 2
+    assert result.added_columns == ()
+    assert frames.raw_table is raw
+    actual = frames.scan().select(["id", 
"label"]).with_row_id().to_arrow().sort_by("_ROW_ID")
+    assert actual["id"].to_pylist() == [0, 1, 2, 3, 4, 1]
+    assert actual["label"].to_pylist() == ["old", "first", "old", "old", 
"old", "second"]
+    assert _blobs(frames) == blobs
+    assert files.issubset(_files(frames))
+    assert all(file.write_cols == ["label"] for name, file in 
_files(frames).items() if name not in files)
+    assert 
frames.scan(snapshot_id=snapshot).select(["label"]).to_arrow()["label"].to_pylist()
 == [
+        "old", "old", "old", "old", "old", "duplicate"]
+
+
+def test_update_columns_by_row_id_only_writes_explicit_columns(frames):
+    frames.add_columns(pa.schema([("score", pa.int64())]))
+    frames.update("id = 1", {"label": "current"})
+    files, blobs = set(_files(frames)), _blobs(frames)
+    payload = pa.table({
+        "_ROW_ID": [1], "id": [999], "label": ["old"],
+        "image": pa.array([b"stale media"], type=pa.large_binary()), "score": 
[42], "unused": ["ignored"]})
+    with patch.object(frames.raw_table.file_io, "read_ranges_coalesced",
+                      side_effect=AssertionError("must not fetch media")):
+        result = frames.update_columns_by_row_id(payload, columns=["score"])
+    assert result.updated_rows == 1
+    assert result.added_columns == ()
+    assert _rows(frames, ["id", "label", "score"]) == [
+        {"id": i, "label": "current" if i == 1 else "old", "score": 42 if i == 
1 else None} for i in range(5)]
+    assert _blobs(frames) == blobs
+    assert all(file.write_cols == ["score"] for name, file in 
_files(frames).items() if name not in files)
+
+
+def test_update_columns_by_row_id_requires_explicit_columns(frames):
+    snapshot = _snapshot(frames)
+    with pytest.raises(TypeError, match="columns"):
+        frames.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "label": 
["new"]}))
+    assert _snapshot(frames) == snapshot
+
+
[email protected]("row_count", [0, 1])
[email protected]("method", ["batch", "predicate"])
+def test_row_id_updates_reject_stale_schema_before_staging(frames, row_count, 
method):
+    from pypaimon.schema.data_types import AtomicType
+    from pypaimon.schema.schema_change import SchemaChange
+
+    connection = pmm.MultimodalConnection(frames.catalog)
+    table = connection.get_table(frames.identifier)
+    raw = table.raw_table
+    snapshot, files = _snapshot(table), set(_files(table))
+    table.catalog.alter_table(table.identifier, [
+        SchemaChange.drop_column("label"), SchemaChange.add_column("label", 
AtomicType("STRING"))])
+    current = connection.get_table(table.identifier)
+    assert current.raw_table.field_dict["label"].id != 
raw.field_dict["label"].id
+    assert _snapshot(current) == snapshot
+    assert 
current.raw_table.snapshot_manager().get_latest_snapshot().schema_id == 
raw.table_schema.id
+    data = pa.table({"_ROW_ID": pa.array([0][:row_count], type=pa.int64()),
+                     "label": pa.array(["new"][:row_count], type=pa.string())})
+    with 
patch("pypaimon.table.file_store_table.FileStoreTable.new_batch_write_builder",
+               side_effect=AssertionError("must not stage files")):
+        with pytest.raises(ValueError, match="schema has changed.*Reopen"):
+            if method == "batch":
+                table.update_columns_by_row_id(data, columns=["label"])
+            else:
+                table.update("_ROW_ID = %s" % (0 if row_count else 999999), 
{"label": "new"})
+    assert table.raw_table is raw
+    assert _snapshot(current) == snapshot
+    assert set(_files(current)) == files
+    assert current.scan().select(["label"]).to_list() == [{"label": None}] * 5
+
+    if method == "batch":
+        result = current.update_columns_by_row_id(
+            pa.table({"_ROW_ID": [0], "label": ["new"]}), columns=["label"])
+        assert result.updated_rows == 1
+        assert result.schema_id == current.raw_table.table_schema.id
+    else:
+        assert current.update("_ROW_ID = 0", {"label": "new"}) is current
+    assert _rows(connection.get_table(table.identifier), ["id", "label"]) == [
+        {"id": i, "label": "new" if i == 0 else None} for i in range(5)]
+
+
[email protected]("method", ["batch", "predicate"])
+def test_row_id_updates_do_not_write_if_schema_lookup_fails(frames, method):
+    snapshot, files = _snapshot(frames), set(_files(frames))
+    with patch.object(frames.catalog, "get_table", side_effect=OSError("schema 
lookup failed")):
+        with 
patch("pypaimon.table.file_store_table.FileStoreTable.new_batch_write_builder",
+                   side_effect=AssertionError("must not stage files")):
+            with pytest.raises(OSError, match="schema lookup failed"):
+                if method == "batch":
+                    frames.update_columns_by_row_id(pa.table({"_ROW_ID": [0], 
"label": ["new"]}), columns=["label"])
+                else:
+                    frames.update("id = 1 OR (_ROW_ID = 0 AND label = 'old')", 
{"label": "new"})
+    assert _snapshot(frames) == snapshot
+    assert set(_files(frames)) == files
+
+
+def 
test_update_columns_by_row_id_checks_current_branch_schema_and_keeps_dynamic_options(frames):
+    from pypaimon.schema.data_types import AtomicType
+    from pypaimon.schema.schema_change import SchemaChange
+
+    connection = pmm.MultimodalConnection(frames.catalog)
+    frames.catalog.create_tag(frames.identifier, "base", _snapshot(frames))
+    frames.catalog.create_branch(frames.identifier, "dev", tag_name="base")
+    frames.catalog.alter_table(frames.identifier, 
[SchemaChange.add_column("score", AtomicType("INT"))])
+    table = connection.get_table(frames.identifier + 
"$branch_dev").copy({"write.native.enabled": "false"})
+    raw = table.raw_table
+    assert raw.table_schema.id != 
connection.get_table(frames.identifier).raw_table.table_schema.id
+    result = table.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "label": 
["branch"]}), columns=["label"])
+    assert result.updated_rows == 1
+    assert result.schema_id == raw.table_schema.id
+    assert table.raw_table is raw
+    assert not raw.options.native_write_enabled()
+    assert _rows(connection.get_table(table.identifier), ["id", "label"]) == [
+        {"id": i, "label": "branch" if i == 0 else "old"} for i in range(5)]
+    assert 
connection.get_table(frames.identifier).scan().select(["label"]).to_list() == 
[{"label": "old"}] * 5
+
+
[email protected]("method", ["batch", "predicate"])
+def 
test_row_id_updates_reject_branch_copy_with_same_schema_id_and_different_field_ids(frames,
 method):
+    from pypaimon.schema.data_types import AtomicType
+    from pypaimon.schema.schema_change import Move, SchemaChange
+
+    connection = pmm.MultimodalConnection(frames.catalog)
+    frames.catalog.create_tag(frames.identifier, "base", _snapshot(frames))
+    frames.catalog.create_branch(frames.identifier, "dev", tag_name="base")
+    frames.catalog.alter_table(frames.identifier, 
[SchemaChange.set_option("read.batch-size", "3")])
+    identifier = frames.identifier + "$branch_dev"
+    frames.catalog.alter_table(identifier, [
+        SchemaChange.drop_column("label"),
+        SchemaChange.add_column("label", AtomicType("STRING"), 
move=Move.before("label", "image"))])
+    copied = connection.get_table(frames.identifier).copy({"branch": "dev"})
+    current = connection.get_table(identifier)
+    assert copied.raw_table.table_schema.id == 
current.raw_table.table_schema.id
+    assert copied.raw_table.field_names == current.raw_table.field_names
+    assert [field.type for field in copied.raw_table.fields] == [field.type 
for field in current.raw_table.fields]
+    assert copied.raw_table.field_dict["label"].id != 
current.raw_table.field_dict["label"].id
+    snapshot, files = _snapshot(current), set(_files(current))
+    with 
patch("pypaimon.table.file_store_table.FileStoreTable.new_batch_write_builder",
+               side_effect=AssertionError("must not stage files")):
+        with pytest.raises(ValueError, match="schema has changed.*Reopen"):
+            if method == "batch":
+                copied.update_columns_by_row_id(pa.table({"_ROW_ID": [0], 
"label": ["new"]}), columns=["label"])
+            else:
+                copied.update("_ROW_ID = 0", {"label": "new"})
+    assert _snapshot(current) == snapshot
+    assert set(_files(current)) == files
+    assert current.scan().select(["label"]).to_list() == [{"label": None}] * 5
+    if method == "batch":
+        current.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "label": 
["new"]}), columns=["label"])
+    else:
+        current.update("_ROW_ID = 0", {"label": "new"})
+    assert _rows(connection.get_table(identifier), ["id", "label"]) == [
+        {"id": i, "label": "new" if i == 0 else None} for i in range(5)]
+
+
+def 
test_business_predicate_with_row_id_string_literal_does_not_check_schema(frames):
+    snapshot = _snapshot(frames)
+    with patch.object(frames.catalog, "get_table", 
side_effect=AssertionError("must not check schema")):
+        assert frames.update("label = '_ROW_ID'", {"label": "new"}) is frames
+    assert _snapshot(frames) == snapshot
+
+
[email protected]("row_order", [
+    pytest.param([0, 1, 2, 3, 4, 5], id="a-first"),
+    pytest.param([3, 4, 5, 0, 1, 2], id="b-first"),
+])
+def 
test_update_columns_by_row_id_preserves_deletions_and_crosses_partitions(tmp_path,
 row_order):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    table = connection.create_table(
+        "partitioned", schema=pa.schema([("part", pa.string()), ("id", 
pa.int64()), ("label", pa.string())]),
+        partitioned=["part"],
+        data=[{"part": "a" if i < 3 else "b", "id": i, "label": "old"} for i 
in row_order],
+        options={"file.format": "parquet", "deletion-vectors.enabled": "true"})
+    table.delete("id = 1 OR id = 4")
+    row_ids = {row["id"]: row["_ROW_ID"] for row in 
table.scan().select(["id"]).with_row_id().to_list()}
+    snapshot = _snapshot(table)
+    commit = BatchTableCommit.commit
+    with patch.object(BatchTableCommit, "commit", autospec=True, 
side_effect=commit) as publish:
+        result = table.update_columns_by_row_id(pa.table({
+            "_ROW_ID": [row_ids[5], row_ids[0]], "label": ["last", None]}), 
columns=["label"])
+    publish.assert_called_once()
+    messages = publish.call_args[0][1]
+    assert len(messages) == 2
+    assert all(message.check_from_snapshot == snapshot for message in messages)
+    assert result.source_snapshot_id == snapshot
+    assert result.snapshot_id == snapshot + 1
+    assert result.updated_rows == 2
+    assert _rows(table, ["id", "label"]) == [
+        {"id": 0, "label": None}, {"id": 2, "label": "old"},
+        {"id": 3, "label": "old"}, {"id": 5, "label": "last"}]
+
+
[email protected]("ids, error, message", [
+    (pa.array([1.0]), TypeError, "integer Arrow"),
+    (pa.array([1.5]), TypeError, "integer Arrow"),
+    (pa.array([True]), TypeError, "integer Arrow"),
+    (pa.array(["1"]), TypeError, "integer Arrow"),
+    (pa.nulls(1), TypeError, "integer Arrow"),
+    (pa.array([None], type=pa.int64()), ValueError, "must not be null"),
+    (pa.chunked_array([[1], [1]], type=pa.int64()), ValueError, "duplicate 
_ROW_ID"),
+    (pa.array([-1]), ValueError, "non-negative"),
+    (pa.array([2 ** 63], type=pa.uint64()), ValueError, "range"),
+])
+def test_update_columns_by_row_id_rejects_invalid_ids_before_writing(frames, 
ids, error, message):
+    from pypaimon.write.table_update import BatchTableUpdate
+
+    snapshot, files = _snapshot(frames), set(_files(frames))
+    with patch.object(BatchTableUpdate, "update_by_arrow_with_row_id",
+                      side_effect=AssertionError("must not write")):
+        with pytest.raises(error, match=message):
+            frames.update_columns_by_row_id(pa.table({"_ROW_ID": ids, "label": 
["new"] * len(ids)}), columns=["label"])
+    assert _snapshot(frames) == snapshot
+    assert set(_files(frames)) == files
+
+
[email protected]("data, columns, message", [
+    ([{"_ROW_ID": 0, "label": "new"}], ["label"], "pyarrow.Table"),
+    (pa.record_batch([pa.array([0]), pa.array(["new"])], names=["_ROW_ID", 
"label"]), ["label"], "pyarrow.Table"),
+    (pa.table({"label": ["new"]}), ["label"], "exactly one _ROW_ID"),
+    (pa.table({"_ROW_ID": [0]}), [], "unique column names"),
+    (pa.table({"_ROW_ID": [0], "absent": ["new"]}), ["absent"], "Output 
columns do not exist"),
+    (pa.table({"_ROW_ID": [0], "_SEQUENCE_NUMBER": [1]}), 
["_SEQUENCE_NUMBER"], "system columns"),
+    (pa.table({"_ROW_ID": [0], "label": [123]}), ["label"], "Incompatible 
type"),
+    (pa.table({"_ROW_ID": [0], "label": ["new"]}), ["id"], "exactly one id 
column"),
+    (pa.table({"_ROW_ID": [0], "label": ["new"]}), ["label", "label"], "unique 
column names"),
+    (pa.table({"_ROW_ID": [0], "label": ["new"]}), ["_ROW_ID"], "system 
columns"),
+    (pa.table([pa.array([0]), pa.array([0]), pa.array(["new"])],
+              names=["_ROW_ID", "_ROW_ID", "label"]), ["label"], "exactly one 
_ROW_ID"),
+    (pa.table([pa.array([0]), pa.array(["a"]), pa.array(["b"])],
+              names=["_ROW_ID", "label", "label"]), ["label"], "exactly one 
label column"),
+])
+def 
test_update_columns_by_row_id_validates_input_without_schema_changes(frames, 
data, columns, message):
+    snapshot, schema_id = _snapshot(frames), frames.raw_table.table_schema.id
+    with patch.object(frames.catalog, "alter_table", 
side_effect=AssertionError("must not alter schema")):
+        with pytest.raises(ValueError, match=message):
+            frames.update_columns_by_row_id(data, columns=columns)
+    assert _snapshot(frames) == snapshot
+    assert frames.catalog.get_table(frames.identifier).table_schema.id == 
schema_id
+
+
[email protected]("options, message", [
+    ({"data-evolution.enabled": "false"}, "Data Evolution"),
+    ({"row-tracking.enabled": "false"}, "row tracking"),
+    ({"scan.mode": "from-snapshot"}, "current full-table"),
+    ({"incremental-between": "1,2"}, "current full-table"),
+    ({"scan.file-creation-time-millis": "1"}, "current full-table"),
+])
+def test_update_columns_by_row_id_rejects_unsupported_views(frames, options, 
message):
+    snapshot = _snapshot(frames)
+    with pytest.raises(ValueError, match=message):
+        frames.copy(options).update_columns_by_row_id(pa.table({"_ROW_ID": 
[0], "label": ["new"]}), columns=["label"])
+    assert _snapshot(frames) == snapshot
+
+
+def 
test_update_columns_by_row_id_rejects_partition_and_video_outputs(tmp_path):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    table = connection.create_table(
+        "videos", schema=pa.schema([("part", pa.string()), ("video", 
pa.large_binary())]),
+        partitioned=["part"], options={"video-frame-field": "video"})
+    with pytest.raises(ValueError, match="partition columns"):
+        table.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "part": 
["new"]}), columns=["part"])
+    with pytest.raises(ValueError, match="replace_video"):
+        table.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "video": 
[b"new"]}), columns=["video"])
+    assert table.raw_table.snapshot_manager().get_latest_snapshot() is None
+
+
+def test_update_columns_by_row_id_enforces_existing_nullability(tmp_path):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    table = connection.create_table(
+        "required", schema=pa.schema([pa.field("value", pa.int64(), 
nullable=False)]),
+        data=[{"value": 1}], options={"file.format": "parquet"})
+    snapshot = _snapshot(table)
+    with pytest.raises(ValueError, match="non-null column value"):
+        table.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "value": 
[None]}), columns=["value"])
+    assert _snapshot(table) == snapshot
+    assert table.scan().to_list() == [{"value": 1}]
+
+
+def test_update_columns_by_row_id_backfills_vectors_and_replaces_blobs(frames):
+    vector_type = pa.list_(pa.float32(), 2)
+    frames.add_columns(pa.schema([("embedding", vector_type)]))
+    blobs = _blobs(frames)
+    result = frames.update_columns_by_row_id(pa.table({
+        "_ROW_ID": [3, 1], "embedding": pa.array([[3., 4.], [1., 2.]], 
type=vector_type)}), columns=["embedding"])
+    assert result.added_columns == ()
+    assert result.updated_rows == 2
+    assert _blobs(frames) == blobs
+    frames.update_columns_by_row_id(pa.table({
+        "_ROW_ID": [1, 3], "image": pa.array([b"replacement", None], 
type=pa.large_binary())}), columns=["image"])
+    assert _rows(frames, ["id", "embedding"]) == [
+        {"id": i, "embedding": [float(i), float(i + 1)] if i in (1, 3) else 
None} for i in range(5)]
+    _, actual = frames.scan().select(["id", "image"]).read_blobs()
+    assert actual["image"] == [bytes([0]) * 100, b"replacement", bytes([2]) * 
100, None, bytes([4]) * 100]
+
+
[email protected]("invalid, deleted", [(99, False), (1, True), (3, 
True)])
+def test_update_columns_by_row_id_rejects_all_targets_before_writing(frames, 
invalid, deleted):
+    from pypaimon.write.table_update import BatchTableUpdate
+
+    if deleted:
+        frames.delete("id = %s" % invalid)
+        # Validate against a group that already has a partial-column version.
+        frames.merge_columns(pa.table({"id": [2], "label": ["prior"]}), 
on="id")
+    snapshot, files = _snapshot(frames), set(_files(frames))
+    before = _rows(frames, ["id", "label"])
+    with patch.object(BatchTableUpdate, "update_by_arrow_with_row_id",
+                      side_effect=AssertionError("must not write")):
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            frames.update_columns_by_row_id(
+                pa.table({"_ROW_ID": [0, invalid], "label": ["new", "bad"]}), 
columns=["label"])
+    assert failure.value.phase == "validate"
+    assert failure.value.schema_changed is False
+    assert failure.value.commit_outcome == "not_started"
+    assert isinstance(failure.value.__cause__, ValueError)
+    assert "not found or deleted: [%s]" % invalid in 
str(failure.value.__cause__)
+    assert _snapshot(frames) == snapshot
+    assert set(_files(frames)) == files
+    assert _rows(frames, ["id", "label"]) == before
+
+
[email protected]("empty_table", [False, True])
+def test_update_columns_by_row_id_empty_input_does_not_commit(frames, 
tmp_path, empty_table):
+    table = frames
+    if empty_table:
+        connection = pmm.connect(options={"warehouse": str(tmp_path / 
"empty-warehouse")})
+        table = connection.create_table("empty", schema=pa.schema([("label", 
pa.string())]))
+    snapshot = table.raw_table.snapshot_manager().get_latest_snapshot()
+    with patch.object(BatchTableCommit, "commit", 
side_effect=AssertionError("must not commit")):
+        result = table.update_columns_by_row_id(pa.table({
+            "_ROW_ID": pa.array([], type=pa.int64()), "label": pa.array([], 
type=pa.string())}), columns=["label"])
+    assert result.source_snapshot_id == (None if snapshot is None else 
snapshot.id)
+    assert result.snapshot_id == result.source_snapshot_id
+    assert result.updated_rows == 0
+    assert result.added_columns == ()
+
+
[email protected]("append_after_capture", [False, True])
+def 
test_update_columns_by_row_id_rejects_ids_in_an_empty_source_snapshot(tmp_path, 
append_after_capture):
+    from pypaimon.multimodal.columns import _ColumnUpdate
+
+    table = pmm.connect(options={"warehouse": str(tmp_path)}).create_table(
+        "empty", schema=pa.schema([("label", pa.string())]))
+    enter = _ColumnUpdate.__enter__
+
+    def maybe_append(operation):
+        if append_after_capture:
+            table.add([{"label": "appended"}])
+        return enter(operation)
+
+    with patch.object(_ColumnUpdate, "__enter__", maybe_append):
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            table.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "label": 
["new"]}), columns=["label"])
+    assert failure.value.source_snapshot_id is None
+    assert failure.value.phase == "validate"
+    assert "not found or deleted: [0]" in str(failure.value.__cause__)
+    assert table.scan().to_list() == ([{"label": "appended"}] if 
append_after_capture else [])
+
+
+def 
test_update_columns_by_row_id_pins_validation_and_writing_to_one_snapshot(frames):
+    from pypaimon.multimodal.columns import _ColumnUpdate
+    from pypaimon.write.table_update import BatchTableUpdate
+
+    snapshot = _snapshot(frames)
+    enter, update = _ColumnUpdate.__enter__, 
BatchTableUpdate.update_by_arrow_with_row_id
+    write_snapshots = []
+
+    def append_after_capture(operation):
+        frames.add([{"id": 5, "label": "appended", "image": b"new"}])
+        return enter(operation)
+
+    def capture_write(self, data):
+        write_snapshots.append(self.table._read_snapshot.id)
+        messages = update(self, data)
+        assert all(message.check_from_snapshot == snapshot for message in 
messages)
+        return messages
+
+    with patch.object(_ColumnUpdate, "__enter__", append_after_capture), 
patch.object(
+            BatchTableUpdate, "update_by_arrow_with_row_id", capture_write):
+        result = frames.update_columns_by_row_id(pa.table({"_ROW_ID": [0], 
"label": ["new"]}), columns=["label"])
+    assert result.source_snapshot_id == snapshot
+    assert write_snapshots == [snapshot]
+    assert _rows(frames, ["id", "label"])[-1] == {"id": 5, "label": "appended"}
+
+    with patch.object(_ColumnUpdate, "__enter__", append_after_capture):
+        with pytest.raises(pmm.ColumnUpdateError, match="validate"):
+            frames.update_columns_by_row_id(pa.table({"_ROW_ID": [6], "label": 
["not in snapshot"]}), columns=["label"])
+
+
[email protected]_write
+def test_update_columns_by_row_id_late_write_failure_does_not_publish(frames):
+    from pypaimon.execution.python.write.table_update_by_row_id import 
PythonTableUpdateByRowId
+
+    frames = frames.copy({"write.native.enabled": "false"})
+    frames.add([{"id": 5, "label": "old", "image": b"other"}])
+    snapshot = _snapshot(frames)
+    write_group = PythonTableUpdateByRowId._write_group
+    written = []
+
+    def fail_second(self, *args, **kwargs):
+        if written:
+            raise OSError("second group failed")
+        result = write_group(self, *args, **kwargs)
+        written.append(args[1])
+        return result
+
+    with patch.object(PythonTableUpdateByRowId, "_write_group", fail_second):
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            frames.update_columns_by_row_id(
+                pa.table({"_ROW_ID": [0, 5], "label": ["first", "second"]}), 
columns=["label"])
+    assert len(written) == 1
+    assert failure.value.phase == "write"
+    assert failure.value.commit_outcome == "not_started"
+    assert _snapshot(frames) == snapshot
+    assert all(row["label"] == "old" for row in _rows(frames, ["id", "label"]))
+    result = frames.update_columns_by_row_id(
+        pa.table({"_ROW_ID": [0, 5], "label": ["first", "second"]}), 
columns=["label"])
+    assert result.updated_rows == 2
+    assert _snapshot(frames) == snapshot + 1
+
+
[email protected]_plan
[email protected]("native_read", [False, True])
+def test_update_columns_by_row_id_uses_native_update(frames, native_read):
+    from pypaimon.execution.python.write.table_update import PythonTableUpdate
+
+    frames.delete("id = 4")
+    table = frames.copy({"write.native.enabled": "true", 
"read.native.enabled": str(native_read).lower()})
+    snapshot = _snapshot(table)
+    with patch.object(PythonTableUpdate, "update_by_arrow_with_row_id",
+                      side_effect=AssertionError("must not write invalid 
IDs")):
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            table.update_columns_by_row_id(
+                pa.table({"_ROW_ID": [0, 4], "label": ["new", "deleted"]}), 
columns=["label"])
+    assert failure.value.phase == "validate"
+    assert failure.value.commit_outcome == "not_started"
+    assert "not found or deleted: [4]" in str(failure.value.__cause__)
+    assert _snapshot(table) == snapshot
+    with patch.object(PythonTableUpdate, "update_by_arrow_with_row_id",
+                      side_effect=AssertionError("must use native update")):
+        result = table.update_columns_by_row_id(
+            pa.table({"_ROW_ID": [3, 1], "label": ["three", "one"]}), 
columns=["label"])
+    assert result.updated_rows == 2
+    assert _rows(table, ["id", "label"]) == [
+        {"id": i, "label": "one" if i == 1 else "three" if i == 3 else "old"} 
for i in range(4)]
+
+
+def test_update_columns_by_row_id_validation_read_failure_never_writes(frames):
+    from pypaimon.read.table_read import TableRead
+    from pypaimon.write.table_update import BatchTableUpdate
+
+    snapshot, files = _snapshot(frames), set(_files(frames))
+    read_error = OSError("validation read failed")
+    with patch.object(TableRead, "to_arrow", side_effect=read_error), 
patch.object(
+            BatchTableUpdate, "update_by_arrow_with_row_id", 
side_effect=AssertionError("must not write")):
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            frames.update_columns_by_row_id(pa.table({"_ROW_ID": [0], "label": 
["new"]}), columns=["label"])
+    assert failure.value.phase == "validate"
+    assert failure.value.commit_outcome == "not_started"
+    assert failure.value.__cause__ is read_error
+    assert _snapshot(frames) == snapshot
+    assert set(_files(frames)) == files
+
+
[email protected]("lose_response", [False, True])
+def 
test_update_columns_by_row_id_preserves_commit_state_when_close_fails(frames, 
lose_response):
+    snapshot = _snapshot(frames)
+    commit, close = BatchTableCommit.commit, BatchTableCommit.close
+    commit_error, close_error = OSError("lost commit response"), 
OSError("commit close failed")
+
+    def maybe_lose_response(self, messages, *args, **kwargs):
+        commit(self, messages, *args, **kwargs)
+        if lose_response:
+            raise commit_error
+
+    def failed_close(self):
+        close(self)
+        raise close_error
+
+    with patch.object(BatchTableCommit, "commit", maybe_lose_response), 
patch.object(
+            BatchTableCommit, "close", failed_close), patch.object(
+            BatchTableCommit, "abort", side_effect=AssertionError("must 
preserve committed files")):
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            frames.update_columns_by_row_id(
+                pa.table({"_ROW_ID": [3, 0], "label": ["three", "zero"]}), 
columns=["label"])
+    assert failure.value.phase == ("commit" if lose_response else "close")
+    assert failure.value.commit_outcome == ("unknown" if lose_response else 
"committed")
+    assert failure.value.__cause__ is (commit_error if lose_response else 
close_error)
+    assert _snapshot(frames) == snapshot + 1
+    assert _rows(frames, ["id", "label"]) == [
+        {"id": i, "label": "zero" if i == 0 else "three" if i == 3 else "old"} 
for i in range(5)]
+
+
+def 
test_update_columns_by_row_id_does_not_replay_failed_native_execution(frames):
+    from unittest.mock import Mock
+
+    backend = Mock()
+    backend.update_by_arrow_with_row_id.side_effect = OSError("native 
execution failed")
+    snapshot = _snapshot(frames)
+    with 
patch("pypaimon.write.update_dispatch.prepare_native_write_operation", 
return_value=backend) as prepare:
+        with 
patch("pypaimon.write.update_dispatch.create_python_update_operation",
+                   side_effect=AssertionError("must not replay after 
execution")):
+            with pytest.raises(pmm.ColumnUpdateError) as failure:
+                frames.update_columns_by_row_id(pa.table({"_ROW_ID": [1], 
"label": ["new"]}), columns=["label"])
+    prepare.assert_called_once()
+    assert prepare.call_args[0][0] == "update"
+    assert prepare.call_args[0][1]._read_snapshot.id == snapshot
+    backend.update_by_arrow_with_row_id.assert_called_once()
+    assert failure.value.phase == "write"
+    assert failure.value.commit_outcome == "not_started"
+    assert str(failure.value.__cause__) == "native execution failed"
+    assert _snapshot(frames) == snapshot
+    assert all(row["label"] == "old" for row in _rows(frames, ["id", "label"]))
diff --git a/paimon-python/pypaimon/tests/multimodal_table_test.py 
b/paimon-python/pypaimon/tests/multimodal_table_test.py
index ac996ecb95..6a520f7083 100644
--- a/paimon-python/pypaimon/tests/multimodal_table_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_table_test.py
@@ -3304,6 +3304,163 @@ class MultimodalTableTest(unittest.TestCase):
             rows,
         )
 
+    def test_update_by_row_id_preserves_duplicate_keys_and_media(self):
+        users = self.conn.create_table(
+            "users", schema=_schema({"id": pa.int32(), "label": pa.string(), 
"image": pa.large_binary()}),
+            data=[{"id": 7, "label": "first", "image": b"first"},
+                  {"id": 7, "label": "second", "image": b"second"}],
+            options=_PARQUET_OPTIONS)
+        row_ids = {row["label"]: row["_ROW_ID"]
+                   for row in 
users.scan().select(["label"]).with_row_id().to_list()}
+        files = {file.file_name for split in 
users.raw_table.new_read_builder().new_scan().plan_all().splits()
+                 for file in split.files}
+        with patch.object(users.raw_table.file_io, "read_ranges_coalesced",
+                          side_effect=AssertionError("must not fetch media")):
+            result = users.update(where="_ROW_ID = %s" % row_ids["second"], 
values={"label": "car"})
+        self.assertIs(users, result)
+        self.assertEqual(
+            {row_ids["first"]: "first", row_ids["second"]: "car"},
+            {row["_ROW_ID"]: row["label"]
+             for row in 
users.scan().select(["label"]).with_row_id().to_list()})
+        current_files = {file.file_name: file
+                         for split in 
users.raw_table.new_read_builder().new_scan().plan_all().splits()
+                         for file in split.files}
+        self.assertTrue(files.issubset(current_files))
+        self.assertTrue(all(file.write_cols == ["label"] for name, file in 
current_files.items() if name not in files))
+
+    def test_update_by_row_id_conditions_skip_missing_and_deleted_rows(self):
+        users = self.conn.create_table(
+            "users", schema=_schema({"part": pa.string(), "id": pa.int32(), 
"label": pa.string()}),
+            partitioned=["part"],
+            data=[{"part": "a" if i < 3 else "b", "id": i, "label": "old"} for 
i in [3, 4, 5, 0, 1, 2]],
+            options=_PARQUET_OPTIONS)
+        row_ids = {row["id"]: row["_ROW_ID"] for row in 
users.scan().select(["id"]).with_row_id().to_list()}
+        users.delete("id = 1")
+        users.update(
+            where="_ROW_ID IN (%s, %s, 999999) AND id = 0" % (row_ids[0], 
row_ids[1]),
+            values={"label": "selected"})
+        users.update(where="_ROW_ID = %s OR id = 2" % row_ids[5], 
values={"label": "either"})
+        users.update(
+            where="_ROW_ID >= %s AND _ROW_ID <= %s" % (row_ids[3], 
row_ids[3]), values={"label": None})
+        users.update(where="_ROW_ID BETWEEN %s AND %s" % (row_ids[4], 
row_ids[4]), values={"label": "range"})
+        expected = [
+            {"id": 0, "label": "selected"}, {"id": 2, "label": "either"},
+            {"id": 3, "label": None}, {"id": 4, "label": "range"}, {"id": 5, 
"label": "either"}]
+        self.assertEqual(expected, sorted(users.scan().select(["id", 
"label"]).to_list(), key=lambda row: row["id"]))
+        for row_id in (row_ids[1], 999999):
+            with self.subTest(row_id=row_id):
+                self.assertIs(users.update(where="_ROW_ID = %s" % row_id, 
values={"label": "absent"}), users)
+        self.assertEqual(expected, sorted(users.scan().select(["id", 
"label"]).to_list(), key=lambda row: row["id"]))
+        users.update(
+            where="_ROW_ID = %s OR _ROW_ID = %s AND id = 999" % (row_ids[0], 
row_ids[3]),
+            values={"label": "precedence"})
+        expected[0]["label"] = "precedence"
+        users.update(
+            where="(_ROW_ID = %s OR _ROW_ID = %s) AND id = 999" % (row_ids[0], 
row_ids[3]),
+            values={"label": "parenthesized"})
+        self.assertEqual(expected, sorted(users.scan().select(["id", 
"label"]).to_list(), key=lambda row: row["id"]))
+
+    def test_update_by_row_id_on_empty_and_fully_deleted_table(self):
+        users = self.conn.create_table(
+            "users", schema=_schema({"id": pa.int32(), "label": pa.string()}), 
options=_PARQUET_OPTIONS)
+        for deleted in (False, True):
+            with self.subTest(deleted=deleted):
+                if deleted:
+                    users.add([{"id": 7, "label": "old"}])
+                    users.delete("id = 7")
+                self.assertIs(users.update(where="_ROW_ID >= 0", 
values={"label": "new"}), users)
+                self.assertEqual([], users.scan().to_list())
+
+    def test_update_by_row_id_with_inverted_between(self):
+        users = self.conn.create_table(
+            "users", schema=_schema({"id": pa.int32(), "label": pa.string()}),
+            data=[{"id": i, "label": "old"} for i in range(3)], 
options=_PARQUET_OPTIONS)
+        row_ids = {row["id"]: row["_ROW_ID"] for row in 
users.scan().select(["id"]).with_row_id().to_list()}
+        lower, upper = max(row_ids.values()), min(row_ids.values())
+        users.update(
+            where="_ROW_ID BETWEEN %s AND %s OR _ROW_ID = %s" % (lower, upper, 
row_ids[1]),
+            values={"label": "new"})
+        expected = [{"id": i, "label": "new" if i == 1 else "old"} for i in 
range(3)]
+        self.assertEqual(expected, users.scan().to_list())
+        users.update(where="_ROW_ID BETWEEN %s AND %s" % (lower, upper), 
values={"label": "empty"})
+        self.assertEqual(expected, users.scan().to_list())
+
+    def test_update_row_id_predicates_keep_system_columns_read_only(self):
+        users = self.conn.create_table(
+            "users", schema=_schema({"id": pa.int32(), "label": pa.string()}),
+            data=[{"id": 7, "label": "old"}], options=_PARQUET_OPTIONS)
+        row_id = 
users.scan().select(["id"]).with_row_id().to_list()[0]["_ROW_ID"]
+        for field in ("_SEQUENCE_NUMBER", "_VALUE_KIND"):
+            with self.subTest(field=field), self.assertRaisesRegex(ValueError, 
"Unknown field"):
+                users.update(where="%s = 0" % field, values={"label": "new"})
+            with self.subTest(assignment=field), 
self.assertRaisesRegex(ValueError, "not in table schema"):
+                users.update(where="_ROW_ID = %s" % row_id, values={field: 0})
+        with self.assertRaisesRegex(ValueError, "not in table schema"):
+            users.update(where="_ROW_ID = %s" % row_id, values={"_ROW_ID": 
999})
+        with self.assertRaises(ValueError):
+            users.update(where="_ROW_ID = 'invalid'", values={"label": "new"})
+        self.assertEqual([{"id": 7, "label": "old"}], users.scan().to_list())
+        self.assertIs(users.update(where=None, values={"label": "all"}), users)
+        self.assertEqual([{"id": 7, "label": "all"}], users.scan().to_list())
+        with self.assertRaisesRegex(ValueError, "Unknown field '_ROW_ID'"):
+            users.copy({"row-tracking.enabled": "false"}).update(
+                where="_ROW_ID = %s" % row_id, values={"label": "new"})
+
+    @pytest.mark.native_plan
+    def test_update_by_row_id_uses_native_predicate_update(self):
+        from pypaimon.execution.python.write.table_update import 
PythonTableUpdate
+
+        users = self.conn.create_table(
+            "users", schema=_schema({"id": pa.int32(), "label": pa.string()}),
+            data=[{"id": 7, "label": "first"}, {"id": 7, "label": "second"}],
+            options=dict(_PARQUET_OPTIONS, **{"write.native.enabled": "true"}))
+        row_ids = {row["label"]: row["_ROW_ID"]
+                   for row in 
users.scan().select(["label"]).with_row_id().to_list()}
+        with patch.object(PythonTableUpdate, "_execute_predicate_update",
+                          side_effect=AssertionError("must use native 
predicate update")):
+            users.update(where="_ROW_ID = %s" % row_ids["second"], 
values={"label": "car"})
+        self.assertEqual(
+            {row_ids["first"]: "first", row_ids["second"]: "car"},
+            {row["_ROW_ID"]: row["label"]
+             for row in 
users.scan().select(["label"]).with_row_id().to_list()})
+
+    def 
test_update_by_row_id_keeps_the_existing_backend_fallback_boundary(self):
+        from unittest.mock import Mock
+
+        users = self.conn.create_table(
+            "users", schema=_schema({"id": pa.int32(), "label": pa.string()}),
+            data=[{"id": 7, "label": "first"}, {"id": 7, "label": "second"}], 
options=_PARQUET_OPTIONS)
+        row_ids = {row["label"]: row["_ROW_ID"]
+                   for row in 
users.scan().select(["label"]).with_row_id().to_list()}
+        users = users.copy({"write.native.enabled": "true"})
+        prepare = Mock(return_value=None)
+        with 
patch("pypaimon.write.update_dispatch.prepare_native_write_operation", 
prepare), patch(
+                
"pypaimon.write.backend_dispatch.prepare_native_write_operation", prepare):
+            users.update(where="_ROW_ID = %s" % row_ids["second"], 
values={"label": "fallback"})
+        prepare.assert_called_once()
+        self.assertEqual("predicate_update", prepare.call_args[0][0])
+        predicate = prepare.call_args[0][3]
+        self.assertEqual("_ROW_ID", predicate.field)
+        self.assertEqual([row_ids["second"]], predicate.literals)
+        expected = {row_ids["first"]: "first", row_ids["second"]: "fallback"}
+        self.assertEqual(expected, {row["_ROW_ID"]: row["label"]
+                                    for row in 
users.scan().select(["label"]).with_row_id().to_list()})
+
+        snapshot = users.raw_table.snapshot_manager().get_latest_snapshot().id
+        backend = Mock()
+        error = OSError("native execution failed")
+        backend.update.side_effect = error
+        with 
patch("pypaimon.write.update_dispatch.prepare_native_write_operation", 
return_value=backend), patch(
+                
"pypaimon.write.update_dispatch.create_python_update_operation",
+                side_effect=AssertionError("must not replay a failed Native 
update")):
+            with self.assertRaises(OSError) as failure:
+                users.update(where="_ROW_ID = %s" % row_ids["second"], 
values={"label": "bad"})
+        backend.update.assert_called_once()
+        self.assertIs(failure.exception, error)
+        self.assertEqual(snapshot, 
users.raw_table.snapshot_manager().get_latest_snapshot().id)
+        self.assertEqual(expected, {row["_ROW_ID"]: row["label"]
+                                    for row in 
users.scan().select(["label"]).with_row_id().to_list()})
+
     def test_delete_by_filter(self):
         users = self.conn.create_table(
             "users",
diff --git a/paimon-python/pypaimon/tests/range_test.py 
b/paimon-python/pypaimon/tests/range_test.py
index 3488d5911d..ee5815e862 100644
--- a/paimon-python/pypaimon/tests/range_test.py
+++ b/paimon-python/pypaimon/tests/range_test.py
@@ -49,6 +49,11 @@ class RangeTest(unittest.TestCase):
         result = _row_ranges_from_predicate(pred_between)
         assert result is not None and result == [Range(10, 20)]
 
+        inverted = Predicate('between', 0, SpecialFields.ROW_ID.name, [2, 0])
+        assert _row_ranges_from_predicate(inverted) == []
+        assert _row_ranges_from_predicate(Predicate('or', None, None, 
[inverted, pred_eq])) == [Range(5, 5)]
+        assert _row_ranges_from_predicate(Predicate('and', None, None, 
[inverted, pred_eq])) == []
+
         pred_other = Predicate('equal', 0, 'other_field', [5])
         assert _row_ranges_from_predicate(pred_other) is None
 

Reply via email to