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 a167267f1c [python] Batch primary-key vector result lookup (#10984)
a167267f1c is described below
commit a167267f1ce109bb0fcb5a193552e7e5613712ae
Author: tzphh <[email protected]>
AuthorDate: Fri Nov 6 23:57:20 2026 +0800
[python] Batch primary-key vector result lookup (#10984)
---
docs/docs/pypaimon/multimodal-search.md | 60 +++---
.../multimodal/primary_key_batch_lookup.py | 115 +++++++++++
paimon-python/pypaimon/multimodal/query.py | 21 +-
paimon-python/pypaimon/ray/search_result.py | 105 ++++++----
.../pypaimon/tests/pk_search_capabilities_test.py | 34 +--
.../tests/primary_key_batch_lookup_test.py | 228 +++++++++++++++++++++
.../tests/ray_primary_key_vector_search_test.py | 47 ++++-
7 files changed, 513 insertions(+), 97 deletions(-)
diff --git a/docs/docs/pypaimon/multimodal-search.md
b/docs/docs/pypaimon/multimodal-search.md
index 1cfc15e5c2..ce6afb7973 100644
--- a/docs/docs/pypaimon/multimodal-search.md
+++ b/docs/docs/pypaimon/multimodal-search.md
@@ -218,9 +218,9 @@ Full-text and hybrid queries are described below.
For primary-key tables, enable the Python read backend with
`read.native.enabled=false` and `scan.native-plan.enabled=false`. Search
-parallelism is limited by the number of matching buckets; refinement and result
-lookup run on the driver. Primary-key vector queries do not support Native Ray
-execution, Ray Dataset results (`to_ray()`), `with_score()`, or
`order_by_score()`.
+parallelism is limited by the number of matching buckets. Refinement and Arrow
+result lookup run on the driver. To fetch projected rows on Ray workers, use
+[`to_ray()`](#return-search-rows-as-a-ray-dataset).
Install the same PyPaimon and index dependencies on the driver and workers:
@@ -249,10 +249,11 @@ neighbors = (
)
```
-`execution` defaults to `"local"`. `concurrency` is a positive integer limiting
-the number of in-flight Ray tasks, with a default of 4. `ray_remote_args`
supplies
-Ray task options, including resources and retry settings; `num_returns` is
-managed by PyPaimon. These two arguments require `execution="ray"`.
+For `to_arrow()`, `execution` defaults to `"local"`. `concurrency` is a
positive
+integer limiting the number of in-flight Ray tasks, with a default of 4.
+`ray_remote_args` supplies Ray task options, including resources and retry
+settings. PyPaimon manages `num_returns`. These two arguments require
+`execution="ray"`.
Ray schedules tasks from the selected search backend. With Native reads enabled
on a supported REST table, Rust performs the query, filtering and ranking on
the
@@ -324,7 +325,7 @@ Each index task searches one shard, while its native index
I/O settings still
apply. Raw-scan parallelism is limited by the number of planned read splits,
controlled by the table's `source.split.target-size` option. For data-evolution
tables, refinement also uses planned read splits; workers return scores for
merging.
-Final row lookup runs on the driver. Candidate traffic grows
+For Arrow results, final row lookup runs on the driver. Candidate traffic grows
with the number of index shards and the configured refinement budget, so Ray
execution is most useful when shard search or raw scanning outweighs scheduling
and transfer costs. Small queries can be faster locally.
@@ -491,9 +492,12 @@ Dictionary vector routes also accept `anns_field`, `data`,
and `param` aliases.
Use `search_vectors` for multiple query vectors against one vector column. It
returns one result set for each input vector, preserving input order.
-Batch results share a lookup of their combined row IDs, so overlapping results
-do not require reading the same row separately for each query. The limit and
-post-filter still apply to each query's result set.
+For Arrow results on data-evolution tables, batch queries can share a lookup
+of their combined row IDs. On primary-key tables using the Python read backend,
+eligible queries that hit the same data file can share reads of the selected
+physical row positions. When each file is selected by at most one query, each
+query uses its own lookup and can read its files in parallel. The limit and
+post-filter apply to each query's result set.
```python
batch_neighbors = (
@@ -512,27 +516,29 @@ batch_neighbors = (
## Return search rows as a Ray Dataset
-Vector queries support `to_ray()` to run candidate search on Ray and fetch the
-selected columns on workers. Single queries return one Dataset;
`search_vectors`
-returns one Dataset per input vector. Candidate IDs and scores are merged on
the
-driver, while projected row data stays in Ray blocks.
+Vector queries on data-evolution tables and primary-key tables using the Python
+read backend can return a Ray Dataset with `to_ray()`. The `execution` option
+selects where candidate search runs. It defaults to `"ray"`. Use `"local"` to
+search for candidates on the driver. With either option, Ray workers fetch the
+projected rows when you consume the Dataset.
```python
ds = (docs.search([0.1, 0.2, 0.3], column="embedding")
- .select(["content", "image"])
- .with_score().order_by_score().limit(100)
- .to_ray(concurrency=4, override_num_blocks=4))
+ .select(["id", "content"])
+ .limit(100)
+ .to_ray(execution="ray", concurrency=4, override_num_blocks=4))
```
-Search runs eagerly; row lookup is lazy and uses the same captured snapshot.
-Retain that snapshot's files until downstream Dataset actions finish. `where`
-filters the candidates during lookup without refilling top-k. `order_by_score`
-performs a distributed global sort, breaking ties by ascending row ID. Empty
-results retain their output schema, including the score column.
+Search runs eagerly. Row lookup is lazy and uses the snapshot captured during
+search. Retain that snapshot's files until downstream Dataset actions finish.
+`search_vectors(...).to_ray()` returns one Dataset per input vector, in input
+order. Each Dataset runs its own lazy lookup on the shared snapshot when
consumed.
+
+`where()` filters the candidates during lookup without refilling top-k. On
+data-evolution tables, `with_score()` adds scores and `order_by_score()`
performs
+a distributed global sort, breaking ties by ascending row ID. Empty results
+retain their output schema, including the score column when requested.
BLOB values are serialized descriptors, as with `scan().to_ray()`. Pass the
Dataset to `docs.map_with_blobs(...)` to resolve payloads on workers.
Projections
-must be nonempty and have unique names. This API requires data evolution;
-`execution="local"` selects local candidate search while keeping distributed
-lookup. Batch queries share candidate-search work but have separate lazy lookup
-pipelines for each query.
+must be nonempty and have unique names.
diff --git a/paimon-python/pypaimon/multimodal/primary_key_batch_lookup.py
b/paimon-python/pypaimon/multimodal/primary_key_batch_lookup.py
new file mode 100644
index 0000000000..bf675d2237
--- /dev/null
+++ b/paimon-python/pypaimon/multimodal/primary_key_batch_lookup.py
@@ -0,0 +1,115 @@
+# 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.
+
+"""Share physical-position reads across primary-key vector query results."""
+
+from copy import copy
+
+import pyarrow as pa
+
+from pypaimon.execution.python.deletionvectors.deletion_vector import
DeletionVector
+from pypaimon.execution.python.index.pk.primary_key_index_source_policy import
should_read
+from pypaimon.globalindex.indexed_split import IndexedSplit
+from pypaimon.table.source.primary_key_scored_result import (
+ PrimaryKeyScoredResult, _partition_bytes, _ranges,
+)
+from pypaimon.utils.arrow_utils import zero_column_batch
+
+
+def _take(rows, indices):
+ if not rows.num_columns:
+ return pa.Table.from_batches([zero_column_batch(len(indices),
rows.schema.metadata)])
+ return rows.take(pa.array(indices, type=pa.int64()))
+
+
+def read_primary_key_batch(query, results):
+ """Return shared lookup tables, or None when position mapping is
unavailable."""
+ table = query._table
+ if (not table.is_primary_key_table or query._predicate is not None
+ or table.options.query_auth_enabled or
table.options.native_read_enabled()
+ or not all(isinstance(result, PrimaryKeyScoredResult) for result
in results)
+ or len({result.snapshot_id for result in results}) != 1):
+ return None
+ projection = query._effective_projection()
+ if projection and not query._configured_read_builder()._output_fields():
+ return None
+
+ groups = {}
+ selections = []
+ for result in results:
+ selected = []
+ for split in result.splits:
+ if not isinstance(split, IndexedSplit) or len(split.files) != 1:
+ return None
+ data = split.data_split()
+ file = data.files[0]
+ if not should_read(file):
+ return None
+ key = (_partition_bytes(data.partition), data.bucket,
file.file_name)
+ positions = {position for r in split.row_ranges()
+ for position in range(r.from_, r.to + 1)}
+ if key not in groups:
+ groups[key] = (data, set())
+ source, union = groups[key]
+ if source.files != data.files or source.data_deletion_files !=
data.data_deletion_files:
+ return None
+ union.update(positions)
+ selected.append((key, positions))
+ selections.append(selected)
+
+ # Preserve per-query read parallelism when every file is selected once.
+ if len(groups) == sum(len(selected) for selected in selections):
+ return None
+
+ lookup = copy(query)
+ # A shared file may contain more rows than any individual query's Top-K.
+ lookup._limit = None
+ reader = lookup._configured_read_builder().new_read()
+ shared = {}
+ for key, (data, positions) in groups.items():
+ ordered = sorted(positions)
+ deletion = data.data_deletion_files[0] if data.data_deletion_files
else None
+ if deletion is not None:
+ dv = DeletionVector.read(table.file_io, deletion)
+ ordered = [position for position in ordered if not
dv.is_deleted(position)]
+ rows = reader.to_arrow([IndexedSplit(data, _ranges(ordered))])
+ # Compacted source files are key-sorted. DVs preserve that physical
+ # order; a tombstone or merge that removes additional rows prevents a
+ # reliable ordinal mapping and requires the individual lookup path.
+ if rows.num_rows != len(ordered):
+ return None
+ shared[key] = (rows, {position: index for index, position in
enumerate(ordered)})
+
+ empty = _take(next(iter(shared.values()))[0], [])
+ output = []
+ for selected in selections:
+ parts = []
+ for key, positions in selected:
+ rows, offsets = shared[key]
+ indices = [offsets[position] for position in sorted(positions) if
position in offsets]
+ parts.append(_take(rows, indices))
+ if not parts:
+ rows = empty
+ elif not empty.num_columns:
+ rows = _take(empty, range(sum(part.num_rows for part in parts)))
+ else:
+ rows = pa.concat_tables(parts)
+ if query._limit is not None:
+ rows = (_take(rows, range(min(query._limit, rows.num_rows)))
+ if not rows.num_columns else rows.slice(0, query._limit))
+ output.append(rows)
+ return output
diff --git a/paimon-python/pypaimon/multimodal/query.py
b/paimon-python/pypaimon/multimodal/query.py
index 28915fb0da..2e61feec05 100644
--- a/paimon-python/pypaimon/multimodal/query.py
+++ b/paimon-python/pypaimon/multimodal/query.py
@@ -623,10 +623,13 @@ class _PreFilterQuery(ScanQuery):
override_num_blocks=None):
"""Return search rows as a Ray Dataset, with BLOB descriptors.
- Search resolves candidates eagerly on one snapshot. Projected row data
- is fetched lazily by Ray workers on that same snapshot. Retain its
files
- until the Dataset has finished executing.
+ ``execution`` selects where candidate search runs. Projected rows are
+ always fetched lazily by Ray workers on the search snapshot. Retain
+ that snapshot's files until the Dataset has finished executing.
"""
+ if isinstance(self, _RayTextQuery) and not
self._table.options.data_evolution_enabled():
+ raise NotImplementedError("Ray Dataset output for text and hybrid
search requires a data-evolution table.")
+
from pypaimon.ray.search_result import read_search_result
from pypaimon.ray.search_execution import execution_options
@@ -947,7 +950,12 @@ class BatchVectorQuery(_PreFilterQuery):
def to_ray(self, *, execution="ray", concurrency=None,
ray_remote_args=None,
override_num_blocks=None):
- """Return one lazy Ray Dataset per query, with distributed row
lookup."""
+ """Return one lazy Ray Dataset per query, with distributed row lookup.
+
+ ``execution`` selects where candidate search runs. The Datasets share
+ that search snapshot and execute their lookups independently when
+ consumed. Retain its files until the Datasets have finished executing.
+ """
from pypaimon.ray.batch_vector_search import
_execute_batch_vector_search
from pypaimon.ray.search_result import read_search_result
from pypaimon.ray.search_execution import execution_options
@@ -971,6 +979,11 @@ class BatchVectorQuery(_PreFilterQuery):
from pypaimon.utils.roaring_bitmap import RoaringBitmap64
projection = self._effective_projection()
+ if len(results) > 1 and self._table.is_primary_key_table:
+ from pypaimon.multimodal.primary_key_batch_lookup import
read_primary_key_batch
+ shared = read_primary_key_batch(self, results)
+ if shared is not None:
+ return shared
if (len(results) <= 1 or any(isinstance(result,
GlobalIndexSplitResult) for result in results)
or self._metadata_only_result()
or (projection and not
self._configured_read_builder()._output_fields())):
diff --git a/paimon-python/pypaimon/ray/search_result.py
b/paimon-python/pypaimon/ray/search_result.py
index 12fe70501b..5e50456647 100644
--- a/paimon-python/pypaimon/ray/search_result.py
+++ b/paimon-python/pypaimon/ray/search_result.py
@@ -28,64 +28,79 @@ from pypaimon.table.special_fields import SpecialFields
def read_search_result(query, result, concurrency, remote_args,
override_num_blocks):
import ray
- query._require_row_id_scores()
lookup = copy(query)
lookup._table = query._table.copy({"blob-as-descriptor": "true"})
- projection = query._effective_projection()
- lookup._projection = (list(projection) if projection is not None
- else [field.name for field in query._table.fields])
- if not lookup._projection or len(set(lookup._projection)) !=
len(lookup._projection):
- raise ValueError("Ray search requires a nonempty projection with
unique column names.")
- row_id = SpecialFields.ROW_ID.name
- added_row_id = row_id not in lookup._projection
- if added_row_id:
- lookup._projection.append(row_id)
lookup._limit = None # Candidates already contain the global top-k.
- builder = lookup._configured_read_builder()
- reader = builder.new_read()
- if query._metadata_only_result():
- dataset = ray.data.from_arrow(pa.table({row_id:
pa.array(list(result.results()), type=pa.int64())}))
- else:
+
+ if query._table.is_primary_key_table:
+ # PK splits already select physical positions and carry deletion files.
+ builder = lookup._configured_read_builder()
+ _validate_projection([field.name for field in
builder._output_fields()])
splits =
builder.new_scan().with_global_index_result(result).plan().splits()
- dataset = reader.to_ray(
+ dataset = builder.new_read().to_ray(
splits, concurrency=concurrency, ray_remote_args=remote_args,
override_num_blocks=override_num_blocks)
+ else:
+ query._require_row_id_scores()
+ row_id = SpecialFields.ROW_ID.name
+ projection = query._effective_projection()
+ lookup._projection = (list(projection) if projection is not None
+ else [field.name for field in
query._table.fields])
+ _validate_projection(lookup._projection)
+ added_row_id = row_id not in lookup._projection
+ if added_row_id:
+ lookup._projection.append(row_id)
+ builder = lookup._configured_read_builder()
+ reader = builder.new_read()
+ if query._metadata_only_result():
+ dataset = ray.data.from_arrow(pa.table({row_id:
pa.array(list(result.results()), type=pa.int64())}))
+ else:
+ splits =
builder.new_scan().with_global_index_result(result).plan().splits()
+ dataset = reader.to_ray(
+ splits, concurrency=concurrency, ray_remote_args=remote_args,
+ override_num_blocks=override_num_blocks)
+
+ # Only compact candidate metadata crosses the driver. Payloads remain
in
+ # worker blocks, including during score attachment and global ordering.
+ rank_column = "_paimon_search_rank_" + uuid.uuid4().hex
+ finish = copy(query)
+ finish._sort_by_score = False
+ sort_by_score = query._sort_by_score
+ score_getter = (result.score_getter()
+ if sort_by_score and not result.results().is_empty()
else None)
- # Only compact candidate metadata crosses the driver. Payloads remain in
- # worker blocks, including during score attachment and global ordering.
- rank_column = "_paimon_search_rank_" + uuid.uuid4().hex
- finish = copy(query)
- finish._sort_by_score = False
- sort_by_score = query._sort_by_score
- score_getter = (result.score_getter()
- if sort_by_score and not result.results().is_empty() else
None)
+ def finish_batch(batch):
+ output = finish._finish_search_result(batch, result, False)
+ if sort_by_score:
+ output = output.append_column(rank_column, pa.array(
+ [-score_getter(value) for value in
batch[row_id].to_pylist()], type=pa.float64()))
+ return output
- def finish_batch(batch):
- output = finish._finish_search_result(batch, result, False)
+ empty = reader._output_arrow_schema().empty_table()
+ dataset = dataset.map_batches(finish_batch, batch_format="pyarrow")
+ empty = finish_batch(empty)
if sort_by_score:
- output = output.append_column(rank_column, pa.array(
- [-score_getter(value) for value in batch[row_id].to_pylist()],
type=pa.float64()))
- return output
+ dataset = dataset.sort([rank_column,
row_id]).drop_columns([rank_column])
+ empty = empty.drop_columns([rank_column])
+ if added_row_id:
+ dataset = dataset.drop_columns([row_id])
+ empty = empty.drop_columns([row_id])
+ # Sort/map may discard every empty block. Restore the final typed
schema.
+ dataset = dataset.union(ray.data.from_arrow(empty))
+ if sort_by_score:
+ # Projection tasks after Sort can finish out of order. Preserve the
+ # sorted block order through the whole returned Dataset, without
+ # changing the process-wide DataContext or unrelated Datasets.
+ dataset.context.execution_options.preserve_order = True
- empty = reader._output_arrow_schema().empty_table()
- dataset = dataset.map_batches(finish_batch, batch_format="pyarrow")
- empty = finish_batch(empty)
- if query._sort_by_score:
- dataset = dataset.sort([rank_column,
row_id]).drop_columns([rank_column])
- empty = empty.drop_columns([rank_column])
- if added_row_id:
- dataset = dataset.drop_columns([row_id])
- empty = empty.drop_columns([row_id])
- # Sort/map may discard every empty block. Restore the final typed schema.
- dataset = dataset.union(ray.data.from_arrow(empty))
- if sort_by_score:
- # Projection tasks after Sort can finish out of order. Preserve the
- # sorted block order through the whole returned Dataset, without
- # changing the process-wide DataContext or unrelated Datasets.
- dataset.context.execution_options.preserve_order = True
setattr(dataset, "_paimon_blob_file_io", lookup._table.file_io)
setattr(dataset, "_paimon_blob_columns", query._readable_blob_columns())
maps, arrays = query._nested_blob_columns()
setattr(dataset, "_paimon_map_blob_columns", maps)
setattr(dataset, "_paimon_array_blob_columns", arrays)
return dataset
+
+
+def _validate_projection(names):
+ if not names or len(set(names)) != len(names):
+ raise ValueError("Ray search requires a nonempty projection with
unique column names.")
diff --git a/paimon-python/pypaimon/tests/pk_search_capabilities_test.py
b/paimon-python/pypaimon/tests/pk_search_capabilities_test.py
index a7cd619b47..c697a143f3 100644
--- a/paimon-python/pypaimon/tests/pk_search_capabilities_test.py
+++ b/paimon-python/pypaimon/tests/pk_search_capabilities_test.py
@@ -21,32 +21,32 @@ from types import SimpleNamespace
import pytest
from pypaimon.catalog.catalog_factory import CatalogFactory
-from pypaimon.multimodal.query import BatchVectorQuery, VectorQuery
-from pypaimon.table.source.primary_key_scored_result import
PrimaryKeyScoredResult
+from pypaimon.multimodal.query import BatchVectorQuery, HybridQuery,
TextQuery, VectorQuery
from pypaimon.tests.primary_key_global_index_golden_test import GOLDEN_ARCHIVE
-def _query(query_type):
- table = SimpleNamespace(
- fields=[], options=SimpleNamespace(data_evolution_enabled=lambda:
False))
- vectors = [[1., 0.]] if query_type is BatchVectorQuery else [1., 0.]
- return query_type(table, vectors, "embedding")
[email protected]
+def pk_table_stub():
+ return SimpleNamespace(
+ fields=[], is_primary_key_table=True,
+ options=SimpleNamespace(data_evolution_enabled=lambda: False))
[email protected]("query_type", [VectorQuery, BatchVectorQuery])
-def test_pk_ray_dataset_conversion_requires_row_id_results(query_type):
- pytest.importorskip("ray")
- from pypaimon.ray.search_result import read_search_result
-
- query = _query(query_type)
- with pytest.raises(NotImplementedError, match="require a data-evolution
table"):
- read_search_result(query, PrimaryKeyScoredResult(0, [], []), 1, {},
None)
[email protected]("query_type,kwargs", [
+ (TextQuery, {"text_query": {"column": "text", "query": "search term"}}),
+ (HybridQuery, {}),
+])
+def test_pk_text_and_hybrid_ray_dataset_require_data_evolution(pk_table_stub,
query_type, kwargs):
+ query = query_type(pk_table_stub, **kwargs)
+ with pytest.raises(NotImplementedError, match="requires a data-evolution
table"):
+ query.to_ray(execution="local")
@pytest.mark.parametrize("query_type", [VectorQuery, BatchVectorQuery])
@pytest.mark.parametrize("method", ["with_score", "order_by_score"])
-def test_pk_score_outputs_rejected_when_configuring_query(query_type, method):
- query = _query(query_type)
+def test_pk_score_outputs_rejected_when_configuring_query(pk_table_stub,
query_type, method):
+ vectors = [[1., 0.]] if query_type is BatchVectorQuery else [1., 0.]
+ query = query_type(pk_table_stub, vectors, "embedding")
with pytest.raises(NotImplementedError, match="Search score output and
ordering require a data-evolution"):
getattr(query, method)()
diff --git a/paimon-python/pypaimon/tests/primary_key_batch_lookup_test.py
b/paimon-python/pypaimon/tests/primary_key_batch_lookup_test.py
new file mode 100644
index 0000000000..f087cef016
--- /dev/null
+++ b/paimon-python/pypaimon/tests/primary_key_batch_lookup_test.py
@@ -0,0 +1,228 @@
+# 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 copy
+from pathlib import Path
+import tarfile
+from unittest.mock import patch
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+import pytest
+
+from pypaimon.catalog.catalog_factory import CatalogFactory
+from pypaimon.execution.python.read.split_read import SplitRead
+from pypaimon.multimodal.query import BatchVectorQuery
+from pypaimon.table.source.primary_key_scored_result import (
+ PrimaryKeyScoredResult, PrimaryKeySearchPosition, _partition_bytes,
+)
+from pypaimon.tests.primary_key_global_index_golden_test import GOLDEN_ARCHIVE
+
+
[email protected](params=[1, 3])
+def table(tmp_path, request):
+ with tarfile.open(GOLDEN_ARCHIVE, "r:gz") as archive:
+ archive.extractall(tmp_path)
+ return CatalogFactory.create({"warehouse": str(tmp_path)}).get_table(
+ "default.test_pk_vector_golden").copy({
+ "read.native.enabled": "false", "scan.native-plan.enabled":
"false",
+ "read.parallelism": str(request.param), "read.batch-size": "2",
+ })
+
+
+def source_plan(table):
+ return (table.new_vector_search_builder().with_vector_column("embedding")
+ .with_query_vector([1., 0., 0., 0.]).with_limit(3)
+ .new_vector_search_scan().scan())
+
+
+def result(snapshot_id, source, positions, score=1.0):
+ file = source.files[0]
+ return PrimaryKeyScoredResult(snapshot_id, [source], [
+ PrimaryKeySearchPosition(
+ _partition_bytes(source.partition), source.bucket, file.file_name,
+ position, score - ordinal * 0.1)
+ for ordinal, position in enumerate(positions)
+ ])
+
+
+def query(table, count=4, projection=None, limit=2):
+ execution = BatchVectorQuery(table, [[1., 0., 0., 0.]] * count,
"embedding")
+ if projection is not None:
+ execution.select(projection)
+ return execution.limit(limit)._for_execution()
+
+
+def lookup_reads(query, results):
+ original = SplitRead.file_reader_supplier
+ opened = []
+
+ def read(split_read, file, *args, **kwargs):
+ opened.append((file.file_path, tuple(
+ (r.from_, r.to) for r in split_read.row_ranges)))
+ return original(split_read, file, *args, **kwargs)
+
+ with patch.object(SplitRead, "file_reader_supplier", read):
+ actual = query._read_batch_results(results)
+ return actual, opened
+
+
[email protected]("projection", [
+ None, [], ["id"], ["id", "id"], ["embedding"], ["embedding", "id"],
+])
+def test_overlapping_queries_read_each_file_once(table, projection):
+ plan = source_plan(table)
+ source = plan.splits()[0].data_split
+ results = [result(plan.snapshot_id, source, rows, score)
+ for rows, score in [([0, 2], 1.0), ([1, 2], 5.0), ([], 1.0),
([0, 2], 9.0)]]
+ execution = query(table, projection=projection)
+ expected = [execution._read_global_index_result(r) for r in results]
+ positions = [r.positions for r in results]
+ actual, opened = lookup_reads(execution, results)
+ assert [t.to_pylist() for t in actual] == [t.to_pylist() for t in expected]
+ assert [t.schema for t in actual] == [t.schema for t in expected]
+ assert [t.num_rows for t in actual] == [2, 2, 0, 2]
+ assert [r.positions for r in results] == positions
+ assert len(opened) == 1
+ assert opened[0][1] == ((0, 2),)
+
+
[email protected]("table", [3], indirect=True)
+def test_disjoint_queries_keep_multi_file_lookup(table, tmp_path):
+ from shutil import copyfile
+ from pypaimon.read.table_read import TableRead
+
+ plan = source_plan(table)
+ source = plan.splits()[0].data_split
+ sources = [source]
+ for bucket in range(1, 4):
+ split = copy.deepcopy(source)
+ split._bucket = bucket
+ file = split.files[0]
+ path = tmp_path / ("bucket-%s" % bucket) / file.file_name
+ path.parent.mkdir()
+ copyfile(file.file_path, path)
+ file.file_path = str(path)
+ sources.append(split)
+
+ results = []
+ for pair in (sources[:2], sources[2:]):
+ positions = [result(plan.snapshot_id, split, [position]).positions[0]
+ for position, split in enumerate(pair)]
+ results.append(PrimaryKeyScoredResult(plan.snapshot_id, pair,
positions))
+ execution = query(table, 2, ["id"])
+ expected = [execution._read_global_index_result(item) for item in results]
+ to_arrow = TableRead.to_arrow
+ split_counts = []
+
+ def read(reader, splits):
+ split_counts.append(len(splits))
+ return to_arrow(reader, splits)
+
+ with patch.object(TableRead, "to_arrow", read):
+ actual = execution._read_batch_results(results)
+
+ assert [item.to_pylist() for item in actual] == [item.to_pylist() for item
in expected]
+ assert split_counts == [2, 2]
+
+
+def test_post_filter_keeps_per_query_membership_and_limit(table):
+ plan = source_plan(table)
+ source = plan.splits()[0].data_split
+ results = [result(plan.snapshot_id, source, rows) for rows in ([0, 1], [2,
3], [0, 1])]
+ execution = query(table, 3, ["id"]).where("id >= 3")
+ expected = [execution._read_global_index_result(r) for r in results]
+ actual, _ = lookup_reads(execution, results)
+ assert [t.to_pylist() for t in actual] == [t.to_pylist() for t in expected]
+ assert [t.num_rows for t in actual] == [0, 2, 0]
+
+
+def test_shared_lookup_respects_deletion_positions(table, tmp_path):
+ from pypaimon.execution.python.deletionvectors.bitmap_deletion_vector
import BitmapDeletionVector
+ from pypaimon.table.source.deletion_file import DeletionFile
+
+ plan = source_plan(table)
+ source = copy.deepcopy(plan.splits()[0].data_split)
+ vector = BitmapDeletionVector()
+ vector.delete(1)
+ data = vector.serialize()
+ path = tmp_path / "deleted.dv"
+ path.write_bytes(data)
+ source.data_deletion_files = [DeletionFile(str(path), 0, len(data) - 8, 1)]
+ results = [result(plan.snapshot_id, source, rows) for rows in ([0, 1], [1,
2], [0, 2])]
+ execution = query(table, 3, ["id"])
+ expected = [execution._read_global_index_result(r) for r in results]
+ actual, opened = lookup_reads(execution, results)
+ assert [t.to_pylist() for t in actual] == [t.to_pylist() for t in expected]
+ assert [t.num_rows for t in actual] == [1, 1, 2]
+ assert len(opened) == 1
+
+
+def test_limit_is_applied_after_scattering_shared_rows(table):
+ plan = source_plan(table)
+ source = plan.splits()[0].data_split
+ results = [result(plan.snapshot_id, source, rows) for rows in ([0, 1], [2,
3])]
+ execution = query(table, 2, ["id"], limit=1)
+ expected = [execution._read_global_index_result(r) for r in results]
+ actual, opened = lookup_reads(execution, results)
+ assert [t.to_pylist() for t in actual] == [t.to_pylist() for t in expected]
+ assert actual[0].to_pylist() == [{"id": 1}]
+ assert actual[1].to_pylist() == [{"id": 3}]
+ assert len(opened) == 1
+
+
+def test_all_empty_results_preserve_schema(table):
+ plan = source_plan(table)
+ source = plan.splits()[0].data_split
+ execution = query(table, 3, ["embedding", "id"])
+ results = [result(plan.snapshot_id, source, []) for _ in range(3)]
+ expected = execution._read_global_index_result(results[0])
+ actual, opened = lookup_reads(execution, results)
+ assert len(actual) == 3
+ assert all(t.equals(expected) for t in actual)
+ assert not opened
+
+
[email protected]("projection", [["id"], []])
+def test_same_file_name_in_different_buckets_has_distinct_rows(table,
projection):
+ plan = source_plan(table)
+ left = plan.splits()[0].data_split
+ right = copy.deepcopy(left)
+ right._bucket = 1
+ file = right.files[0]
+ path = Path(file.file_path).parent.parent / "bucket-1" / file.file_name
+ path.parent.mkdir()
+ physical = pq.read_table(file.file_path)
+ pq.write_table(pa.Table.from_pylist([
+ dict(row, _KEY_id=row["_KEY_id"] + 100, id=row["id"] + 100)
+ for row in physical.to_pylist()
+ ], schema=physical.schema), path)
+ file.file_path = str(path)
+ first = result(plan.snapshot_id, left, [0, 2])
+ second = result(plan.snapshot_id, right, [0])
+ both = PrimaryKeyScoredResult(
+ plan.snapshot_id, [left, right], first.positions + second.positions)
+ results = [both, result(plan.snapshot_id, right, [0, 3]), first]
+ execution = query(table, 3, projection, limit=3)
+ expected = [execution._read_global_index_result(r) for r in results]
+ actual, opened = lookup_reads(execution, results)
+ assert [t.to_pylist() for t in actual] == [t.to_pylist() for t in expected]
+ assert [t.num_rows for t in actual] == [3, 2, 2]
+ if projection:
+ assert actual[0].column("id").to_pylist() == [1, 3, 101]
+ assert len(opened) == 2
+ assert {path for path, _ in opened} == {left.files[0].file_path,
file.file_path}
diff --git a/paimon-python/pypaimon/tests/ray_primary_key_vector_search_test.py
b/paimon-python/pypaimon/tests/ray_primary_key_vector_search_test.py
index 67306bafcd..b327a1dc9e 100644
--- a/paimon-python/pypaimon/tests/ray_primary_key_vector_search_test.py
+++ b/paimon-python/pypaimon/tests/ray_primary_key_vector_search_test.py
@@ -656,11 +656,50 @@ def
test_batch_physical_lookup_preserves_projections(table, ray_cluster, project
assert all(result.equals(local) for result, local in zip(actual, expected))
-def test_batch_ray_dataset_output_remains_unsupported(table, ray_cluster):
- from pypaimon.multimodal.query import BatchVectorQuery
[email protected]("execution", ["local", "ray"])
[email protected]("batch", [False, True])
[email protected]("where,pre_filter", [("id >= 2", None), ("id = 999",
None), (None, "id = 999")])
+def test_ray_dataset_matches_arrow_lookup(table, ray_cluster, execution,
batch, where, pre_filter):
+ pytest.importorskip("paimon_vindex")
+ from pypaimon.multimodal.table import MultimodalTable
- with pytest.raises(NotImplementedError, match="data-evolution"):
- BatchVectorQuery(table, QUERIES, "embedding").to_ray(execution="local")
+ view = MultimodalTable(None, table.identifier.get_full_name(), table)
+ query = (view.search_vectors(QUERIES, pre_filter=pre_filter) if batch else
+ view.search(QUERIES[0], pre_filter=pre_filter))
+ # The filter column is deliberately absent from the requested projection.
+ query = query.select(["embedding"]).where(where).limit(3)
+ expected = query.to_arrow()
+ actual = query.to_ray(execution=execution, concurrency=2,
override_num_blocks=2)
+ datasets, tables = (actual, expected) if batch else ([actual], [expected])
+ assert len(datasets) == len(tables)
+ for dataset, rows in zip(datasets, tables):
+ assert sorted(row["embedding"] for row in dataset.take_all()) ==
sorted(
+ rows.column("embedding").to_pylist())
+ assert dataset.schema().names == ["embedding"]
+
+
+def test_ray_dataset_defers_pk_lookup_to_workers(table, ray_cluster, tmp_path):
+ pytest.importorskip("paimon_vindex")
+ from pypaimon.filesystem.local_file_io import LocalFileIO
+
+ marker = tmp_path / "lookup-pids"
+
+ class ReportingFileIO(LocalFileIO):
+ def to_filesystem_path(self, path):
+ if path.endswith(".parquet"):
+ with marker.open("a") as output:
+ output.write(f"{os.getpid()}\n")
+ return super().to_filesystem_path(path)
+
+ query = VectorQuery(table, QUERIES[0], "embedding").select(["id"]).limit(3)
+ expected = query.to_list()
+ with patch.object(table, "file_io", ReportingFileIO()):
+ dataset = query.to_ray(execution="local", override_num_blocks=2)
+ assert not marker.exists()
+ assert sorted(row["id"] for row in dataset.take_all()) ==
sorted(row["id"] for row in expected)
+ worker_pids = {int(pid) for pid in marker.read_text().splitlines()}
+ assert worker_pids
+ assert os.getpid() not in worker_pids
def test_batch_split_only_read_requires_captured_snapshot(table):