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 9701dc299c [python] Support Ray execution for multimodal
compute_columns (#11090)
9701dc299c is described below
commit 9701dc299cd5d99d69a1c4e7a57636b0a2ffa07f
Author: QuakeWang <[email protected]>
AuthorDate: Wed Nov 11 16:25:27 2026 +0800
[python] Support Ray execution for multimodal compute_columns (#11090)
---
docs/docs/pypaimon/multimodal-tables.mdx | 32 +-
.../execution/python/write/table_update.py | 14 +-
paimon-python/pypaimon/multimodal/columns.py | 51 ++-
paimon-python/pypaimon/multimodal/table.py | 19 +-
paimon-python/pypaimon/ray/compute_columns.py | 112 ++++++
.../pypaimon/tests/ray_compute_columns_test.py | 393 +++++++++++++++++++++
paimon-python/pypaimon/write/backend_dispatch.py | 4 +-
7 files changed, 593 insertions(+), 32 deletions(-)
diff --git a/docs/docs/pypaimon/multimodal-tables.mdx
b/docs/docs/pypaimon/multimodal-tables.mdx
index 943121ff28..e1640a8f4e 100644
--- a/docs/docs/pypaimon/multimodal-tables.mdx
+++ b/docs/docs/pypaimon/multimodal-tables.mdx
@@ -348,6 +348,26 @@ 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.
+To recompute an existing column on Ray, install `pypaimon[ray]` and set
+`execution="ray"`. The driver plans one source snapshot and assigns complete
+Data Evolution file groups to workers. Each worker reads the requested inputs
+and uses the Python shard updater to prepare the output files. The driver
+publishes them in one commit after all shards succeed. A worker failure leaves
+the prepared files unpublished.
+
+```python
+result = frames.compute_columns(
+ "image_size", inputs=["image"], fn=image_sizes, batch_size=128,
+ execution="ray", concurrency=4, ray_remote_args={"num_cpus": 1},
+)
+```
+
+`concurrency` caps the number of shards and defaults to four. Parallelism also
+depends on the number of complete file groups and available Ray resources.
+`ray_remote_args` accepts task resource options such as `num_gpus`. The
function
+must be serializable by Ray, and workers need its dependencies and access to
+the table storage. Ray task retries are disabled for this write operation.
+
`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;
@@ -386,7 +406,7 @@ 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
+`add_columns` and local `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
@@ -400,13 +420,13 @@ 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.
+These are single-writer operations on a current full-table view.
As with other table methods, reopen the table after external schema changes.
Time-travel and incremental table views are rejected. `merge_columns`
materializes
the source as an Arrow table; target matching is handled by the selected MERGE
executor. The read snapshot is fixed for the
operation. Coordinate writers for the entire call.
-The APIs do not provide automatic retries, checkpoints, or distributed jobs.
+The APIs do not provide automatic function retries or checkpoints.
Successful calls return `ColumnUpdateResult` with added column names,
the source and final data snapshot IDs, and the schema ID. `updated_rows` is
the
@@ -417,8 +437,10 @@ logical row counts. `update_columns_by_row_id` reports the
input row count in
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
-`ColumnUpdateError`, retaining the original exception as `__cause__` and
exposing:
+and commit raise `ColumnUpdateError` with the underlying error as `__cause__`.
+For Ray worker failures, the original exception type is preserved only if Ray
+can serialize and deserialize the exception. If Ray cannot restore it, the
+cause can be a Ray error containing the worker traceback.
| Attribute | Meaning |
| --- | --- |
diff --git a/paimon-python/pypaimon/execution/python/write/table_update.py
b/paimon-python/pypaimon/execution/python/write/table_update.py
index ad354a3bb5..63b3fd5069 100644
--- a/paimon-python/pypaimon/execution/python/write/table_update.py
+++ b/paimon-python/pypaimon/execution/python/write/table_update.py
@@ -528,6 +528,8 @@ class ShardTableUpdator:
commit_user,
shard_num: int,
total_shard_count: int,
+ *,
+ splits: Optional[List[DataSplit]] = None,
):
from pypaimon.table.file_store_table import FileStoreTable
snapshot = TimeTravelUtil.resolve_snapshot(table)
@@ -539,11 +541,13 @@ class ShardTableUpdator:
self.commit_user = commit_user
self.total_shard_count = total_shard_count
self.shard_num = shard_num
- scanner = self.table.new_read_builder().new_scan()
- plan = scanner.plan_all()
- self.snapshot_id = plan.snapshot_id if plan.snapshot_id is not None
else -1
- splits = plan.splits()
- splits = _filter_by_whole_file_shard(splits, shard_num,
total_shard_count)
+ if splits is None:
+ plan = self.table.new_read_builder().new_scan().plan_all()
+ self.snapshot_id = plan.snapshot_id if plan.snapshot_id is not
None else -1
+ splits = _filter_by_whole_file_shard(plan.splits(), shard_num,
total_shard_count)
+ else:
+ # The driver already assigned complete groups from this snapshot.
+ self.snapshot_id = snapshot.id
self.splits = splits
self._files_info = RowIdFileIndex.from_splits(self.snapshot_id, splits)
self._write_schema = PyarrowFieldParser.from_paimon_schema(
diff --git a/paimon-python/pypaimon/multimodal/columns.py
b/paimon-python/pypaimon/multimodal/columns.py
index 7141461e19..5b419d85ec 100644
--- a/paimon-python/pypaimon/multimodal/columns.py
+++ b/paimon-python/pypaimon/multimodal/columns.py
@@ -62,7 +62,8 @@ class ColumnUpdateError(RuntimeError):
``schema_changed=None`` means the schema request had an unknown outcome.
``commit_outcome`` is ``not_started``, ``unknown``, or ``committed``. Never
retry blindly after an unknown outcome; inspect the table first. The
- original failure is retained as ``__cause__``.
+ underlying error is retained as ``__cause__``. Ray preserves a worker
+ exception's type only if it can serialize and deserialize the exception.
"""
def __init__(self, operation):
@@ -319,7 +320,12 @@ def add_columns(owner, schema, *, inputs, fn, batch_size):
return _compute_columns(operation, pa.schema(fields), inputs, fn,
batch_size)
-def compute_columns(owner, columns, *, inputs, fn, batch_size):
+def compute_columns(owner, columns, *, inputs, fn, batch_size,
+ execution="local", concurrency=None, ray_remote_args=None):
+ if execution not in ("local", "ray"):
+ raise ValueError("execution must be 'local' or 'ray'.")
+ if execution == "local" and (concurrency is not None or ray_remote_args is
not None):
+ raise ValueError("Ray options require execution='ray'.")
columns = [columns] if isinstance(columns, str) else list(columns)
_validate_names(columns, "Output")
_validate_batch_size(batch_size)
@@ -335,32 +341,49 @@ def compute_columns(owner, columns, *, inputs, fn,
batch_size):
inputs = _validate_inputs(raw, inputs, fn)
target_schema = _target_schema(raw)
schema = pa.schema([target_schema.field(name) for name in columns])
+ if execution == "ray":
+ from pypaimon.ray.compute_columns import validate_ray_options
+ concurrency, ray_remote_args = validate_ray_options(concurrency,
ray_remote_args)
with _ColumnUpdate(owner, raw) as operation:
- return _compute_columns(operation, schema, inputs, fn, batch_size)
+ return _compute_columns(operation, schema, inputs, fn, batch_size,
execution=execution,
+ concurrency=concurrency,
ray_remote_args=ray_remote_args)
-def _compute_columns(operation, schema, inputs, fn, batch_size):
+def _compute_columns(operation, schema, inputs, fn, batch_size, *,
+ execution="local", concurrency=None,
ray_remote_args=None):
operation.phase = "compute"
- table = operation.raw.copy_without_time_travel({
+ options = {
"blob-as-descriptor": "false", "read.batch-size": str(batch_size),
- })._copy_with_snapshot(operation.snapshot)
+ }
+ if execution == "ray":
+ options[CoreOptions.SCALAR_INDEX_SEARCH_MODE.key()] = "full"
+ table =
operation.raw.copy_without_time_travel(options)._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))
+ if execution == "local":
+ update = builder.new_update().with_update_type(schema.names)
+ update.with_read_projection(inputs)
+ shard = operation.keep(update.new_shard_updator(0, 1))
+ messages, updated_rows = _prepare_column_shard(shard, schema, fn,
batch_size, operation)
+ else:
+ from pypaimon.ray.compute_columns import prepare_ray_column_update
+ messages, updated_rows = prepare_ray_column_update(
+ operation, table, builder.commit_user, inputs, schema, fn,
batch_size, concurrency, ray_remote_args)
+ return operation.finish(updated_rows, commit=commit, messages=messages)
+
+
+def _prepare_column_shard(shard, schema, fn, batch_size, progress):
updated_rows = 0
for batch in shard.arrow_reader():
for start in range(0, batch.num_rows, batch_size):
- operation.phase = "compute"
+ progress.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"
+ progress.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)
+ progress.phase = "write"
+ return shard.prepare_commit(), updated_rows
diff --git a/paimon-python/pypaimon/multimodal/table.py
b/paimon-python/pypaimon/multimodal/table.py
index 45206596d1..5686bdfcde 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -583,7 +583,8 @@ class MultimodalTable:
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):
+ def compute_columns(self, columns, *, inputs, fn, batch_size=1024,
execution="local",
+ concurrency=None, ray_remote_args=None):
"""Compute existing columns for all visible rows without changing the
schema.
``columns`` is a column name or a sequence of names. Outputs must be
@@ -592,14 +593,20 @@ class MultimodalTable:
``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`
+ Execution requires a current full-table view and a single writer.
+ With ``execution="ray"``, workers use the Python shard updater on
+ disjoint file groups, then the driver commits once after all succeed.
+ ``concurrency`` bounds the number of shards (default 4) and
+ ``ray_remote_args`` configures Ray task resources. Workers must be able
+ to serialize and run ``fn`` and access the table storage.
+ 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)
+ return compute_columns(self, columns, inputs=inputs, fn=fn,
batch_size=batch_size,
+ execution=execution, concurrency=concurrency,
ray_remote_args=ray_remote_args)
def map_with_blobs(self, dataset, columns, fn, **kwargs):
from pypaimon.ray import map_with_blobs
diff --git a/paimon-python/pypaimon/ray/compute_columns.py
b/paimon-python/pypaimon/ray/compute_columns.py
new file mode 100644
index 0000000000..b6f5c62a5e
--- /dev/null
+++ b/paimon-python/pypaimon/ray/compute_columns.py
@@ -0,0 +1,112 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from types import SimpleNamespace
+
+from pypaimon.execution.python.read.scan_distribution import shard_range
+from pypaimon.multimodal.columns import _prepare_column_shard
+from pypaimon.read.read_support import close_read_source
+from pypaimon.write.backend_dispatch import create_python_shard_updator
+from pypaimon.write.row_id_plan import capture_row_id_plan
+from pypaimon.write.update_validation import _authorize_update
+
+
+class _ShardError(RuntimeError):
+ def __init__(self, phase, error):
+ self.phase = phase
+ self.error = error
+ # Ray pickles the exception arguments, but not its cause chain.
+ super().__init__(phase, error)
+
+
+def validate_ray_options(concurrency, ray_remote_args):
+ concurrency = 4 if concurrency is None else concurrency
+ if isinstance(concurrency, bool) or not isinstance(concurrency, int) or
concurrency < 1:
+ raise ValueError("concurrency must be a positive integer.")
+ options = dict(ray_remote_args or {})
+ if "num_returns" in options:
+ raise ValueError("compute_columns manages num_returns; omit it from
ray_remote_args.")
+ if options.get("max_retries", 0) != 0 or options.get("retry_exceptions",
False):
+ raise ValueError("Ray column computation requires max_retries=0 and
retry_exceptions=False.")
+ options.update(max_retries=0, retry_exceptions=False)
+ try:
+ import ray # noqa: F401
+ except ModuleNotFoundError as error:
+ if error.name != "ray":
+ raise
+ raise ImportError("Ray column computation requires pypaimon[ray].")
from error
+ return concurrency, options
+
+
+def prepare_ray_column_update(operation, table, commit_user, inputs, schema,
fn, batch_size, concurrency, remote_args):
+ import ray
+ from ray.exceptions import RayTaskError
+
+ plan = capture_row_id_plan(table)
+ groups = [split for _, _, split in plan.groups]
+ count = min(len(groups), concurrency)
+ if not count:
+ return [], 0
+
+ context = ray.put((plan.table, commit_user, inputs, schema, fn,
batch_size))
+ # Ray sets the default GPU worker exit policy when registering the
function.
+ worker = ray.remote(**remote_args)(_prepare_shard)
+ pending = []
+ try:
+ try:
+ for index in range(count):
+ start, end = shard_range(len(groups), index, count)
+ pending.append(worker.remote(context, groups[start:end]))
+ results = ray.get(pending)
+ except Exception as error:
+ # Drain dispatched writers and retain their staged files.
+ for ref in pending:
+ try:
+ ray.get(ref)
+ except Exception:
+ pass
+ if isinstance(error, RayTaskError) and isinstance(error.cause,
_ShardError):
+ operation.phase = error.cause.phase
+ raise error.cause.error from error
+ raise
+ except KeyboardInterrupt:
+ # Cancel later submissions first so they cannot use slots freed by
earlier tasks.
+ for ref in reversed(pending):
+ try:
+ ray.cancel(ref)
+ except Exception:
+ pass
+ raise
+ return [message for messages, _ in results for message in messages],
sum(rows for _, rows in results)
+
+
+def _prepare_shard(context, splits):
+ table, commit_user, inputs, schema, fn, batch_size = context
+ _authorize_update(table)
+ shard = create_python_shard_updator(table, inputs, schema.names,
commit_user, splits=splits)
+ progress = SimpleNamespace(phase="compute")
+ try:
+ result = _prepare_column_shard(shard, schema, fn, batch_size, progress)
+ except BaseException as error:
+ close_read_source(shard, error)
+ if isinstance(error, Exception):
+ raise _ShardError(progress.phase, error) from error
+ raise
+ try:
+ shard.close()
+ except Exception as error:
+ raise _ShardError("close", error) from error
+ return result
diff --git a/paimon-python/pypaimon/tests/ray_compute_columns_test.py
b/paimon-python/pypaimon/tests/ray_compute_columns_test.py
new file mode 100644
index 0000000000..3fe6b01e24
--- /dev/null
+++ b/paimon-python/pypaimon/tests/ray_compute_columns_test.py
@@ -0,0 +1,393 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import time
+from unittest.mock import Mock, patch
+
+import pyarrow as pa
+import pytest
+
+import pypaimon.multimodal as pmm
+from pypaimon.execution.python.write.table_update import ShardTableUpdator
+from pypaimon.manifest.schema.data_file_meta import DataFileMeta
+from pypaimon.ray import compute_columns as ray_compute
+from pypaimon.read.table_scan import TableScan
+from pypaimon.tests.multimodal_columns_test import _blobs, _files, _rows,
_snapshot
+from pypaimon.write.table_commit import BatchTableCommit
+
+ray = pytest.importorskip("ray")
+
+
[email protected](scope="module")
+def ray_cluster():
+ started = not ray.is_initialized()
+ if started:
+ with patch.dict(os.environ, {"CUDA_VISIBLE_DEVICES": "0"}):
+ ray.init(num_cpus=2, num_gpus=1, include_dashboard=False)
+ try:
+ yield
+ finally:
+ if started:
+ ray.shutdown()
+
+
[email protected]
+def frames(tmp_path, request):
+ connection = pmm.connect(options={"warehouse": str(tmp_path /
"warehouse")})
+ options = {"file.format": "parquet", "deletion-vectors.enabled": "true"}
+ dedicated_vector = getattr(request, "param", False)
+ if dedicated_vector:
+ options["vector.file.format"] = "parquet"
+ table = connection.create_table(
+ "frames",
+ schema=pa.schema([
+ ("id", pa.int64()), ("part", pa.string()),
+ ("image", pa.large_binary()), ("embedding", pa.list_(pa.float32(),
2)),
+ ]),
+ partitioned=["part"],
+ options=options,
+ )
+ for start in (0, 3, 6, 9):
+ part = "b" if dedicated_vector and start >= 6 else "a"
+ table.add([{"id": i, "part": part, "image": bytes([i]) * 100,
+ "embedding": [-1., -1.]} for i in range(start, start + 3)])
+ return table
+
+
+def _prepare_without_replanning(context, splits):
+ from pypaimon.ray.compute_columns import _prepare_shard
+
+ with patch.object(TableScan, "plan_all",
side_effect=AssertionError("worker replanned the table")):
+ return _prepare_shard(context, splits)
+
+
+def _wait_for_workers(directory, count):
+ deadline = time.monotonic() + 30
+ while len(list(directory.glob("worker-*"))) < count:
+ if time.monotonic() >= deadline:
+ raise AssertionError("expected concurrent Ray workers")
+ time.sleep(0.02)
+
+
[email protected]("frames", [False, True], indirect=True,
ids=["inline", "dedicated-vector"])
+def test_recompute_uses_disjoint_groups_and_one_commit(frames, tmp_path,
ray_cluster, monkeypatch):
+ frames.delete("id = 1")
+ source = _snapshot(frames)
+ blobs = _blobs(frames)
+ files = set(_files(frames))
+ schema_id = frames.raw_table.table_schema.id
+ driver = os.getpid()
+ planned = []
+ plan_all = TableScan.plan_all
+
+ def track_plan(scan):
+ plan = plan_all(scan)
+ planned.append(plan.snapshot_id)
+ return plan
+
+ def embed(batch):
+ assert batch.schema.names == ["image"]
+ assert batch.num_rows <= 2
+ assert os.getpid() != driver
+ (tmp_path / ("worker-%s" % os.getpid())).touch()
+ _wait_for_workers(tmp_path, 2)
+ images = batch["image"].to_pylist()
+ assert all(isinstance(image, bytes) for image in images)
+ return pa.table({"embedding": pa.array(
+ [[float(image[0]), float(len(image))] for image in images],
+ type=pa.list_(pa.float32(), 2))})
+
+ with monkeypatch.context() as patches:
+ patches.setattr(TableScan, "plan_all", track_plan)
+ patches.setattr(ray_compute, "_prepare_shard",
_prepare_without_replanning)
+ result = frames.compute_columns(
+ "embedding", inputs=["image"], fn=embed, batch_size=2,
execution="ray",
+ concurrency=2, ray_remote_args={"num_cpus": 1})
+ assert planned == [source]
+ assert result == pmm.ColumnUpdateResult(source, source + 1, schema_id, 11,
())
+ assert _snapshot(frames) == source + 1
+ assert _rows(frames, ["id", "embedding"]) == [
+ {"id": i, "embedding": [float(i), 100.]} for i in range(12) if i != 1]
+ assert _blobs(frames) == blobs
+ assert files.issubset(_files(frames))
+ new_files = [file for name, file in _files(frames).items() if name not in
files]
+ assert len(new_files) == 4
+ assert all(file.write_cols == ["embedding"] for file in new_files)
+ assert all(DataFileMeta.is_vector_file(file.file_name) ==
frames.raw_table.options.with_vector_format()
+ for file in new_files)
+
+
+def test_gpu_resource_is_passed_at_task_registration(frames, ray_cluster,
monkeypatch):
+ remote = ray.remote
+
+ def register_on_cpu(*args, **options):
+ # Check the registration option before scheduling the real task on a
CPU.
+ assert options.pop("num_gpus", None) == 1
+ return remote(*args, **options)
+
+ monkeypatch.setattr(ray, "remote", register_on_cpu)
+ result = frames.compute_columns(
+ "embedding", inputs=["embedding"], fn=lambda batch: batch,
execution="ray",
+ concurrency=1, ray_remote_args={"num_gpus": 1})
+
+ assert result.updated_rows == 12
+
+
+def test_gpu_shards_use_separate_worker_processes(frames, tmp_path,
ray_cluster):
+ if ray.cluster_resources().get("GPU", 0) < 1:
+ pytest.skip("requires one logical Ray GPU")
+
+ def record_worker(batch):
+ assert len(ray.get_gpu_ids()) == 1
+ (tmp_path / ("gpu-worker-%s" % os.getpid())).touch()
+ return batch
+
+ result = frames.compute_columns(
+ "embedding", inputs=["embedding"], fn=record_worker, execution="ray",
+ concurrency=2, ray_remote_args={"num_cpus": 1, "num_gpus": 1})
+
+ assert result.updated_rows == 12
+ assert len(list(tmp_path.glob("gpu-worker-*"))) == 2
+
+
[email protected]
+def vector_frames(tmp_path, request):
+ connection = pmm.connect(options={"warehouse": str(tmp_path /
"warehouse")})
+ table = connection.create_table(
+ "vectors",
+ schema=pa.schema([("id", pa.int64()), ("embedding",
pa.list_(pa.float32(), 2))]),
+ options={"file.format": "parquet", "vector.file.format": "parquet",
+ "vector.target-file-size": "1 b", "deletion-vectors.enabled":
"true"},
+ )
+ append_table = table.copy({"vector.target-file-size": "16 b" if
request.param else "1 mb"})
+ for start in (0, 6):
+ rows = [{"id": i, "embedding": [float(i), -1.]} for i in range(start,
start + 6)]
+ if request.param:
+ append_table.add_batches(rows[offset:offset + 2] for offset in
range(0, 6, 2))
+ else:
+ append_table.add(rows)
+ return table
+
+
[email protected]_write
[email protected]("vector_frames", [False], indirect=True)
+def test_vector_update_keeps_one_file_per_group(vector_frames, ray_cluster):
+ table = vector_frames
+ source = _snapshot(table)
+ files = _files(table)
+ assert sorted((file.first_row_id, file.row_count) for file in
files.values()
+ if DataFileMeta.is_vector_file(file.file_name)) == [(0, 6),
(6, 6)]
+
+ def embed(batch):
+ return pa.table({"embedding": pa.array(
+ [[float(i), 1.] for i in batch["id"].to_pylist()],
type=pa.list_(pa.float32(), 2))})
+
+ result = table.compute_columns("embedding", inputs=["id"], fn=embed,
batch_size=2, execution="ray")
+
+ assert result.updated_rows == 12
+ assert result.snapshot_id == source + 1
+ assert _rows(table, ["id", "embedding"]) == [
+ {"id": i, "embedding": [float(i), 1.]} for i in range(12)]
+ new_files = [file for name, file in _files(table).items() if name not in
files]
+ assert all(DataFileMeta.is_vector_file(file.file_name) for file in
new_files)
+ assert sorted((file.first_row_id, file.row_count) for file in new_files)
== [(0, 6), (6, 6)]
+
+
[email protected]_write
[email protected]("vector_frames", [True], indirect=True)
[email protected]("columns", [["id"], ["embedding"], ["id",
"embedding"]])
+def test_recompute_with_vector_files_inside_normal_ranges(vector_frames,
ray_cluster, columns):
+ table = vector_frames
+ files = list(_files(table).values())
+ assert sorted((file.first_row_id, file.row_count) for file in files
+ if not DataFileMeta.is_vector_file(file.file_name)) == [(0,
6), (6, 6)]
+ assert sorted((file.first_row_id, file.row_count) for file in files
+ if DataFileMeta.is_vector_file(file.file_name)) == [(i, 2)
for i in range(0, 12, 2)]
+ builder = table.raw_table.new_batch_write_builder()
+ commit = builder.new_commit()
+ try:
+ commit.commit(builder.new_update().delete_by_row_id([3, 7]))
+ finally:
+ commit.close()
+ source = _snapshot(table)
+ ids = [i for i in range(12) if i not in (3, 7)]
+ assert _rows(table, ["id", "embedding"]) == [
+ {"id": i, "embedding": [float(i), -1.]} for i in ids]
+
+ def recompute(batch):
+ values = batch["id"].to_pylist()
+ return pa.table({
+ "id": [i + 100 for i in values],
+ "embedding": pa.array([[float(i), 1.] for i in values],
type=pa.list_(pa.float32(), 2)),
+ }).select(columns)
+
+ result = table.compute_columns(columns, inputs=["id"], fn=recompute,
batch_size=2,
+ execution="ray", concurrency=2)
+
+ assert result.updated_rows == 10
+ assert result.snapshot_id == source + 1
+ offset = 100 if "id" in columns else 0
+ version = 1. if "embedding" in columns else -1.
+ assert _rows(table, ["id", "embedding"]) == [
+ {"id": i + offset, "embedding": [float(i), version]} for i in ids]
+
+
+def test_interrupt_cancels_running_and_queued_shards(frames, tmp_path,
ray_cluster, monkeypatch):
+ source = _snapshot(frames)
+ submitted = []
+ drained = []
+ ray_get = ray.get
+
+ def pause_before_writing(context, splits):
+ from pypaimon.ray.compute_columns import _prepare_shard
+
+ (tmp_path / ("worker-%s" % splits[0].files[0].first_row_id)).touch()
+ time.sleep(3)
+ return _prepare_shard(context, splits)
+
+ def interrupt_after_worker_starts(refs):
+ if isinstance(refs, list):
+ submitted.extend(refs)
+ _wait_for_workers(tmp_path, 1)
+ raise KeyboardInterrupt
+ drained.append(refs)
+ return ray_get(refs)
+
+ monkeypatch.setattr(ray_compute, "_prepare_shard", pause_before_writing)
+ monkeypatch.setattr(ray, "get", interrupt_after_worker_starts)
+ with pytest.raises(KeyboardInterrupt):
+ frames.compute_columns("embedding", inputs=["embedding"], fn=lambda
batch: batch, execution="ray",
+ concurrency=2, ray_remote_args={"num_cpus":
ray.cluster_resources()["CPU"]})
+
+ assert len(submitted) == 2
+ assert not drained
+ for ref in submitted:
+ with pytest.raises(ray.exceptions.TaskCancelledError):
+ ray_get(ref, timeout=15)
+ assert len(list(tmp_path.glob("worker-*"))) == 1
+ assert _snapshot(frames) == source
+
+
+def test_invalid_worker_output_after_another_shard_prepares(frames, tmp_path,
ray_cluster, monkeypatch):
+ source = _snapshot(frames)
+ files = set(_files(frames))
+ prepared = tmp_path / "prepared"
+
+ def prepare_and_signal(context, splits):
+ from pypaimon.ray.compute_columns import _prepare_shard
+
+ messages, rows = _prepare_shard(context, splits)
+ assert messages and rows
+ prepared.touch()
+ return messages, rows
+
+ def invalid_second_shard(batch):
+ if batch["id"][0].as_py() >= 6:
+ deadline = time.monotonic() + 30
+ while not prepared.exists():
+ if time.monotonic() >= deadline:
+ raise AssertionError("first shard did not prepare")
+ time.sleep(0.02)
+ return pa.table({"embedding": pa.array([],
type=pa.list_(pa.float32(), 2))})
+ return batch.select(["embedding"])
+
+ commit = Mock(side_effect=AssertionError("must not commit"))
+ monkeypatch.setattr(BatchTableCommit, "commit", commit)
+ monkeypatch.setattr(ray_compute, "_prepare_shard", prepare_and_signal)
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ frames.compute_columns("embedding", inputs=["id", "embedding"],
fn=invalid_second_shard,
+ execution="ray", concurrency=2)
+
+ commit.assert_not_called()
+ assert prepared.exists()
+ assert failure.value.source_snapshot_id == source
+ assert failure.value.phase == "compute"
+ assert failure.value.commit_outcome == "not_started"
+ assert "one output row per input row" in str(failure.value.__cause__)
+ assert _snapshot(frames) == source
+ assert set(_files(frames)) == files
+ assert all(row["embedding"] == [-1., -1.] for row in _rows(frames, ["id",
"embedding"]))
+
+
+def test_worker_write_failure_preserves_phase_and_cause(frames, ray_cluster,
monkeypatch):
+ source = _snapshot(frames)
+
+ def prepare_with_failing_writer(context, splits):
+ from pypaimon.ray.compute_columns import _prepare_shard
+
+ with patch.object(ShardTableUpdator, "_flush_group",
side_effect=OSError("shard write failed")):
+ return _prepare_shard(context, splits)
+
+ monkeypatch.setattr(ray_compute, "_prepare_shard",
prepare_with_failing_writer)
+ with pytest.raises(pmm.ColumnUpdateError) as failure:
+ frames.compute_columns("embedding", inputs=["embedding"], fn=lambda
batch: batch,
+ execution="ray", concurrency=2)
+
+ assert failure.value.phase == "write"
+ assert failure.value.commit_outcome == "not_started"
+ cause = failure.value.__cause__
+ assert type(cause) is OSError
+ assert str(cause) == "shard write failed"
+ assert isinstance(cause.__cause__, ray.exceptions.RayTaskError)
+ assert _snapshot(frames) == source
+
+
+def test_later_append_is_outside_captured_snapshot(frames, ray_cluster):
+ source = _snapshot(frames)
+ capture = ray_compute.capture_row_id_plan
+
+ def capture_then_append(table):
+ plan = capture(table)
+ frames.add([{"id": 12, "part": "b", "image": b"later", "embedding":
[-1., -1.]}])
+ return plan
+
+ def embed(batch):
+ return pa.table({"embedding": pa.array(
+ [[1., 2.]] * batch.num_rows, type=pa.list_(pa.float32(), 2))})
+
+ with patch.object(ray_compute, "capture_row_id_plan", capture_then_append):
+ result = frames.compute_columns("embedding", inputs=["image"],
fn=embed, execution="ray")
+
+ assert result.source_snapshot_id == source
+ assert result.snapshot_id == source + 2
+ assert result.updated_rows == 12
+ assert _rows(frames, ["id", "embedding"]) == [
+ {"id": i, "embedding": [1., 2.]} for i in range(12)] + [{"id": 12,
"embedding": [-1., -1.]}]
+
+
+def test_empty_snapshot_skips_ray_tasks(tmp_path):
+ connection = pmm.connect(options={"warehouse": str(tmp_path)})
+ frames = connection.create_table("empty", schema=pa.schema([("value",
pa.int64())]))
+ with patch.object(ray, "remote", side_effect=AssertionError("must not
start a task")):
+ result = frames.compute_columns("value", inputs=["value"], fn=lambda
batch: batch, execution="ray")
+ assert result.source_snapshot_id is None
+ assert result.snapshot_id is None
+ assert result.updated_rows == 0
+
+
[email protected]("options,match", [
+ ({"execution": "other"}, "execution"),
+ ({"concurrency": 1}, "execution='ray'"),
+ ({"execution": "ray", "concurrency": 0}, "concurrency"),
+ ({"execution": "ray", "ray_remote_args": {"num_returns": 2}},
"num_returns"),
+ ({"execution": "ray", "ray_remote_args": {"max_retries": 1}},
"max_retries"),
+ ({"execution": "ray", "ray_remote_args": {"retry_exceptions": True}},
"retry_exceptions"),
+])
+def test_invalid_ray_options_are_rejected_before_planning(frames, options,
match):
+ with patch.object(TableScan, "plan_all", side_effect=AssertionError("must
not plan the table")):
+ with pytest.raises(ValueError, match=match):
+ frames.compute_columns("embedding", inputs=["embedding"],
fn=lambda batch: batch, **options)
diff --git a/paimon-python/pypaimon/write/backend_dispatch.py
b/paimon-python/pypaimon/write/backend_dispatch.py
index 5c35016f27..f25af5ab51 100644
--- a/paimon-python/pypaimon/write/backend_dispatch.py
+++ b/paimon-python/pypaimon/write/backend_dispatch.py
@@ -313,10 +313,10 @@ def create_python_row_id_delete(table, precomputed=None):
return PythonTableDeleteByRowId().initialize(table, precomputed)
-def create_python_shard_updator(table, projection, columns, commit_user,
shard, shard_count):
+def create_python_shard_updator(table, projection, columns, commit_user,
shard=0, shard_count=1, *, splits=None):
"""Initialize the Python shard resources only after backend selection."""
from pypaimon.execution.python.write.table_update import ShardTableUpdator
- return ShardTableUpdator(table, projection, columns, commit_user, shard,
shard_count)
+ return ShardTableUpdator(table, projection, columns, commit_user, shard,
shard_count, splits=splits)
def create_python_update_operation(context, commit_identifier, predicate=None,
*, has_callable=False, has_array=False):