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 68023de116 [python] Support Ray execution for multimodal add_columns
(#11100)
68023de116 is described below
commit 68023de1160c16a67dd839c638ba817de23a9212
Author: QuakeWang <[email protected]>
AuthorDate: Thu Nov 12 10:32:49 2026 +0800
[python] Support Ray execution for multimodal add_columns (#11100)
---
docs/docs/pypaimon/multimodal-tables.mdx | 25 ++++--
paimon-python/README.md | 14 +++-
paimon-python/pypaimon/multimodal/columns.py | 41 ++++++----
paimon-python/pypaimon/multimodal/table.py | 17 +++--
paimon-python/pypaimon/ray/compute_columns.py | 27 +++++--
.../pypaimon/tests/multimodal_columns_test.py | 10 +++
.../pypaimon/tests/ray_compute_columns_test.py | 88 ++++++++++++++++------
7 files changed, 160 insertions(+), 62 deletions(-)
diff --git a/docs/docs/pypaimon/multimodal-tables.mdx
b/docs/docs/pypaimon/multimodal-tables.mdx
index e1640a8f4e..a789f602c0 100644
--- a/docs/docs/pypaimon/multimodal-tables.mdx
+++ b/docs/docs/pypaimon/multimodal-tables.mdx
@@ -337,8 +337,8 @@ 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
+`compute_columns` 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
@@ -348,16 +348,25 @@ 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
+To backfill a new column or recompute an existing one on Ray, install
+`pypaimon[ray]` and set `execution="ray"` on `add_columns` or
`compute_columns`.
+For `add_columns`, Ray execution requires `fn`. Before publishing the schema,
+the driver validates the Ray task definition. In
`ray_remote_args["resources"]`,
+it rejects reserved keys such as `bundle`, requires integer or floating-point
+quantities, and checks that positive quantities have ASCII resource names.
+Ray checks placement group compatibility at task submission, and runtime
+environment setup and the function can fail during execution. If submission or
+execution fails before the data commit, the new columns remain visible as NULL.
+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.
+the prepared files unpublished. The following call adds `image_size` to a table
+that does not already have that column.
```python
-result = frames.compute_columns(
- "image_size", inputs=["image"], fn=image_sizes, batch_size=128,
+result = frames.add_columns(
+ pa.schema([("image_size", pa.int64())]), inputs=["image"], fn=image_sizes,
batch_size=128,
execution="ray", concurrency=4, ray_remote_args={"num_cpus": 1},
)
```
@@ -406,7 +415,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 local `compute_columns` can use the native shard reader and
writer
+Local `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
diff --git a/paimon-python/README.md b/paimon-python/README.md
index 9b122b788e..2c6379e123 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 local column-enrichment methods:
+Multimodal Data Evolution tables provide column-enrichment methods:
```python
# labels is a typed Arrow table containing sample_id and the columns to fill.
@@ -158,7 +158,13 @@ Outputs must have the declared/existing types. A
fixed-size Arrow list declares
a VECTOR column, for example `pa.list_(pa.float32(), 768)` for an embedding.
These methods require a current full-table view and a single writer during the
-operation. They do not provide distributed execution or automatic retries.
+operation. `add_columns` with `fn` and `compute_columns` support
`execution="ray"`
+with `pypaimon[ray]` installed. `concurrency` caps the number of shards and
+`ray_remote_args` configures task resources. The driver commits the backfill
+after all workers succeed. For `add_columns`, task definition and static
+resource checks run before schema publication. Ray can still reject placement
+group constraints during submission, and workers can fail during execution.
+There are no automatic retries.
`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`
@@ -170,8 +176,8 @@ Function calls have at most
`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` and `compute_columns` can use the native shard reader and writer;
-their `fn` runs in Python.
+Local `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
diff --git a/paimon-python/pypaimon/multimodal/columns.py
b/paimon-python/pypaimon/multimodal/columns.py
index 5b419d85ec..d5c578af19 100644
--- a/paimon-python/pypaimon/multimodal/columns.py
+++ b/paimon-python/pypaimon/multimodal/columns.py
@@ -295,7 +295,8 @@ def update_columns_by_row_id(owner, data, *, columns):
return operation.finish(source.num_rows, commit=commit,
messages=messages)
-def add_columns(owner, schema, *, inputs, fn, batch_size):
+def add_columns(owner, schema, *, inputs, fn, batch_size,
+ execution="local", concurrency=None, ray_remote_args=None):
if not isinstance(schema, pa.Schema):
raise ValueError("schema must be a pyarrow.Schema.")
_validate_names(schema.names, "Schema")
@@ -311,21 +312,21 @@ def add_columns(owner, schema, *, inputs, fn, batch_size):
if fn is None:
if inputs is not None:
raise ValueError("inputs requires fn.")
+ if execution == "ray":
+ raise ValueError("execution='ray' requires fn.")
else:
inputs = _validate_inputs(raw, inputs, fn)
+ concurrency, ray_worker = _prepare_compute_worker(execution, concurrency,
ray_remote_args)
with _ColumnUpdate(owner, raw) as operation:
operation.add_schema(fields)
if fn is None:
return operation.finish(0)
- return _compute_columns(operation, pa.schema(fields), inputs, fn,
batch_size)
+ return _compute_columns(operation, pa.schema(fields), inputs, fn,
batch_size,
+ concurrency=concurrency, ray_worker=ray_worker)
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)
@@ -341,26 +342,34 @@ 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)
+ concurrency, ray_worker = _prepare_compute_worker(execution, concurrency,
ray_remote_args)
with _ColumnUpdate(owner, raw) as operation:
- return _compute_columns(operation, schema, inputs, fn, batch_size,
execution=execution,
- concurrency=concurrency,
ray_remote_args=ray_remote_args)
+ return _compute_columns(operation, schema, inputs, fn, batch_size,
+ concurrency=concurrency, ray_worker=ray_worker)
+
+def _prepare_compute_worker(execution, concurrency, ray_remote_args):
+ if execution == "local":
+ if concurrency is not None or ray_remote_args is not None:
+ raise ValueError("Ray options require execution='ray'.")
+ return None, None
+ if execution == "ray":
+ from pypaimon.ray.compute_columns import create_ray_column_worker
+ return create_ray_column_worker(concurrency, ray_remote_args)
+ raise ValueError("execution must be 'local' or 'ray'.")
-def _compute_columns(operation, schema, inputs, fn, batch_size, *,
- execution="local", concurrency=None,
ray_remote_args=None):
+
+def _compute_columns(operation, schema, inputs, fn, batch_size, *,
concurrency, ray_worker):
operation.phase = "compute"
options = {
"blob-as-descriptor": "false", "read.batch-size": str(batch_size),
}
- if execution == "ray":
+ if ray_worker is not None:
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())
- if execution == "local":
+ if ray_worker is None:
update = builder.new_update().with_update_type(schema.names)
update.with_read_projection(inputs)
shard = operation.keep(update.new_shard_updator(0, 1))
@@ -368,7 +377,7 @@ def _compute_columns(operation, schema, inputs, fn,
batch_size, *,
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)
+ operation, table, builder.commit_user, inputs, schema, fn,
batch_size, concurrency, ray_worker)
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 5686bdfcde..de39dcb5be 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -535,7 +535,8 @@ class MultimodalTable:
from pypaimon.multimodal.columns import merge_columns
return merge_columns(self, data, on=on)
- def add_columns(self, schema, *, inputs=None, fn=None, batch_size=1024):
+ def add_columns(self, schema, *, inputs=None, fn=None, batch_size=1024,
execution="local",
+ concurrency=None, ray_remote_args=None):
"""Add nullable columns, optionally computing their values in batches.
``schema`` declares new columns. If supplied, ``fn`` receives an
@@ -547,12 +548,17 @@ class MultimodalTable:
Outputs are grouped by the original file row-ID ranges before being
written. Untouched columns, including media, retain their files.
- Schema publication precedes computation; failures leave new columns
- visible as NULL. Requires a current full-table view and a single
- writer. Returns :class:`pypaimon.multimodal.ColumnUpdateResult`.
+ With ``execution="ray"``, ``fn`` is required. Task definition and
+ static resource checks run before schema publication. See
+ :meth:`compute_columns` for Ray execution options and requirements.
+ Schema publication precedes task submission and computation. If
+ submission or computation fails before the data commit, the new
+ columns remain visible as NULL. Requires a current full-table view and
+ a single writer. Returns
:class:`pypaimon.multimodal.ColumnUpdateResult`.
"""
from pypaimon.multimodal.columns import add_columns
- return add_columns(self, schema, inputs=inputs, fn=fn,
batch_size=batch_size)
+ return add_columns(self, schema, inputs=inputs, fn=fn,
batch_size=batch_size,
+ execution=execution, concurrency=concurrency,
ray_remote_args=ray_remote_args)
def update_columns_by_row_id(self, data, *, columns):
"""Update existing columns from one local Arrow table containing
``_ROW_ID``.
@@ -596,6 +602,7 @@ class MultimodalTable:
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.
+ Task definition and static resource checks run before planning the
update.
``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.
diff --git a/paimon-python/pypaimon/ray/compute_columns.py
b/paimon-python/pypaimon/ray/compute_columns.py
index b6f5c62a5e..727bd3d5dc 100644
--- a/paimon-python/pypaimon/ray/compute_columns.py
+++ b/paimon-python/pypaimon/ray/compute_columns.py
@@ -32,26 +32,39 @@ class _ShardError(RuntimeError):
super().__init__(phase, error)
-def validate_ray_options(concurrency, ray_remote_args):
+def create_ray_column_worker(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 {})
+ options = {} if ray_remote_args is None else dict(ray_remote_args)
if "num_returns" in options:
- raise ValueError("compute_columns manages num_returns; omit it from
ray_remote_args.")
+ raise ValueError("Ray column computation 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
+ import ray
except ModuleNotFoundError as error:
if error.name != "ray":
raise
raise ImportError("Ray column computation requires pypaimon[ray].")
from error
- return concurrency, options
+ # Defining the task validates its options and applies Ray's GPU worker
exit policy.
+ worker = ray.remote(**options)(_prepare_shard)
+ # Ray defers these resource checks until task submission.
+ resources = options.get("resources") or {}
+ reserved = {"bundle", "memory",
"object_store_memory"}.intersection(resources)
+ if reserved:
+ raise ValueError("Ray reserves resource names %s in
ray_remote_args['resources']." % sorted(reserved))
+ for name, quantity in resources.items():
+ if not isinstance(quantity, (int, float)):
+ raise ValueError("Ray resource quantities must be integers or
floats.")
+ if quantity > 0 and (not isinstance(name, str) or not name.isascii()):
+ raise ValueError("Ray resource names must be ASCII strings.")
+ return concurrency, worker
-def prepare_ray_column_update(operation, table, commit_user, inputs, schema,
fn, batch_size, concurrency, remote_args):
+
+def prepare_ray_column_update(operation, table, commit_user, inputs, schema,
fn, batch_size, concurrency, worker):
import ray
from ray.exceptions import RayTaskError
@@ -62,8 +75,6 @@ def prepare_ray_column_update(operation, table, commit_user,
inputs, schema, fn,
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:
diff --git a/paimon-python/pypaimon/tests/multimodal_columns_test.py
b/paimon-python/pypaimon/tests/multimodal_columns_test.py
index 6c58e26017..928fd2ff51 100644
--- a/paimon-python/pypaimon/tests/multimodal_columns_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_columns_test.py
@@ -684,6 +684,7 @@ def test_column_enrichment_on_an_empty_table(tmp_path):
(pa.schema([pa.field("feature", pa.int64(), nullable=False)]), {}),
(pa.schema([("_ROW_ID", pa.int64())]), {}),
(pa.schema([("feature", pa.int64())]), {"batch_size": 0}),
+ (pa.schema([("feature", pa.int64())]), {"execution": "ray"}),
])
def test_add_columns_validation_never_publishes_schema(frames, schema, kwargs):
schema_id = frames.raw_table.table_schema.id
@@ -692,6 +693,15 @@ def
test_add_columns_validation_never_publishes_schema(frames, schema, kwargs):
assert frames.catalog.get_table(frames.identifier).table_schema.id ==
schema_id
+def test_add_columns_requires_ray_before_publishing_schema(frames):
+ schema_id = frames.raw_table.table_schema.id
+ with patch.dict("sys.modules", {"ray": None}):
+ with pytest.raises(ImportError, match=r"pypaimon\[ray\]"):
+ frames.add_columns(pa.schema([("feature", pa.int64())]),
inputs=["id"],
+ fn=lambda batch: batch, execution="ray")
+ assert frames.catalog.get_table(frames.identifier).table_schema.id ==
schema_id
+
+
def test_enrichment_rejects_historical_views(frames):
historical = frames.copy({"scan.snapshot-id": str(_snapshot(frames))})
with pytest.raises(ValueError, match="current full-table"):
diff --git a/paimon-python/pypaimon/tests/ray_compute_columns_test.py
b/paimon-python/pypaimon/tests/ray_compute_columns_test.py
index 3fe6b01e24..9180a388b6 100644
--- a/paimon-python/pypaimon/tests/ray_compute_columns_test.py
+++ b/paimon-python/pypaimon/tests/ray_compute_columns_test.py
@@ -16,6 +16,7 @@
import os
import time
+from decimal import Decimal
from unittest.mock import Mock, patch
import pyarrow as pa
@@ -84,12 +85,15 @@ def _wait_for_workers(directory, count):
@pytest.mark.parametrize("frames", [False, True], indirect=True,
ids=["inline", "dedicated-vector"])
-def test_recompute_uses_disjoint_groups_and_one_commit(frames, tmp_path,
ray_cluster, monkeypatch):
[email protected]("add", [False, True], ids=["compute", "add"])
+def test_column_computation_uses_disjoint_groups_and_one_commit(frames,
tmp_path, ray_cluster, monkeypatch, add):
frames.delete("id = 1")
source = _snapshot(frames)
blobs = _blobs(frames)
files = set(_files(frames))
schema_id = frames.raw_table.table_schema.id
+ column = "embedding_v2" if add else "embedding"
+ vector_type = pa.list_(pa.float32(), 2)
driver = os.getpid()
planned = []
plan_all = TableScan.plan_all
@@ -107,26 +111,30 @@ def
test_recompute_uses_disjoint_groups_and_one_commit(frames, tmp_path, ray_clu
_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))})
+ return pa.table({column: pa.array(
+ [[float(image[0]), float(len(image))] for image in images],
type=vector_type)})
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})
+ options = dict(inputs=["image"], fn=embed, batch_size=2,
execution="ray",
+ concurrency=2, ray_remote_args={"num_cpus": 1})
+ if add:
+ result = frames.add_columns(pa.schema([(column, vector_type)]),
**options)
+ else:
+ result = frames.compute_columns(column, **options)
assert planned == [source]
- assert result == pmm.ColumnUpdateResult(source, source + 1, schema_id, 11,
())
+ expected_schema_id = schema_id + int(add)
+ assert result == pmm.ColumnUpdateResult(source, source + 1,
expected_schema_id, 11, (column,) if add else ())
+ assert frames.catalog.get_table(frames.identifier).table_schema.id ==
expected_schema_id
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 _rows(frames, ["id", column]) == [
+ {"id": i, column: [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(file.write_cols == [column] 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)
@@ -282,9 +290,13 @@ def
test_interrupt_cancels_running_and_queued_shards(frames, tmp_path, ray_clust
assert _snapshot(frames) == source
-def test_invalid_worker_output_after_another_shard_prepares(frames, tmp_path,
ray_cluster, monkeypatch):
[email protected]("add", [False, True], ids=["compute", "add"])
+def test_invalid_worker_output_after_another_shard_prepares(frames, tmp_path,
ray_cluster, monkeypatch, add):
source = _snapshot(frames)
files = set(_files(frames))
+ schema_id = frames.raw_table.table_schema.id
+ column = "embedding_v2" if add else "embedding"
+ vector_type = pa.list_(pa.float32(), 2)
prepared = tmp_path / "prepared"
def prepare_and_signal(context, splits):
@@ -302,25 +314,33 @@ def
test_invalid_worker_output_after_another_shard_prepares(frames, tmp_path, ra
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"])
+ return pa.table({column: pa.array([], type=vector_type)})
+ return pa.table({column: batch["embedding"]})
commit = Mock(side_effect=AssertionError("must not commit"))
monkeypatch.setattr(BatchTableCommit, "commit", commit)
monkeypatch.setattr(ray_compute, "_prepare_shard", prepare_and_signal)
+ options = dict(inputs=["id", "embedding"], fn=invalid_second_shard,
execution="ray", concurrency=2)
with pytest.raises(pmm.ColumnUpdateError) as failure:
- frames.compute_columns("embedding", inputs=["id", "embedding"],
fn=invalid_second_shard,
- execution="ray", concurrency=2)
+ if add:
+ frames.add_columns(pa.schema([(column, vector_type)]), **options)
+ else:
+ frames.compute_columns(column, **options)
commit.assert_not_called()
assert prepared.exists()
assert failure.value.source_snapshot_id == source
+ assert failure.value.schema_changed is add
+ assert failure.value.schema_id == schema_id + int(add)
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"]))
+ if add:
+ assert column in
frames.catalog.get_table(frames.identifier).field_names
+ assert frames.scan().select([column]).to_arrow()[column].to_pylist()
== [None] * 12
def test_worker_write_failure_preserves_phase_and_cause(frames, ray_cluster,
monkeypatch):
@@ -369,14 +389,20 @@ def
test_later_append_is_outside_captured_snapshot(frames, ray_cluster):
{"id": i, "embedding": [1., 2.]} for i in range(12)] + [{"id": 12,
"embedding": [-1., -1.]}]
-def test_empty_snapshot_skips_ray_tasks(tmp_path):
[email protected]("add", [False, True], ids=["compute", "add"])
+def test_empty_snapshot_skips_ray_tasks(tmp_path, add):
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")
+ options = dict(inputs=["value"], fn=lambda batch: batch, execution="ray")
+ with patch.object(ray, "put", side_effect=AssertionError("must not submit
work")):
+ if add:
+ result = frames.add_columns(pa.schema([("feature", pa.int64())]),
**options)
+ else:
+ result = frames.compute_columns("value", **options)
assert result.source_snapshot_id is None
assert result.snapshot_id is None
assert result.updated_rows == 0
+ assert result.added_columns == (("feature",) if add else ())
@pytest.mark.parametrize("options,match", [
@@ -386,8 +412,28 @@ def test_empty_snapshot_skips_ray_tasks(tmp_path):
({"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"),
+ ({"execution": "ray", "ray_remote_args": {"num_cpus": -1}}, "num_cpus"),
+ ({"execution": "ray", "ray_remote_args": {"unknown_option": 1}},
"unknown_option"),
+ ({"execution": "ray", "ray_remote_args": {"resources": {"bundle": 1}}},
"bundle"),
+ ({"execution": "ray", "ray_remote_args": {"resources": {"memory": 1}}},
"memory"),
+ ({"execution": "ray", "ray_remote_args": {"resources":
{"object_store_memory": 1}}}, "object_store_memory"),
+ ({"execution": "ray", "ray_remote_args": {"resources": {1: 1}}}, "resource
names"),
+ ({"execution": "ray", "ray_remote_args": {"resources": {"\u00e9": 1}}},
"resource names"),
+ ({"execution": "ray", "ray_remote_args": {"resources": {"custom":
Decimal("1")}}}, "resource quantities"),
])
-def test_invalid_ray_options_are_rejected_before_planning(frames, options,
match):
[email protected]("add", [False, True], ids=["compute", "add"])
+def test_invalid_ray_options_are_rejected_before_mutation(frames, options,
match, add):
+ source = _snapshot(frames)
+ schema_id = frames.raw_table.table_schema.id
+ field_names = frames.raw_table.field_names
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)
+ if add:
+ frames.add_columns(pa.schema([("feature", pa.int64())]),
+ inputs=["id"], fn=lambda batch: batch,
**options)
+ else:
+ frames.compute_columns("embedding", inputs=["embedding"],
fn=lambda batch: batch, **options)
+ persisted = frames.catalog.get_table(frames.identifier)
+ assert persisted.table_schema.id == schema_id
+ assert persisted.field_names == frames.raw_table.field_names == field_names
+ assert persisted.snapshot_manager().get_latest_snapshot().id == source