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 7b0e075510 [python] Stream raw vector batches for local single-query
search (#11254)
7b0e075510 is described below
commit 7b0e0755101aa8b9ffcfcdb3af1cba28cdd83ee4
Author: zhigang <[email protected]>
AuthorDate: Thu Nov 19 15:41:32 2026 +0800
[python] Stream raw vector batches for local single-query search (#11254)
---
docs/docs/pypaimon/multimodal-search.md | 6 +
.../read/search/distributed_vector_search.py | 12 +-
.../python/read/search/vector_search_read.py | 165 ++++++++++---
.../pypaimon/globalindex/vector_search_result.py | 13 +-
paimon-python/pypaimon/multimodal/query.py | 7 +-
.../pypaimon/tests/ray_vector_search_test.py | 25 ++
.../pypaimon/tests/vector_scoring_test.py | 19 +-
.../pypaimon/tests/vector_search_filter_test.py | 18 +-
.../pypaimon/tests/vector_search_streaming_test.py | 259 +++++++++++++++++++++
9 files changed, 479 insertions(+), 45 deletions(-)
diff --git a/docs/docs/pypaimon/multimodal-search.md
b/docs/docs/pypaimon/multimodal-search.md
index ce6afb7973..d5f0f52394 100644
--- a/docs/docs/pypaimon/multimodal-search.md
+++ b/docs/docs/pypaimon/multimodal-search.md
@@ -165,6 +165,12 @@ column and `order_by_score()` to sort by descending score,
with ascending
the existing result order, and `order_by_score()` does not require projecting
scores. Without either method, result behavior is unchanged.
+For local single-vector searches on data-evolution tables with the Python read
+backend, NaN scores rank after all numeric scores. A NaN row can appear in the
+top K only when fewer than K candidates have numeric scores. Ties, including
+ties between NaNs, favor the smaller row ID. Returned NaN scores retain their
+original value.
+
```python
neighbors = (
docs.search([0.1, 0.2, 0.3], column="embedding")
diff --git
a/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py
b/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py
index 78ac0462cc..4ffc774511 100644
---
a/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py
+++
b/paimon-python/pypaimon/execution/python/read/search/distributed_vector_search.py
@@ -17,15 +17,16 @@
"""Python search tasks and global result coordination for distributed
executors."""
-from collections import Counter
import math
+from collections import Counter
+from itertools import chain
from pypaimon.globalindex.batch_vector_search import BatchVectorSearch
from pypaimon.globalindex.global_index_result import GlobalIndexResult
from pypaimon.globalindex.vector_search_result import
DictBasedScoredIndexResult
from pypaimon.execution.python.read.search.vector_search_read import (
BatchVectorSearchReadImpl, DataEvolutionVectorRead,
- _filtered_raw_row_ranges, _offer_score, _scored_result,
_split_search_splits,
+ _filtered_raw_row_ranges, _offer_score, _scored_result,
_split_search_splits, _top_vector_scores,
)
from pypaimon.execution.python.read.search import global_index_live_row_filter
from pypaimon.execution.python.read.search.distributed_search import
closing_task_results
@@ -77,15 +78,12 @@ class DistributedVectorSearchRead(DataEvolutionVectorRead):
table_read, splits = self._plan_raw_read(ranges, include_filter,
snapshot)
context = (table_read, self._vector_column, query_vector,
self._limit, self._search_metric(index_type))
- heap = []
# Keep each planned data split intact: its files may be vertical column
# groups that must be read together to reconstruct a logical row.
work = [SearchTask(_search_raw_split, context, split) for split in
splits]
with closing_task_results(self._executor.map(work)) as tasks:
- for _, scores in tasks:
- for row_id, score in scores.items():
- _offer_score(heap, self._limit, row_id, score)
- return _scored_result(heap)
+ rows = chain.from_iterable(scores.items() for _, scores in tasks)
+ return _top_vector_scores(rows, self._limit)
class DistributedBatchVectorSearchRead(BatchVectorSearchReadImpl):
diff --git
a/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py
b/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py
index 7a48fa7970..7b54aaa966 100644
--- a/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py
+++ b/paimon-python/pypaimon/execution/python/read/search/vector_search_read.py
@@ -16,14 +16,18 @@
# under the License.
-from pypaimon.table.source.search_types import (VectorSearchRead,
BatchVectorSearchRead)
"""Vector search read to read index files."""
import logging
+import math
from collections import deque
-from concurrent.futures import ThreadPoolExecutor
-from contextlib import closing
+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
+from contextlib import ExitStack, closing
+from heapq import nsmallest
from threading import Lock
+from typing import (
+ TYPE_CHECKING, Callable, Container, Dict, Generator, Iterable, Iterator,
List, Optional, Sequence, Tuple,
+)
from pypaimon.common.options.core_options import CoreOptions
from pypaimon.common.options.options import Options
@@ -33,7 +37,8 @@ from pypaimon.globalindex.global_index_meta import
GlobalIndexIOMeta
from pypaimon.globalindex.global_index_result import GlobalIndexResult
from pypaimon.execution.python.globalindex.offset_global_index_reader import
OffsetGlobalIndexReader
from pypaimon.globalindex.vector_search import VectorSearch
-from pypaimon.globalindex.vector_search_result import
DictBasedScoredIndexResult
+from pypaimon.globalindex.vector_search_result import
DictBasedScoredIndexResult, vector_score_order
+from pypaimon.table.source.search_types import BatchVectorSearchRead,
VectorSearchRead
from pypaimon.table.special_fields import SpecialFields
from pypaimon.table.source.vector_search_split import (
IndexVectorSearchSplit,
@@ -44,6 +49,18 @@ from pypaimon.utils.range import Range
from pypaimon.utils.roaring_bitmap import RoaringBitmap64
+if TYPE_CHECKING:
+ from concurrent.futures import Future
+
+ import pyarrow as pa
+
+ from pypaimon.read.read_support import _ClosableArrowBatchReader
+ from pypaimon.read.split import Split
+ from pypaimon.read.table_read import TableRead
+
+ _BatchStream = Generator[pa.RecordBatch, None, None]
+
+
class AbstractVectorSearchReadImpl:
"""Base implementation for vector search reads."""
@@ -356,37 +373,51 @@ class AbstractVectorSearchReadImpl:
if not raw_row_ranges:
return DictBasedScoredIndexResult({})
- table = self._read_raw_arrow(raw_row_ranges, include_filter, snapshot)
- if table is None or table.num_rows == 0:
- return DictBasedScoredIndexResult({})
+ table_read: "TableRead"
+ splits: "List[Split]"
+ table_read, splits = self._plan_raw_read(raw_row_ranges,
include_filter, snapshot)
+ metric = self._search_metric(index_type)
+ workers = min(len(splits), table_read._resolve_parallelism(None,
len(splits)))
+ if workers <= 1:
+ source = _open_raw_batch_reader(table_read, splits)
+ else:
+ source = closing(_parallel_raw_batches(table_read, splits,
workers))
- return self._score_raw_batches(
- table.to_batches(max_chunksize=_score_block_size(query_vector)),
- query_vector, self._search_metric(index_type), score_candidates)
+ with source as batches:
+ return self._score_raw_batches(batches, query_vector, metric,
score_candidates)
def _score_raw_batches(self, batches, query_vector, metric,
score_candidates=None, reject_nan=False):
"""Score bounded Arrow batches, shared by local and distributed
reads."""
- import math
-
- top_k_heap = []
- for block in batches:
+ scores = self._iter_raw_scores(batches, query_vector, metric,
score_candidates, reject_nan)
+ return _top_vector_scores(scores, self._limit)
+
+ def _iter_raw_scores(
+ self, batches: "Iterable[pa.RecordBatch]", query_vector:
Sequence[float], metric: str,
+ score_candidates: Optional[Container[int]], reject_nan: bool,
+ ) -> Iterator[Tuple[int, float]]:
+ # Bound the Arrow take as well as the scoring matrix for wide vectors.
+ blocks = batches if score_candidates is None else
_slice_batches(batches, _score_block_size(query_vector))
+ for block in blocks:
row_ids = block.column(SpecialFields.ROW_ID.name).to_pylist()
- vectors = block.column(self._vector_column.name)
if score_candidates is not None:
positions = [i for i, row_id in enumerate(row_ids)
if row_id in score_candidates]
if not positions:
+ del block, row_ids
continue
- vectors = vectors.take(positions)
+ vectors =
block.column(self._vector_column.name).take(positions)
row_ids = [row_ids[i] for i in positions]
+ else:
+ vectors = block.column(self._vector_column.name)
for row_id, score in zip(
row_ids, _iter_arrow_scores(vectors, query_vector, metric)
):
- if score is not None:
- if reject_nan and math.isnan(score):
- raise ValueError("Ray vector search cannot rank NaN
scores.")
- _offer_score(top_k_heap, self._limit, row_id, score)
- return _scored_result(top_k_heap)
+ if score is None:
+ continue
+ if reject_nan and math.isnan(score):
+ raise ValueError("Ray vector search cannot rank NaN
scores.")
+ yield row_id, score
+ del block, row_ids, vectors
def _read_raw_vectors(self, candidates, include_filter=True,
snapshot=None):
return self._read_raw_candidate_vectors(
@@ -707,11 +738,11 @@ class
DataEvolutionVectorRead(AbstractVectorSearchReadImpl, VectorSearchRead):
if not index_splits and not raw_splits:
return GlobalIndexResult.create_empty()
- indexed = (
- DictBasedScoredIndexResult({})
- if not index_splits
- else self._read_indexed(index_splits, self._query_vector, snapshot)
- )
+ indexed = None
+ if index_splits:
+ indexed = self._read_indexed(index_splits, self._query_vector,
snapshot)
+ if not raw_splits:
+ return indexed
raw_result = self._read_raw_search(
_raw_row_ranges(raw_splits),
self._raw_pre_filter(raw_splits, snapshot),
@@ -719,7 +750,12 @@ class
DataEvolutionVectorRead(AbstractVectorSearchReadImpl, VectorSearchRead):
_raw_search_index_type(raw_splits),
snapshot=snapshot,
)
- return indexed.or_(raw_result).top_k(self._limit)
+ if indexed is None:
+ return raw_result
+ merged_scores = {}
+ _merge_index_scores(merged_scores, indexed)
+ _merge_index_scores(merged_scores, raw_result)
+ return _top_vector_scores(merged_scores.items(), self._limit)
def _read_indexed(self, splits, query_vector, snapshot):
index_type = _vector_index_type(splits)
@@ -731,7 +767,7 @@ class DataEvolutionVectorRead(AbstractVectorSearchReadImpl,
VectorSearchRead):
_merge_index_scores(merged_scores, split_result)
del split_result
- indexed = DictBasedScoredIndexResult(merged_scores).top_k(search_limit)
+ indexed = _top_vector_scores(merged_scores.items(), search_limit)
return self._maybe_rerank_indexed_result(
indexed, index_type, query_vector, snapshot)
@@ -848,6 +884,72 @@ class
BatchVectorSearchReadImpl(AbstractVectorSearchReadImpl,
return [_scored_result(heap) for heap in heaps]
+def _open_raw_batch_reader(table_read: "TableRead", splits: "List[Split]") ->
"_ClosableArrowBatchReader":
+ from pypaimon.read.read_support import _ClosableArrowBatchReader
+
+ reader, source = table_read._new_arrow_batch_reader(splits)
+ return _ClosableArrowBatchReader(reader, source)
+
+
+def _parallel_raw_batches(
+ table_read: "TableRead", splits: "List[Split]", workers: int,
+) -> "_BatchStream":
+ """Yield ready batches, with at most one outstanding read per split
group."""
+ # Readers may be suspended after yielding. Join all in-flight reads
+ # before closing their iterators, including when scoring fails.
+ with ExitStack() as streams, ThreadPoolExecutor(max_workers=workers) as
executor:
+ pending: "Dict[Future[Optional[pa.RecordBatch]],
Iterator[pa.RecordBatch]]" = {}
+ try:
+ for i in range(workers):
+ group = splits[i::workers]
+ batches = _open_prefetched_batches(table_read, group, streams)
+ pending[executor.submit(next, batches, None)] = batches
+ while pending:
+ completed = wait(pending, return_when=FIRST_COMPLETED).done
+ while completed:
+ future = completed.pop()
+ batches = pending.pop(future)
+ batch = future.result()
+ if batch is None:
+ continue
+ yield batch
+ # Keep completed batches bounded, and let ready
+ # readers progress while another reader is slow.
+ del batch, future
+ pending[executor.submit(next, batches, None)] = batches
+ finally:
+ for future in pending:
+ future.cancel()
+
+
+def _open_prefetched_batches(
+ table_read: "TableRead", splits: "List[Split]", streams: ExitStack,
+) -> "_BatchStream":
+ """Open on the caller thread and register cleanup before submitting the
first read."""
+ reader_scope = streams.enter_context(ExitStack())
+ reader = reader_scope.enter_context(_open_raw_batch_reader(table_read,
splits))
+ batches = _read_one_batch_ahead(reader, reader_scope.close)
+ return streams.enter_context(closing(batches))
+
+
+def _read_one_batch_ahead(reader: "Iterator[pa.RecordBatch]", close_reader:
Callable[[], None]) -> "_BatchStream":
+ """Read one batch ahead so the last batch can be scored with its reader
already closed."""
+ current = next(reader, None)
+ if current is None:
+ close_reader()
+ return
+ for following in reader:
+ yield current
+ current = following
+ close_reader()
+ yield current
+
+
+def _top_vector_scores(scores: Iterable[Tuple[int, float]], limit: int) ->
DictBasedScoredIndexResult:
+ best = nsmallest(limit, scores, key=vector_score_order)
+ return DictBasedScoredIndexResult(dict(best))
+
+
def _merge_index_scores(merged_scores, result):
if result is None:
return
@@ -1052,6 +1154,13 @@ def _normalize_metric(metric):
return str(metric).lower().replace("-", "_")
+def _slice_batches(batches: "Iterable[pa.RecordBatch]", size: int) ->
"Iterator[pa.RecordBatch]":
+ for batch in batches:
+ for start in range(0, batch.num_rows, size):
+ yield batch.slice(start, size)
+ del batch
+
+
def _score_block_size(query):
# Target 8 MiB per float64 matrix, allowing at least one vector.
return max(1, min(1024, (1 << 20) // max(1, len(query))))
diff --git a/paimon-python/pypaimon/globalindex/vector_search_result.py
b/paimon-python/pypaimon/globalindex/vector_search_result.py
index 74d76c5042..ae1ccc8281 100644
--- a/paimon-python/pypaimon/globalindex/vector_search_result.py
+++ b/paimon-python/pypaimon/globalindex/vector_search_result.py
@@ -17,8 +17,9 @@
"""Vector search global index result."""
+import math
from abc import abstractmethod
-from typing import Callable, Dict, Optional
+from typing import Callable, Dict, Optional, Tuple
from pypaimon.globalindex.global_index_result import GlobalIndexResult
from pypaimon.utils.roaring_bitmap import RoaringBitmap64
@@ -28,6 +29,16 @@ from pypaimon.utils.roaring_bitmap import RoaringBitmap64
ScoreGetter = Callable[[int], Optional[float]]
+def vector_score_order(row: Tuple[int, Optional[float]]) -> Tuple[bool, float,
int]:
+ """Best first: higher scores, then smaller row IDs. NaNs follow all
numbers."""
+ row_id, score = row
+ if score is None:
+ score = 0.0 # Same missing-score fallback as
ScoredGlobalIndexResult.top_k.
+ if math.isnan(score):
+ return True, 0.0, row_id
+ return False, -score, row_id
+
+
class ScoredGlobalIndexResult(GlobalIndexResult):
"""
Vector search global index result for vector index.
diff --git a/paimon-python/pypaimon/multimodal/query.py
b/paimon-python/pypaimon/multimodal/query.py
index 2e61feec05..2dfba91954 100644
--- a/paimon-python/pypaimon/multimodal/query.py
+++ b/paimon-python/pypaimon/multimodal/query.py
@@ -597,7 +597,12 @@ class _PreFilterQuery(ScanQuery):
raise ValueError("Score column name conflicts with a
projected column: %s" % self._score_column)
table = table.append_column(self._score_column,
pa.array(scores, type=pa.float64()))
if self._sort_by_score:
- order = sorted(range(len(row_ids)), key=lambda i: (-scores[i],
row_ids[i]))
+ if isinstance(self, VectorQuery):
+ from pypaimon.globalindex.vector_search_result import
vector_score_order
+
+ order = sorted(range(len(row_ids)), key=lambda i:
vector_score_order((row_ids[i], scores[i])))
+ else:
+ order = sorted(range(len(row_ids)), key=lambda i:
(-scores[i], row_ids[i]))
table = table.take(pa.array(order, type=pa.int64()))
if added_row_id:
table = table.select([i for i, name in
enumerate(table.column_names) if name != SpecialFields.ROW_ID.name])
diff --git a/paimon-python/pypaimon/tests/ray_vector_search_test.py
b/paimon-python/pypaimon/tests/ray_vector_search_test.py
index f40ce3bcd0..902949881c 100644
--- a/paimon-python/pypaimon/tests/ray_vector_search_test.py
+++ b/paimon-python/pypaimon/tests/ray_vector_search_test.py
@@ -421,6 +421,31 @@ def test_nan_scores_fail_before_worker_top_k(table,
ray_cluster):
table.search([1., 1.]).limit(1).to_arrow(execution="ray")
[email protected]("first_value", [float("nan"), 1.0], ids=["nan",
"tie"])
+def test_single_vector_top_k_in_either_split_order(table, ray_cluster,
first_value):
+ add_rows(table, [[first_value, 1.]])
+ add_rows(table, [[1., 1.]], start=1)
+ query = table.search([1., 1.]).select(["id"]).limit(1)
+ original = RaySearchTaskExecutor.map
+
+ def run(reverse):
+ def dispatch(executor, tasks, ordered=False):
+ assert len(tasks) == 2
+ # One real worker task at a time fixes the completion order.
+ tasks = sorted(tasks, key=lambda task:
task.item.files[0].first_row_id, reverse=reverse)
+ yield from original(executor, tasks, ordered=ordered)
+
+ with patch.object(RaySearchTaskExecutor, "map", dispatch):
+ return query.to_arrow(execution="ray", concurrency=1)
+
+ for reverse in (False, True):
+ if np.isnan(first_value):
+ with pytest.raises(ValueError, match="cannot rank NaN"):
+ run(reverse)
+ else:
+ assert ids(run(reverse)) == [0]
+
+
@pytest.mark.parametrize("ordered", [False, True])
@pytest.mark.parametrize("early_close", [False, True])
def test_slow_first_task_bounds_completed_results(ordered, early_close):
diff --git a/paimon-python/pypaimon/tests/vector_scoring_test.py
b/paimon-python/pypaimon/tests/vector_scoring_test.py
index e293f68424..0c091d642f 100644
--- a/paimon-python/pypaimon/tests/vector_scoring_test.py
+++ b/paimon-python/pypaimon/tests/vector_scoring_test.py
@@ -16,6 +16,7 @@
# under the License.
import unittest
+from typing import Iterator, List, Tuple
from unittest import mock
import numpy as np
@@ -30,6 +31,7 @@ from pypaimon.execution.python.read.search.vector_search_read
import (
_score_block_size,
_score_rows,
)
+from pypaimon.read.split import Split
from pypaimon.table.special_fields import SpecialFields
from pypaimon.tests.vector_search_filter_test import _StubTable, _field
from pypaimon.utils.range import Range
@@ -174,13 +176,20 @@ class VectorScoringTest(unittest.TestCase):
candidates = RoaringBitmap64()
for row_id in (1, 2, 3):
candidates.add(row_id)
- with mock.patch.object(reader, "_read_raw_arrow", return_value=table):
+
+ def new_reader(_splits: List[Split]) ->
Tuple[pa.ipc.RecordBatchReader, Iterator[pa.RecordBatch]]:
+ batches = iter(table.to_batches(max_chunksize=2))
+ return pa.ipc.RecordBatchReader.from_batches(table.schema,
batches), batches
+
+ table_read = mock.Mock()
+ table_read._resolve_parallelism.return_value = 1
+ table_read._new_arrow_batch_reader.side_effect = new_reader
+ with mock.patch.object(reader, "_plan_raw_read",
return_value=(table_read, [])):
result = reader._read_raw_search([Range(0, 9)], None, [1, 0],
score_candidates=candidates)
- self.assertEqual([1, 3], result.results().to_list())
- reader._limit = 1
- with mock.patch.object(reader, "_read_raw_arrow", return_value=table):
+ self.assertEqual([1, 3], result.results().to_list())
+ reader._limit = 1
result = reader._read_raw_search([Range(0, 9)], None, [1, 0],
score_candidates=candidates)
- self.assertEqual([1], result.results().to_list())
+ self.assertEqual([1], result.results().to_list())
def test_refinement_and_block_memory_bound(self):
column = _field(1, "embedding", "FLOAT")
diff --git a/paimon-python/pypaimon/tests/vector_search_filter_test.py
b/paimon-python/pypaimon/tests/vector_search_filter_test.py
index 8089eba115..26024e16b5 100644
--- a/paimon-python/pypaimon/tests/vector_search_filter_test.py
+++ b/paimon-python/pypaimon/tests/vector_search_filter_test.py
@@ -27,13 +27,14 @@ import struct
import sys
import types
import unittest
-from typing import List
+from typing import Iterator, List, Optional, Tuple
from unittest import mock
from pypaimon.common.options.core_options import CoreOptions,
GlobalIndexSearchMode
from pypaimon.common.options.options import Options
from pypaimon.common.predicate import Predicate
from pypaimon.common.predicate_builder import PredicateBuilder
+from pypaimon.read.split import Split
from pypaimon.execution.python.globalindex.btree.btree_index_meta import
BTreeIndexMeta
from pypaimon.globalindex.global_index_meta import GlobalIndexIOMeta,
GlobalIndexMeta
from pypaimon.execution.python.globalindex.global_index_evaluator import
GlobalIndexEvaluation
@@ -219,7 +220,7 @@ def _install_raw_vector_read_builder(table,
vector_column_name, row_id_to_vector
def _new_arrow_batch_reader(self, splits):
table = self.to_arrow(splits)
batches = (batch for batch in table.to_batches(max_chunksize=2))
- return pa.RecordBatchReader.from_batches(table.schema, batches),
batches
+ return pa.ipc.RecordBatchReader.from_batches(table.schema,
batches), batches
class _Builder:
def with_partition_filter(self, predicate):
@@ -2924,7 +2925,7 @@ class VectorSearchManySplitsTest(unittest.TestCase):
class _FakeReader:
def visit_vector_search(self_inner, vs):
return _completed_future(
- DictBasedScoredIndexResult({1: 0.1}))
+ DictBasedScoredIndexResult({0: float("nan"), 1:
float("-inf")}))
def close(self_inner):
pass
@@ -2952,6 +2953,7 @@ class VectorSearchManySplitsTest(unittest.TestCase):
raw_read.assert_called_once()
self.assertEqual([1, 8], sorted(list(result.results())))
+ self.assertEqual(float("-inf"), result.score_getter()(1))
def test_batch_merges_raw_search_results(self):
from pypaimon.globalindex.global_index_reader import GlobalIndexReader
@@ -3071,6 +3073,16 @@ class VectorSearchManySplitsTest(unittest.TestCase):
"_ROW_ID": pa.array([5, 6], type=pa.int64()),
})
+ def _resolve_parallelism(self, parallelism: Optional[int],
num_splits: int) -> int:
+ return 1
+
+ def _new_arrow_batch_reader(
+ self, splits: List[Split]
+ ) -> Tuple[pa.ipc.RecordBatchReader, Iterator[pa.RecordBatch]]:
+ table = self.to_arrow(splits)
+ batches = iter(table.to_batches())
+ return pa.ipc.RecordBatchReader.from_batches(table.schema,
batches), batches
+
class _Builder:
def with_partition_filter(self_inner, predicate):
calls["partition_filter"] = predicate
diff --git a/paimon-python/pypaimon/tests/vector_search_streaming_test.py
b/paimon-python/pypaimon/tests/vector_search_streaming_test.py
new file mode 100644
index 0000000000..3aabdfc03f
--- /dev/null
+++ b/paimon-python/pypaimon/tests/vector_search_streaming_test.py
@@ -0,0 +1,259 @@
+# 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 threading
+import unittest
+import weakref
+from contextlib import ExitStack
+from typing import Callable, Dict, Iterator, List, Optional, Tuple
+from unittest import mock
+
+import numpy as np
+import pyarrow as pa
+import pytest
+
+from pypaimon.execution.python.read.search import vector_search_read as search
+from pypaimon.multimodal.query import VectorQuery
+from pypaimon.read.split import Split
+from pypaimon.tests.data_evolution_test_helpers import BatchModeMixin,
DataEvolutionTestBase
+from pypaimon.tests.vector_search_filter_test import _field
+from pypaimon.utils.range import Range
+
+
+SCHEMA = pa.schema([("_ROW_ID", pa.int64()), ("embedding",
pa.list_(pa.float32(), 1))])
+
+
+def batch(row_id: int, value: float) -> pa.RecordBatch:
+ return pa.record_batch([[row_id], [[value]]], schema=SCHEMA)
+
+
+def planned_read(*sources: Iterator[pa.RecordBatch]) ->
search.AbstractVectorSearchReadImpl:
+ """Give each split its own Arrow reader and run the real single-query read
path."""
+ splits = [mock.Mock(spec=Split) for _ in sources]
+ by_split: Dict[object, Iterator[pa.RecordBatch]] = dict(zip(splits,
sources))
+ caller = threading.get_ident()
+
+ def open_group(group: List[Split]) -> Tuple[pa.ipc.RecordBatchReader,
Iterator[pa.RecordBatch]]:
+ assert threading.get_ident() == caller
+ split, = group
+ source = by_split[split]
+ return pa.ipc.RecordBatchReader.from_batches(SCHEMA, source), source
+
+ table_read = mock.Mock()
+ table_read._new_arrow_batch_reader.side_effect = open_group
+ table_read._resolve_parallelism.return_value = len(splits)
+ read = search.AbstractVectorSearchReadImpl(
+ mock.Mock(), 2, _field(1, "embedding", "FLOAT"), options={"metric":
"inner_product"})
+ read._plan_raw_read = mock.Mock(return_value=(table_read, splits))
+ return read
+
+
+def test_serial_failure_closes_source_before_reading_another_batch() -> None:
+ closed = False
+
+ def source() -> Iterator[pa.RecordBatch]:
+ nonlocal closed
+ try:
+ yield batch(0, 1.0)
+ raise AssertionError("Read the next batch before scoring the
first")
+ finally:
+ closed = True
+
+ read = planned_read(source())
+ with pytest.raises(ValueError, match="dimension mismatch"):
+ read._read_raw_search([Range(0, 1)], None, [1.0, 0.0])
+ assert closed
+
+
+def test_filters_candidates_in_bounded_blocks() -> None:
+ ids = list(range(2051))
+ vectors = [[float(i)] for i in ids]
+ vectors[1024] = [float(len(ids))] # The excluded row would otherwise win.
+ read = planned_read(iter([pa.record_batch([ids, vectors], schema=SCHEMA)]))
+ with mock.patch.object(search, "_iter_arrow_scores",
wraps=search._iter_arrow_scores) as score:
+ result = read._read_raw_search([Range(0, 2050)], None, [1.0],
score_candidates=set(ids) - {1024})
+ assert max(len(args[0]) for args, _ in score.call_args_list) <= 1024
+ assert result.results().to_list() == [2049, 2050]
+
+
+def test_scoring_releases_vector_buffer_before_next_read() -> None:
+ def source() -> Iterator[pa.RecordBatch]:
+ values = np.array([1.0], dtype=np.float32)
+ owner = weakref.ref(values)
+ record = pa.record_batch([pa.array([0]),
pa.FixedSizeListArray.from_arrays(pa.array(values), 1)],
+ schema=SCHEMA)
+ del values
+ yield record
+ del record
+ assert owner() is None
+
+ read = planned_read()
+ for candidates in (None, {0}, set()):
+ read._score_raw_batches(source(), [1.0], "inner_product", candidates)
+
+
+def test_ready_split_makes_progress_with_bounded_lookahead() -> None:
+ scored = [threading.Event() for _ in range(4)]
+ caller = threading.get_ident()
+ original = search._iter_arrow_scores
+
+ def slow() -> Iterator[pa.RecordBatch]:
+ assert scored[2].wait(timeout=5), "A slow split blocked the ready
split"
+ yield batch(4, 4.0)
+
+ def fast() -> Iterator[pa.RecordBatch]:
+ for i in range(4):
+ if i >= 2:
+ assert scored[i - 2].is_set(), "Read more than one batch ahead"
+ yield batch(i, float(i))
+
+ def score(vectors: pa.Array, query: List[float], metric: str) ->
Iterator[Optional[float]]:
+ assert threading.get_ident() == caller
+ value = int(vectors[0].as_py()[0])
+ if value < len(scored):
+ scored[value].set()
+ yield from original(vectors, query, metric)
+
+ read = planned_read(slow(), fast())
+ with mock.patch.object(search, "_iter_arrow_scores", score):
+ result = read._read_raw_search([Range(0, 4)], None, [1.0])
+ assert result.results().to_list() == [3, 4]
+
+
+def test_scoring_error_closes_both_splits() -> None:
+ both_started = threading.Barrier(2)
+ closed = [False, False]
+
+ def source(split: int) -> Iterator[pa.RecordBatch]:
+ try:
+ both_started.wait(timeout=5)
+ yield batch(split, 1.0)
+ yield batch(split + 2, 2.0)
+ finally:
+ closed[split] = True
+
+ read = planned_read(source(0), source(1))
+ with pytest.raises(ValueError, match="dimension mismatch"):
+ read._read_raw_search([Range(0, 3)], None, [1.0, 0.0])
+ assert all(closed)
+
+
+def test_read_error_closes_the_other_split() -> None:
+ started = threading.Event()
+ closed = False
+
+ def failing() -> Iterator[pa.RecordBatch]:
+ yield batch(0, 0.0)
+ assert started.wait(timeout=5)
+ raise OSError("split read failed")
+
+ def other() -> Iterator[pa.RecordBatch]:
+ nonlocal closed
+ try:
+ started.set()
+ while True:
+ yield batch(1, 1.0)
+ finally:
+ closed = True
+
+ read = planned_read(failing(), other())
+ with pytest.raises(OSError, match="split read failed"):
+ read._read_raw_search([Range(0, 1)], None, [1.0])
+ assert closed
+
+
+def test_last_batch_can_outlive_its_reader() -> None:
+ source = mock.Mock()
+ reader = pa.ipc.RecordBatchReader.from_batches(SCHEMA, [batch(0, 1.0)])
+ ref = weakref.ref(reader)
+ table_read = mock.Mock()
+ table_read._new_arrow_batch_reader.return_value = reader, source
+ with ExitStack() as streams:
+ batches = search._open_prefetched_batches(table_read, [], streams)
+ table_read._new_arrow_batch_reader.return_value = None
+ del reader
+ last = next(batches)
+ source.close.assert_called_once()
+ assert list(batches) == []
+ assert ref() is None
+ assert last.column("_ROW_ID").to_pylist() == [0]
+
+
+def test_submit_failure_closes_reader_before_first_read() -> None:
+ reader, source = mock.Mock(), mock.Mock()
+ table_read = mock.Mock()
+ table_read._new_arrow_batch_reader.return_value = reader, source
+ with mock.patch.object(search.ThreadPoolExecutor, "submit",
side_effect=RuntimeError("submit failed")), \
+ pytest.raises(RuntimeError, match="submit failed"):
+ next(search._parallel_raw_batches(table_read, [mock.Mock(spec=Split)],
1))
+ reader.close.assert_called_once()
+ source.close.assert_called_once()
+
+
+class SingleVectorParallelReadTest(BatchModeMixin, DataEvolutionTestBase,
unittest.TestCase):
+ pa_schema = pa.schema([("embedding", pa.list_(pa.float32())), ("pt",
pa.int32())])
+ table_options = {"row-tracking.enabled": "true", "data-evolution.enabled":
"true", "bucket": "-1",
+ "file.format": "parquet", "global-index.search-mode":
"full"}
+
+ def test_public_search_across_partitions(self) -> None:
+ table = self._create_table(partition_keys=["pt"])
+ for i in range(4):
+ self._write_arrow(table, pa.table({"embedding": [[i, 1]], "pt":
[i]}, schema=self.pa_schema))
+
+ def query(parallelism: int) -> Dict[int, float]:
+ result = (table.copy({"read.parallelism":
str(parallelism)}).new_vector_search_builder()
+ .with_vector_column("embedding").with_query_vector([1,
0]).with_limit(2).execute_local())
+ return {row: result.score_getter()(row) for row in
result.results()}
+
+ expected = query(1)
+ assert len(expected) == 2
+ assert query(2) == expected
+
+ def test_nan_last_in_either_split_completion_order(self) -> None:
+ table =
self._create_table(partition_keys=["pt"]).copy({"read.parallelism": "2"})
+ nan = float("nan")
+ for pt, values in enumerate(([nan, 1.0], [1.0, nan])):
+ self._write_arrow(table, pa.table({"embedding": [[v, 0.0] for v in
values], "pt": [pt, pt]},
+ schema=self.pa_schema))
+
+ read_ahead = search._read_one_batch_ahead
+
+ def run(order: Tuple[int, int], limit: int) -> pa.Table:
+ first_consumed = threading.Event()
+ observed = []
+
+ def gated(reader: Iterator[pa.RecordBatch], close_reader:
Callable[[], None]) -> Iterator[pa.RecordBatch]:
+ for block in read_ahead(reader, close_reader):
+ row_id = block.column("_ROW_ID")[0].as_py()
+ if row_id != order[0]:
+ assert first_consumed.wait(timeout=5)
+ observed.append(row_id)
+ yield block
+ first_consumed.set()
+
+ with mock.patch.object(search, "_read_one_batch_ahead", gated):
+ rows = (VectorQuery(table, [1.0, 0.0], "embedding", {"metric":
"l2"})
+
.select(["_ROW_ID"]).limit(limit).with_score().order_by_score().to_arrow())
+ assert observed == list(order)
+ return rows
+
+ for order in ((0, 2), (2, 0)):
+ for limit in (1, 2, 3, 4):
+ with self.subTest(order=order, limit=limit):
+ rows = run(order, limit)
+ assert rows.column("_ROW_ID").to_pylist() == [1, 2, 0,
3][:limit]
+ np.testing.assert_equal(rows.column("_score").to_pylist(),
[1.0, 1.0, nan, nan][:limit])