Repository navigation
Conversation
JingsongLi
left a comment
There was a problem hiding this comment.
Please separate any changes unrelated to the functionality into a distinct PR.
|
Could we support both distance bounds in this PR? A lower bound lets callers exclude near-duplicates while keeping other similar results. Lance exposes this through its lower bound, and Milvus covers the same use case with I’d use a
The indexed path and the exact fallback should apply the same boundary rules. Tests should cover both endpoints and adjacent floating-point values. I’d keep range reads uncapped in this PR. If a caller sets |
|
Thanks @JingsongLi. I updated the PR in 0ca4fb4.
The clean Maven build passed all 162 selected Core and Native tests, including boundary and adjacent floating-point cases. Both Java usage examples compiled against the rebuilt API. |
d2f9135 to
34e1558
Compare
jerry-024
left a comment
There was a problem hiding this comment.
Left a few inline comments on planning-time I/O/JNI coupling, concurrency/backpressure handling in RangeChunkReader / RangeDelivery, raw-fallback task packing & scoring, and VectorDistanceRange value-object methods.
| for (List<IndexFileMeta> index : indexes) { | ||
| String stored = rawSearchMetric(createMetricIndexer(index)); | ||
| checkArgument( | ||
| metric == null || metric.equals(stored), | ||
| "Vector range search found conflicting index metrics %s and %s.", | ||
| metric, | ||
| stored); | ||
| metric = stored; |
There was a problem hiding this comment.
Now that non-centroid paimon-vector index files still write an empty {} VectorIndexMeta (no persisted metric), calling createMetricIndexer(index) -> NativeVectorGlobalIndexer.forRead(...) in this loop opens a remote SeekableInputStream and instantiates a native VectorIndexReader (JNI) for every non-centroid index group during plan() (and across all partitions if partitionFilter pruned to an unindexed partition).
This has two downsides:
- On a table with hundreds/thousands of non-centroid index files,
plan()performs O(N) synchronous remote file opens on the coordinator before returning tasks. - Pure-Java planner/driver nodes without the native vector library installed will fail with
UnsatisfiedLinkErrorduringplan().
Consider either persisting metric in VectorIndexMeta first (in a prerequisite PR), or avoiding full-loop file opens during plan() (e.g., indexed tasks already read their own native header at execution time, and raw fallback can resolve from a single sample or table options).
There was a problem hiding this comment.
Handled in 4dc4a64793. plan() now builds tasks from snapshot and manifest metadata. Workers read older Native headers at execution and use the persisted metric for raw fallback. Indexed tasks check their metric before emitting hits. The regression blocks index-file opens during planning and verifies the results of serialized tasks when the table is configured for a different metric.
| synchronized void stop() { | ||
| stopped = true; | ||
| } |
There was a problem hiding this comment.
stopped is already volatile, so making stop() synchronized on the same monitor held during accept(...) -> consumer.accept(...) can block cancellation: if one shard thread is parked inside a slow or backpressured consumer.accept(...), an interrupted caller in visitRangeShards (catch (InterruptedException) { delivery.stop(); }) blocks waiting for the lock instead of flipping stopped = true immediately so other shards can exit.
Dropping synchronized from stop() avoids this.
There was a problem hiding this comment.
Updated in 3eec77ebe8. stop() now sets the volatile flag directly. Range search checks interruption during delivery and before opening the next shard. The cancellation regression checks that only the current shard was opened.
| } catch (ExecutionException e) { | ||
| Throwable cause = e.getCause(); | ||
| if (cause instanceof IOException) { | ||
| throw (IOException) cause; | ||
| } | ||
| throw new IOException("Vector range search failed.", cause); | ||
| } catch (InterruptedException e) { |
There was a problem hiding this comment.
This wraps RuntimeException (e.g., IllegalArgumentException from option or dimension validation) and Error (e.g., OutOfMemoryError) into IOException, whereas searchBatch and NativeCentroidRoutedIndexReader.visitRangeShards rethrow RuntimeException and Error directly. Consider rethrowing RuntimeException and Error unwrapped here as well.
There was a problem hiding this comment.
Updated in 3eec77ebe8. RangeChunkReader now rethrows the original IOException, RuntimeException, or Error from the producer. The regression checks that the same exception instance reaches the caller.
| synchronized (pending) { | ||
| while (!closed && pending.size() == MAX_QUEUED_CHUNKS) { | ||
| pending.wait(); | ||
| } |
There was a problem hiding this comment.
Two lifecycle/concurrency concerns here:
- When backing
NativeCentroidRoutedIndexReader(which probes all shards concurrently on the JVM-wideGlobalIndexReadThreadPool), blocking inoffer()while holdingRangeDelivery'ssynchronizedlock parks the remaining shard threads onRangeDelivery's monitor as well. A slow Parquet consumer (or an openRecordReaderthat pauses between batches) can tie upGlobalIndexReadThreadPoolthreads for other queries in the same JVM. readBatch()spawns a raw unmanagedThreadpercreateReader(), andclose()returns aftersearch.cancel(true)without waiting for the producer thread to finish releasing native reader /SeekableInputStreamhandles (JNI calls do not respond to Java interrupts until the next callback).
There was a problem hiding this comment.
Handled in 3eec77ebe8. Centroid Range visits shards one at a time and delivers results on the calling thread, keeping callback backpressure off the shared index pool. Pull readers use a dedicated bounded producer executor. close() wakes a blocked producer, requests cancellation, and waits for cleanup. It may wait for an active JNI call to return. The regressions cover index-pool availability during delivery and closing with both queued and running producers.
| DataEvolutionVectorScan.ScanPlan plan = | ||
| new DataEvolutionVectorScan( | ||
| table, partitionFilter, null, vectorColumn, options, snapshot) | ||
| .scanWithIndexFiles(); |
There was a problem hiding this comment.
Passing filter = null here means VectorRangeRead does not discover standalone scalar global indexes (bitmap / btree / rtree) — prepareIndexCandidates only checks CentroidBitmapFilter, so filtered range queries on non-centroid indexes or standalone scalar indexes always fall back to FilteredRowIdReader scanning Parquet data files. If skipping standalone scalar global indexes is intentional for this PR, it would be helpful to note that limitation in vector.mdx / Javadoc.
There was a problem hiding this comment.
Documented in 4dc4a64793 in both vector.mdx and the VectorRangeRead Javadoc. Range search uses compatible centroid bitmaps when available. Other scalar predicates are evaluated from data at the task snapshot, including predicates on columns with standalone scalar indexes.
| RawVectorSearchSplit raw = (RawVectorSearchSplit) split; | ||
| for (Range range : raw.rowRanges()) { | ||
| sources.add(new Source(range, null, raw.indexType())); | ||
| } | ||
| } |
There was a problem hiding this comment.
Unpacking every Range from RawVectorSearchSplit.rowRanges() into a separate Source emits at least one Task per disjoint unindexed range. If a table has many small disjoint unindexed gaps, this can produce a large number of tiny tasks, each running its own file-group scan and Parquet read. Consider packing consecutive small non-overlapping raw ranges into a single RawVectorSearchSplit task up to the RAW_TASK_ROWS budget.
There was a problem hiding this comment.
I’ve left raw-task packing as a follow-up optimization. The proposed change is to group adjacent raw task ranges under RAW_TASK_ROWS by counting the covered rows and retaining the gaps, so the ranges can share a file-group plan.
| float distance = | ||
| VectorSearchMetric.computeDistance(queries[query], stored, metric); | ||
| if (distanceRange.contains(distance)) { | ||
| hitIds[size] = ids[i]; | ||
| scores[size++] = | ||
| VectorSearchMetric.computeScore(queries[query], stored, metric); | ||
| } |
There was a problem hiding this comment.
For every matching row, computeDistance and computeScore both scan the full vector dimension independently, doubling CPU work on hits. Computing the score directly from distance (e.g., via a VectorSearchMetric.distanceToScore helper) avoids repeating the vector arithmetic.
There was a problem hiding this comment.
I’ve left this as a follow-up CPU optimization. The proposed change is to compute the squared L2 distance, dot product, or cosine similarity once per pair and derive the distance and score from it. For cosine, reusing the original similarity preserves the score across floating-point boundaries.
| import static org.apache.paimon.utils.Preconditions.checkArgument; | ||
|
|
||
| /** Inclusive range in the distance units of the vector index metric. */ | ||
| public final class VectorDistanceRange implements Serializable { |
There was a problem hiding this comment.
Since VectorDistanceRange is a public Serializable value object in paimon-common, consider implementing equals, hashCode, and toString for future query-plan equality/caching, explain output, and test assertions.
There was a problem hiding this comment.
Added equals, hashCode, and toString in 3ae94d9c19. Equality and hashing use the two bounds and treat signed zero as the same bound. The tests cover one-sided and closed ranges and a serialization round trip.
Purpose
Add uncapped distance range reads for single-vector columns on Data Evolution append tables. Engines can plan snapshot-scoped tasks and distribute them before searching. Each task streams matching row IDs and scores in bounded chunks and can read projected table rows from the same snapshot.
Usage
The single-vector and batch APIs use the same inclusive bounds.
VectorDistanceRange.atMost(max)distance <= maxVectorDistanceRange.atLeast(min)distance >= minVectorDistanceRange.closed(min, max)min <= distance <= maxBounds are finite. A closed range may have equal bounds. Result order is unspecified. Both range methods reject an explicit
withLimit(k)and branch fallback reads.Single query
Batch queries
Plan once and run
searchBatchfor each task. The callback produces the zero-based input query index and aligned row IDs and scores, with up to 4,096 hits per chunk. Use the chunk directly for metadata-only consumers or callcreateBatchReaderto read table columns.Distance means squared L2,
1 - cosine similarity, or the negative dot product according to the index metric. Set search options withwithOptionorwithOptions. Thedetailmode also evaluates uncovered rows from their original vectors. Thefastmode restricts the search to index coverage. Probe options can narrow candidate coverage, and quantized distances can move results across a boundary. Compatible centroid bitmaps can prefilter scalar predicates. Other scalar predicates are evaluated from table data at the task snapshot.Changes
Tests
The selected suites cover inclusive bounds, time travel through a tag, explicit limit and branch fallback rejection, persisted Lumina metrics, zero-distance cosine matches for identical non-axis-aligned vectors, and extreme-scale cosine queries with and without centroid routing. The review regressions also cover payload-free planning for legacy native indexes, worker-side metric validation after task serialization, slow consumers, cancellation, and producer error propagation.