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 bb14a9e848 [python] Add batch computation for existing multimodal 
columns (#11006)
bb14a9e848 is described below

commit bb14a9e848de8874ece7bc69447049efbb782858
Author: QuakeWang <[email protected]>
AuthorDate: Mon Nov 9 12:03:10 2026 +0800

    [python] Add batch computation for existing multimodal columns (#11006)
---
 docs/docs/pypaimon/multimodal-tables.mdx           |  34 +-
 paimon-python/README.md                            |  21 +-
 paimon-python/pypaimon/multimodal/columns.py       | 115 ++++---
 paimon-python/pypaimon/multimodal/table.py         |  18 +
 .../pypaimon/tests/multimodal_columns_test.py      | 369 ++++++++++++++++++++-
 5 files changed, 504 insertions(+), 53 deletions(-)

diff --git a/docs/docs/pypaimon/multimodal-tables.mdx 
b/docs/docs/pypaimon/multimodal-tables.mdx
index d295802987..a1744441d7 100644
--- a/docs/docs/pypaimon/multimodal-tables.mdx
+++ b/docs/docs/pypaimon/multimodal-tables.mdx
@@ -297,6 +297,10 @@ 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())]))
+
+# Recompute an existing column without changing its schema.
+result = frames.compute_columns(
+    ["image_size"], inputs=["image"], fn=image_sizes, batch_size=128)
 ```
 
 For embeddings, declare a fixed-size list such as
@@ -308,6 +312,17 @@ 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`.
 
+`compute_columns(columns, *, inputs, fn, batch_size=1024)` fills or replaces
+existing columns without changing the schema. `columns` is a name or a sequence
+of names; output types and nullability come from the table schema. The function
+follows the same batch contract as `add_columns`. Every call processes all
+visible rows in the captured source snapshot, including rows whose output 
values
+are already non-NULL. Inputs may also be outputs. Partition and system columns
+cannot be outputs; use `replace_video` for configured video-frame outputs.
+Use this method after a schema-only addition or to recompute a column left by
+failed `add_columns` computation. A new call starts a complete run, without
+resuming an earlier run or retrying function calls automatically.
+
 `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;
@@ -322,15 +337,16 @@ 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.
+`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.
 
-Both methods retain files for untouched columns. Computing an image embedding
+All three 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.
+physical writes. `add_columns` and `compute_columns` buffer outputs per 
original
+file group so a small function batch does not repeatedly rewrite the same 
group.
+`batch_size` bounds function input rows, not total memory usage.
 
 These are local, single-writer operations on a current full-table view.
 As with other table methods, reopen the table after external schema changes.
@@ -342,8 +358,10 @@ 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
+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
+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
 and commit raise
diff --git a/paimon-python/README.md b/paimon-python/README.md
index 3685996cf6..ffdec9cf9f 100644
--- a/paimon-python/README.md
+++ b/paimon-python/README.md
@@ -127,7 +127,7 @@ 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:
+Multimodal Data Evolution tables provide local column-enrichment methods:
 
 ```python
 # labels is a typed Arrow table containing sample_id and the columns to fill.
@@ -140,6 +140,10 @@ result = table.add_columns(
 
 # Without fn, only the schema is changed; existing rows read as NULL.
 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)
 ```
 
 `table` is a `pypaimon.multimodal.MultimodalTable`. `merge_columns` uses 
ordinary
@@ -152,17 +156,24 @@ 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
+`compute_columns` requires existing, non-partition output columns and never
+changes the schema. It uses the table's output types and nullability. Every 
call
+computes all visible rows, including rows with existing values. Use 
`replace_video`
+for video-frame outputs. Inputs may also be outputs; reads use the source 
snapshot.
+`add_columns` and `compute_columns` read only their 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.
+`add_columns` and `compute_columns` can use the native shard reader and writer;
+their `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`.
+`add_columns` (zero for schema-only additions) and `compute_columns`, and 
`None`
+for `merge_columns`. `compute_columns` always returns `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/multimodal/columns.py 
b/paimon-python/pypaimon/multimodal/columns.py
index 4e69310d11..1ae6412f86 100644
--- a/paimon-python/pypaimon/multimodal/columns.py
+++ b/paimon-python/pypaimon/multimodal/columns.py
@@ -27,6 +27,7 @@ from pypaimon.multimodal.table import (
     _cast_merge_on_columns, _normalize_merge_on, _target_schema,
     _to_arrow_table, _validate_merge_on,
 )
+from pypaimon.schema.arrow_schema import normalize_arrow_write_nullability
 from pypaimon.schema.data_types import PyarrowFieldParser
 from pypaimon.schema.schema_change import SchemaChange
 from pypaimon.snapshot.time_travel_util import SCAN_KEYS
@@ -39,8 +40,9 @@ 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 is ``None`` for
-    ``merge_columns``, whose MERGE executor does not return logical row counts.
+    ``updated_rows`` is available for ``add_columns`` and ``compute_columns``
+    and is ``None`` for ``merge_columns``, whose MERGE executor does not return
+    logical row counts.
     """
 
     source_snapshot_id: Optional[int]
@@ -161,6 +163,22 @@ def _canonical_field(field):
     return field.with_type(PyarrowFieldParser.from_paimon_type(data_type))
 
 
+def _validate_batch_size(batch_size):
+    if isinstance(batch_size, bool) or not isinstance(batch_size, int) or 
batch_size <= 0:
+        raise ValueError("batch_size must be a positive integer.")
+
+
+def _validate_inputs(raw, inputs, fn):
+    if not callable(fn) or inputs is None:
+        raise ValueError("A callable fn and explicit inputs are required for 
column computation.")
+    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))
+    return inputs
+
+
 def _normalize_output(data, schema):
     if not isinstance(data, (pa.Table, pa.RecordBatch)):
         raise ValueError("Column function must return a pyarrow.Table or 
RecordBatch.")
@@ -172,12 +190,18 @@ def _normalize_output(data, 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:
+            # Same-type casts can reject child NULLs hidden by a NULL parent.
+            if array.type != source_type:
+                array = array.cast(source_type)
+            # Read schemas relax nested nullability; restore it before 
comparing types.
+            source = pa.Table.from_arrays([array], names=[field.name])
+            array = normalize_arrow_write_nullability(source, 
pa.schema([field]))[field.name]
+            if array.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))
+        arrays.append(array if array.type == field.type else 
array.cast(field.type))
     return pa.Table.from_arrays(arrays, schema=schema)
 
 
@@ -220,8 +244,7 @@ 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.")
+    _validate_batch_size(batch_size)
     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]
@@ -234,38 +257,56 @@ def add_columns(owner, schema, *, inputs, fn, batch_size):
         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))
+        inputs = _validate_inputs(raw, inputs, fn)
     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)
+        return _compute_columns(operation, pa.schema(fields), inputs, fn, 
batch_size)
+
+
+def compute_columns(owner, columns, *, inputs, fn, batch_size):
+    columns = [columns] if isinstance(columns, str) else list(columns)
+    _validate_names(columns, "Output")
+    _validate_batch_size(batch_size)
+    raw = owner.raw_table
+    _validate_update(raw)
+    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("compute_columns cannot update partition columns.")
+    if set(columns).intersection(raw.options.video_frame_fields()):
+        raise ValueError("Use replace_video() to update video-frame columns.")
+    inputs = _validate_inputs(raw, inputs, fn)
+    target_schema = _target_schema(raw)
+    schema = pa.schema([target_schema.field(name) for name in columns])
+    with _ColumnUpdate(owner, raw) as operation:
+        return _compute_columns(operation, schema, inputs, fn, batch_size)
+
+
+def _compute_columns(operation, schema, inputs, fn, batch_size):
+    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), schema)
+            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 c5fe9ed2f1..58a97417dd 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -539,6 +539,24 @@ class MultimodalTable:
         from pypaimon.multimodal.columns import add_columns
         return add_columns(self, schema, inputs=inputs, fn=fn, 
batch_size=batch_size)
 
+    def compute_columns(self, columns, *, inputs, fn, batch_size=1024):
+        """Compute existing columns for all visible rows without changing the 
schema.
+
+        ``columns`` is a column name or a sequence of names. Outputs must be
+        existing, non-partition columns; use ``replace_video`` for video-frame
+        outputs. Types and nullability are taken from the table schema.
+        ``fn`` follows the same input and output contract as ``add_columns``.
+        Inputs may also be outputs; all reads use the captured source snapshot.
+
+        Execution is local and requires a current full-table view and a single
+        writer. Every call recomputes all visible rows, including non-NULL
+        outputs. Untouched columns retain their files. There are no automatic
+        retries or checkpoints. Returns 
:class:`pypaimon.multimodal.ColumnUpdateResult`
+        with ``added_columns=()`` and the computed row count in 
``updated_rows``.
+        """
+        from pypaimon.multimodal.columns import compute_columns
+        return compute_columns(self, columns, 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/tests/multimodal_columns_test.py 
b/paimon-python/pypaimon/tests/multimodal_columns_test.py
index 8c9e93dc93..bfd353b278 100644
--- a/paimon-python/pypaimon/tests/multimodal_columns_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_columns_test.py
@@ -226,7 +226,328 @@ def 
test_add_columns_rejects_existing_columns_before_calling_user_code(frames):
         frames.add_columns(pa.schema([("label", pa.string())]), 
inputs=["image"], fn=compute)
 
 
-def test_merge_columns_preserves_files_if_commit_response_is_lost(frames):
+def 
test_compute_columns_backfills_and_recomputes_without_schema_or_media_changes(frames):
+    vector_type = pa.list_(pa.float32(), 2)
+    frames.add_columns(pa.schema([("embedding", vector_type)]))
+    raw = frames.raw_table
+    schema_id = raw.table_schema.id
+    blobs = _blobs(frames)
+    original_files = set(_files(frames))
+
+    for offset in (0, 10):
+        snapshot = _snapshot(frames)
+        files = set(_files(frames))
+        batches = []
+
+        def embed(batch):
+            assert batch.schema.names == ["image"]
+            images = batch["image"].to_pylist()
+            assert all(isinstance(image, bytes) for image in images)
+            batches.append(batch.num_rows)
+            return pa.table({"embedding": pa.array(
+                [[float(image[0] + offset), float(len(image))] for image in 
images],
+                type=vector_type)})
+
+        with patch.object(frames.catalog, "alter_table", 
side_effect=AssertionError("must not alter schema")):
+            result = frames.compute_columns("embedding", inputs="image", 
fn=embed, batch_size=2)
+
+        assert sum(batches) == 5
+        assert max(batches) <= 2
+        assert result.source_snapshot_id == snapshot
+        assert result.snapshot_id > snapshot
+        assert result.schema_id == schema_id
+        assert result.updated_rows == 5
+        assert result.added_columns == ()
+        assert frames.raw_table is raw
+        assert frames.catalog.get_table(frames.identifier).table_schema.id == 
schema_id
+        assert _rows(frames, ["id", "label", "embedding"]) == [
+            {"id": i, "label": "old", "embedding": [float(i + offset), 100.0]} 
for i in range(5)]
+        assert _blobs(frames) == blobs
+        assert original_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_compute_columns_can_backfill_after_failed_add(frames):
+    with pytest.raises(pmm.ColumnUpdateError):
+        frames.add_columns(pa.schema([("feature", pa.int64())]), inputs=["id"],
+                           fn=lambda batch: pa.table({"feature": ["invalid"] * 
batch.num_rows}))
+    schema_id = frames.raw_table.table_schema.id
+    result = frames.compute_columns(
+        ["feature"], inputs=["id"],
+        fn=lambda batch: pa.table({"feature": batch["id"]}))
+
+    assert result.schema_id == schema_id
+    assert result.added_columns == ()
+    assert result.updated_rows == 5
+    assert _rows(frames, ["id", "feature"]) == [{"id": i, "feature": i} for i 
in range(5)]
+
+
+def 
test_compute_columns_reads_output_columns_and_accepts_reordered_record_batches(frames):
+    def compute(batch):
+        assert batch.schema.names == ["id", "label"]
+        return pa.RecordBatch.from_pydict({
+            "label": [label + "!" for label in batch["label"].to_pylist()],
+            "id": [value + 10 for value in batch["id"].to_pylist()],
+        })
+
+    with patch.object(frames.raw_table.file_io, "read_ranges_coalesced",
+                      side_effect=AssertionError("must not fetch media")):
+        for _ in range(2):
+            result = frames.compute_columns(["id", "label"], inputs=["id", 
"label"],
+                                            fn=compute, batch_size=2)
+
+    assert result.updated_rows == 5
+    assert _rows(frames, ["id", "label"]) == [{"id": i + 20, "label": "old!!"} 
for i in range(5)]
+
+
+def test_compute_columns_preserves_deleted_rows_across_partitions(tmp_path):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    table = connection.create_table(
+        "partitioned", schema=pa.schema([("id", pa.int64()), ("part", 
pa.string()), ("value", pa.int64())]),
+        partitioned=["part"], options={"file.format": "parquet", 
"deletion-vectors.enabled": "true"},
+        data=[{"id": i, "part": "a" if i < 3 else "b", "value": -1} for i in 
range(6)])
+    table.delete("id = 1")
+    result = table.compute_columns(
+        ["value"], inputs=["id"], batch_size=1,
+        fn=lambda batch: pa.table({"value": [i * 2 for i in 
batch["id"].to_pylist()]}))
+
+    assert result.updated_rows == 5
+    assert _rows(table, ["id", "part", "value"]) == [
+        {"id": i, "part": "a" if i < 3 else "b", "value": i * 2} for i in (0, 
2, 3, 4, 5)]
+    with pytest.raises(ValueError, match="partition"):
+        table.compute_columns(["part"], inputs=["id"], fn=lambda batch: batch)
+
+
[email protected]("output", [
+    lambda batch: ["new"] * batch.num_rows,
+    lambda batch: pa.table({"label": ["new"]}),
+    lambda batch: pa.table({"wrong": ["new"] * batch.num_rows}),
+    lambda batch: pa.table({"label": [123] * batch.num_rows}),
+    lambda batch: pa.Table.from_arrays([batch["id"], batch["id"]], 
names=["label", "label"]),
+])
+def test_compute_columns_rejects_bad_outputs_without_publishing(frames, 
output):
+    snapshot = _snapshot(frames)
+    schema_id = frames.raw_table.table_schema.id
+    files = set(_files(frames))
+    with pytest.raises(pmm.ColumnUpdateError) as failure:
+        frames.compute_columns(["label"], inputs=["id"], fn=output, 
batch_size=2)
+
+    assert failure.value.phase == "compute"
+    assert failure.value.schema_changed is False
+    assert failure.value.schema_id == schema_id
+    assert failure.value.source_snapshot_id == snapshot
+    assert failure.value.commit_outcome == "not_started"
+    assert isinstance(failure.value.__cause__, ValueError)
+    assert _snapshot(frames) == snapshot
+    assert set(_files(frames)) == files
+    assert _rows(frames, ["id", "label"]) == [{"id": i, "label": "old"} for i 
in range(5)]
+
+
+def test_compute_columns_late_failure_can_be_fully_rerun(frames):
+    frames.add([{"id": i, "label": "old", "image": b"other"} for i in range(5, 
9)])
+    snapshot = _snapshot(frames)
+    files = set(_files(frames))
+    calls = []
+
+    def compute(batch):
+        calls.append(batch.num_rows)
+        if len(calls) == 5:
+            raise RuntimeError("model failed after staging a file group")
+        return pa.table({"label": [str(i) for i in batch["id"].to_pylist()]})
+
+    with pytest.raises(pmm.ColumnUpdateError) as failure:
+        frames.compute_columns(["label"], inputs=["id"], fn=compute, 
batch_size=2)
+
+    assert len(calls) == 5
+    assert failure.value.schema_changed is False
+    assert failure.value.commit_outcome == "not_started"
+    assert isinstance(failure.value.__cause__, RuntimeError)
+    assert _snapshot(frames) == snapshot
+    assert set(_files(frames)) == files
+    assert _rows(frames, ["id", "label"]) == [{"id": i, "label": "old"} for i 
in range(9)]
+
+    result = frames.compute_columns(["label"], inputs=["id"], fn=compute, 
batch_size=2)
+    assert result.updated_rows == 9
+    assert sum(calls[5:]) == 9
+    assert _rows(frames, ["id", "label"]) == [{"id": i, "label": str(i)} for i 
in range(9)]
+
+
[email protected]("nullable", [False, True])
+def test_compute_columns_uses_existing_nullability(tmp_path, nullable):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    table = connection.create_table(
+        "values", schema=pa.schema([("id", pa.int64()), pa.field("value", 
pa.int64(), nullable=nullable)]),
+        data=[{"id": 0, "value": 1}], options={"file.format": "parquet"})
+    table.compute_columns(["value"], inputs=["id"], fn=lambda batch: 
pa.table({"value": [2]}))
+    snapshot = _snapshot(table)
+
+    def clear(batch):
+        return pa.table({"value": [None] * batch.num_rows})
+
+    if nullable:
+        table.compute_columns(["value"], inputs=["id"], fn=clear)
+        assert _rows(table, ["id", "value"]) == [{"id": 0, "value": None}]
+    else:
+        with pytest.raises(pmm.ColumnUpdateError) as failure:
+            table.compute_columns(["value"], inputs=["id"], fn=clear)
+        assert "non-null column value" in str(failure.value.__cause__)
+        assert _snapshot(table) == snapshot
+        assert _rows(table, ["id", "value"]) == [{"id": 0, "value": 2}]
+
+
[email protected]("data_type, value, invalid", [
+    (pa.struct([pa.field("x", pa.int64(), nullable=False)]), {"x": 2}, {"x": 
None}),
+    (pa.list_(pa.field("element", pa.int64(), nullable=False)), [2], [None]),
+])
[email protected]("as_table", [False, True])
+def test_compute_columns_restores_nested_nullability(tmp_path, data_type, 
value, invalid, as_table):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    schema = pa.schema([("id", pa.int64()), ("value", data_type)])
+    table = connection.create_table(
+        "nested", schema=schema,
+        data=pa.table({"id": [0, 1], "value": [value, None]}, schema=schema),
+        options={"file.format": "parquet"})
+    schema_id = table.raw_table.table_schema.id
+
+    def identity(batch):
+        field = batch.schema.field("value")
+        child = field.type[0] if pa.types.is_struct(field.type) else 
field.type.value_field
+        assert child.nullable
+        return pa.Table.from_batches([batch]) if as_table else batch
+
+    result = table.compute_columns(["value"], inputs=["value"], fn=identity)
+    assert result.updated_rows == 2
+    assert result.added_columns == ()
+    assert result.schema_id == schema_id
+    assert _rows(table, ["id", "value"]) == [{"id": 0, "value": value}, {"id": 
1, "value": None}]
+    snapshot = _snapshot(table)
+
+    def invalid_children(batch):
+        array = pa.array([invalid] * batch.num_rows, 
type=batch.schema.field("value").type)
+        factory = pa.Table if as_table else pa.RecordBatch
+        return factory.from_arrays([array], names=["value"])
+
+    with pytest.raises(pmm.ColumnUpdateError) as failure:
+        table.compute_columns(["value"], inputs=["value"], fn=invalid_children)
+    assert failure.value.phase == "compute"
+    assert failure.value.schema_changed is False
+    assert failure.value.commit_outcome == "not_started"
+    assert "non-nullable field value." in str(failure.value.__cause__)
+    assert _snapshot(table) == snapshot
+    assert _rows(table, ["id", "value"]) == [{"id": 0, "value": value}, {"id": 
1, "value": None}]
+
+
[email protected]("as_table", [False, True])
[email protected]("canonical", [False, True])
+def test_compute_columns_preserves_hidden_null_children(tmp_path, as_table, 
canonical):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    data_type = pa.struct([pa.field("x", pa.int64(), nullable=False)])
+    schema = pa.schema([("id", pa.int64()), ("value", data_type)])
+    table = connection.create_table(
+        "nested", schema=schema,
+        data=pa.table({"id": [0, 1], "value": [{"x": 2}, None]}, 
schema=schema),
+        options={"file.format": "parquet"})
+    snapshot = _snapshot(table)
+
+    def compute(batch):
+        ids = batch["id"].to_pylist()
+        array = pa.StructArray.from_arrays(
+            [pa.array([2 if value == 0 else None for value in ids], 
type=pa.int64())],
+            fields=[pa.field("x", pa.int64(), nullable=not canonical)],
+            mask=pa.array([value != 0 for value in ids]))
+        array.validate(full=True)
+        factory = pa.Table if as_table else pa.RecordBatch
+        return factory.from_arrays([array], names=["value"])
+
+    result = table.compute_columns(["value"], inputs=["id"], fn=compute)
+    assert result.source_snapshot_id == snapshot
+    assert result.snapshot_id > snapshot
+    assert result.updated_rows == 2
+    assert result.added_columns == ()
+    assert _rows(table, ["id", "value"]) == [{"id": 0, "value": {"x": 2}}, 
{"id": 1, "value": None}]
+
+
+def 
test_compute_columns_normalizes_reordered_outputs_with_null_siblings(tmp_path):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    data_type = pa.struct([pa.field("x", pa.int64(), nullable=False)])
+    schema = pa.schema([("id", pa.int64()), ("value", data_type), ("label", 
pa.string())])
+    table = connection.create_table(
+        "nested", schema=schema,
+        data=pa.table({"id": [0], "value": [{"x": 2}], "label": ["old"]}, 
schema=schema),
+        options={"file.format": "parquet"})
+
+    def compute(batch):
+        return pa.table({"value": batch["value"], "label": 
pa.nulls(batch.num_rows)})
+
+    result = table.compute_columns(["label", "value"], inputs=["value"], 
fn=compute)
+    assert result.updated_rows == 1
+    assert _rows(table, ["id", "value", "label"]) == [{"id": 0, "value": {"x": 
2}, "label": None}]
+
+
[email protected]("method", ["add_columns", "merge_columns"])
+def test_column_enrichment_restores_nested_nullability(tmp_path, method):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    data_type = pa.struct([pa.field("x", pa.int64(), nullable=False)])
+    schema = pa.schema([("id", pa.int64()), ("value", data_type)])
+    table = connection.create_table(
+        "nested", schema=schema, data=pa.table({"id": [0], "value": [{"x": 
2}]}, schema=schema),
+        options={"file.format": "parquet"})
+
+    if method == "add_columns":
+        table.add_columns(pa.schema([("derived", data_type)]), 
inputs=["value"],
+                          fn=lambda batch: pa.table({"derived": 
batch["value"]}))
+        assert _rows(table, ["id", "derived"]) == [{"id": 0, "derived": {"x": 
2}}]
+    else:
+        table.merge_columns(table.scan().select(["id", "value"]).to_arrow(), 
on="id")
+        assert _rows(table, ["id", "value"]) == [{"id": 0, "value": {"x": 2}}]
+
+
[email protected]("kwargs, message", [
+    ({"columns": []}, "unique column names"),
+    ({"columns": ["label", "label"]}, "unique column names"),
+    ({"columns": [""]}, "unique column names"),
+    ({"columns": ["absent"]}, "Output columns do not exist"),
+    ({"columns": ["_ROW_ID"]}, "system columns"),
+    ({"inputs": []}, "unique column names"),
+    ({"inputs": ["id", "id"]}, "unique column names"),
+    ({"inputs": ["absent"]}, "Input columns do not exist"),
+    ({"inputs": ["_ROW_ID"]}, "system columns"),
+    ({"inputs": None}, "explicit inputs"),
+    ({"fn": None}, "callable fn"),
+    ({"fn": 1}, "callable fn"),
+    ({"batch_size": 0}, "positive integer"),
+    ({"batch_size": -1}, "positive integer"),
+    ({"batch_size": True}, "positive integer"),
+    ({"batch_size": 1.5}, "positive integer"),
+])
+def test_compute_columns_validates_before_execution(frames, kwargs, message):
+    def never_called(batch):
+        raise AssertionError("must not run")
+
+    arguments = {"columns": ["label"], "inputs": ["id"], "fn": never_called}
+    arguments.update(kwargs)
+    schema_id = frames.raw_table.table_schema.id
+    snapshot = _snapshot(frames)
+    with patch.object(frames.catalog, "alter_table", 
side_effect=AssertionError("must not alter schema")):
+        with pytest.raises(ValueError, match=message):
+            frames.compute_columns(**arguments)
+    assert frames.catalog.get_table(frames.identifier).table_schema.id == 
schema_id
+    assert _snapshot(frames) == snapshot
+
+
+def test_compute_columns_rejects_video_frame_outputs(tmp_path):
+    connection = pmm.connect(options={"warehouse": str(tmp_path / 
"warehouse")})
+    table = connection.create_table(
+        "videos", schema=pa.schema([("id", pa.int64()), ("video", 
pa.large_binary())]),
+        options={"file.format": "parquet", "video-frame-field": "video"})
+    with pytest.raises(ValueError, match="replace_video"):
+        table.compute_columns(["video"], inputs=["id"], fn=lambda batch: batch)
+
+
[email protected]("method", ["merge_columns", "compute_columns"])
+def test_column_updates_preserve_files_if_commit_response_is_lost(frames, 
method):
     commit = BatchTableCommit.commit
 
     def lost_response(self, messages, *args, **kwargs):
@@ -236,7 +557,11 @@ def 
test_merge_columns_preserves_files_if_commit_response_is_lost(frames):
     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")
+            if method == "merge_columns":
+                frames.merge_columns(pa.table({"id": [0], "label": 
["committed"]}), on="id")
+            else:
+                frames.compute_columns(["label"], inputs=["id"], fn=lambda 
batch: pa.table({
+                    "label": ["committed"] * batch.num_rows}))
 
     assert failure.value.phase == "commit"
     assert failure.value.commit_outcome == "unknown"
@@ -244,6 +569,20 @@ def 
test_merge_columns_preserves_files_if_commit_response_is_lost(frames):
     assert _rows(frames, ["id", "label"])[0]["label"] == "committed"
 
 
+def test_compute_columns_on_fully_deleted_table_does_not_commit(frames):
+    frames.delete("id >= 0")
+    snapshot = _snapshot(frames)
+
+    def never_called(batch):
+        raise AssertionError("deleted rows must not be computed")
+
+    result = frames.compute_columns(["label"], inputs=["id"], fn=never_called)
+    assert result.source_snapshot_id == snapshot
+    assert result.snapshot_id == snapshot
+    assert result.updated_rows == 0
+    assert result.added_columns == ()
+
+
 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({
@@ -284,6 +623,11 @@ def test_column_enrichment_on_an_empty_table(tmp_path):
                                  on="id")
     assert result.updated_rows is None
     assert result.snapshot_id is None
+    result = table.compute_columns(["feature"], inputs=["id"], fn=never_called)
+    assert result.source_snapshot_id is None
+    assert result.snapshot_id is None
+    assert result.updated_rows == 0
+    assert result.added_columns == ()
 
 
 @pytest.mark.parametrize("schema, kwargs", [
@@ -306,6 +650,18 @@ def test_enrichment_rejects_historical_views(frames):
         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")
+    with pytest.raises(ValueError, match="current full-table"):
+        historical.compute_columns(["label"], inputs=["label"], fn=lambda 
batch: batch)
+
+
[email protected]("options", [
+    {"scan.mode": "from-snapshot"},
+    {"incremental-between": "1,2"},
+    {"scan.file-creation-time-millis": "1"},
+])
+def test_compute_columns_rejects_non_full_table_views(frames, options):
+    with pytest.raises(ValueError, match="current full-table"):
+        frames.copy(options).compute_columns(["label"], inputs=["label"], 
fn=lambda batch: batch)
 
 
 def test_add_columns_keeps_published_schema_if_schema_response_is_lost(frames):
@@ -409,8 +765,15 @@ def 
test_column_enrichment_uses_native_merge_and_shard_without_rewriting_media(f
             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)]
+        result = table.compute_columns(
+            ["image_size"], inputs=["image"],
+            fn=lambda batch: pa.table({"image_size": [len(value) + 1 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 result.added_columns == ()
+    assert _rows(table, ["id", "image_size"]) == [{"id": i, "image_size": 101} 
for i in range(5)]
     assert _blobs(table) == blobs
     assert table.scan(snapshot_id=snapshot).select(["id", 
"label"]).to_arrow().num_rows == 5
 

Reply via email to