Skip to content

[core][vector] Add distance range search for Data Evolution - #11655

Open
shyjsarah wants to merge 9 commits into
apache:masterfrom
shyjsarah:feat/vector-distance-range-search
Open

shyjsarah wants to merge 9 commits into
apache:masterfrom
shyjsarah:feat/vector-distance-range-search

Conversation

@shyjsarah

@shyjsarah shyjsarah commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

Java factory Matching distance
VectorDistanceRange.atMost(max) distance <= max
VectorDistanceRange.atLeast(min) distance >= min
VectorDistanceRange.closed(min, max) min <= distance <= max

Bounds 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

import org.apache.paimon.data.InternalRow;
import org.apache.paimon.predicate.VectorDistanceRange;
import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.table.Table;
import org.apache.paimon.table.source.VectorRangeRead;
import org.apache.paimon.types.RowType;

import java.util.Collections;

// Use a Data Evolution table with a three-dimensional embedding column and an INT id.
Table table = catalog.getTable(identifier);
RowType projection = table.rowType().project(Collections.singletonList("id"));
VectorRangeRead read = table.newVectorSearchBuilder()
        .withVectorColumn("embedding")
        .withVector(new float[] {1.0f, 2.0f, 3.0f})
        .newVectorRangeRead(VectorDistanceRange.closed(0.05, 0.20));

for (VectorRangeRead.Task task : read.plan()) {
    try (RecordReader<InternalRow> rows = read.createReader(task, projection)) {
        rows.forEachRemaining(row -> System.out.println(row.getInt(0)));
    }
}

Batch queries

Plan once and run searchBatch for 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 call createBatchReader to read table columns.

float[][] queries = {{1.0f, 2.0f, 3.0f}, {3.0f, 2.0f, 1.0f}};
VectorRangeRead batch = table.newVectorSearchBuilder()
        .withVectorColumn("embedding")
        .newBatchVectorRangeRead(VectorDistanceRange.atMost(0.20));

for (VectorRangeRead.Task task : batch.plan()) {
    batch.searchBatch(task, queries, (queryIndex, rowIds, scores) -> {
        try (RecordReader<InternalRow> rows =
                batch.createBatchReader(task, rowIds, scores, projection)) {
            rows.forEachRemaining(row -> System.out.println(queryIndex + ": " + row.getInt(0)));
        }
    });
}

Distance means squared L2, 1 - cosine similarity, or the negative dot product according to the index metric. Set search options with withOption or withOptions. The detail mode also evaluates uncovered rows from their original vectors. The fast mode 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

  • Convert inclusive Java bounds to the Native SDK's half-open float interval and apply the range predicate to both indexed and exact distances. This uses the chunked SDK API already available through [build] Upgrade Java and Python vector index dependencies to 0.6.0 #11358.
  • Plan tasks from snapshot and manifest metadata. Resolve the persisted metric on the worker, including from the native header for older indexes, and use that metric for exact fallback. Apply live-row and predicate filters at the task snapshot and reuse file-group planning across result chunks.
  • Prescale cosine queries only when their FP32 squared norm risks overflow or underflow. Native search and centroid routing use the same prescaling rule and let the SDK normalize the query.
  • Deliver centroid range results outside the shared index pool. Use a bounded producer executor for pull readers, wait for active producers to release resources on close, and preserve the original failure type.
  • Keep the snapshot handling local to the Range path and read the existing index format. The Spark SQL integration is tracked in [spark] Add distance range search for Data Evolution #11657.

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.

  • Clean Maven build on JDK 11 passed 228 tests. Two existing Lumina scan tests require the Lumina JNI library and were skipped on this machine. The new Lumina range fallback regression passed using persisted manifest metadata.
  • The documentation production build passed, and both Java examples compile against the rebuilt API.
mvn -B -pl paimon-vector,paimon-lumina -am -DfailIfNoTests=false -DwildcardSuites=none \
  -Dtest=BatchReadTagCreatorTest,CentroidTableInteropTest,CentroidVectorGlobalIndexTest,DataEvolutionBatchScanTest,DataEvolutionReadTest,DataEvolutionTableReadTest,DataEvolutionVectorReadPlannerTest,LuminaVectorGlobalIndexerFactoryTest,LuminaVectorGlobalIndexScanTest,LuminaVectorRangeReadTest,NativeVectorGlobalIndexTest,RangeChunkReaderTest,VectorSearchBuilderTest,VectorSearchMetricTest \
  clean package

@JingsongLi JingsongLi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please separate any changes unrelated to the functionality into a distinct PR.

@JingsongLi

Copy link
Copy Markdown
Contributor

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 range_filter. Lance Java API · Milvus Range Search

I’d use a VectorDistanceRange for both newVectorRangeRead and newBatchVectorRangeRead, with explicit factory methods:

  • atMost(max) matches distance <= max and preserves the current inclusive threshold.
  • atLeast(min) matches distance >= min.
  • closed(min, max) matches min <= distance <= max.

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 withLimit(k) before creating a range read, the builder should reject that combination explicitly. A future bounded search can pair the same range with the existing Top-K API, filter by distance first, and apply k per query across all tasks.

@shyjsarah

Copy link
Copy Markdown
Contributor Author

Thanks @JingsongLi. I updated the PR in 0ca4fb4.

  • Both the single-vector and batch Java APIs now accept VectorDistanceRange.atMost(max), atLeast(min), and closed(min, max). Both endpoints are inclusive for indexed and exact reads. The builder rejects an explicit withLimit(k), including zero. The PR description now has single-query and batch Java examples. Distance bounds and limit feedback
  • The snapshot changes are scoped to range reads, and I dropped the index writer metadata change. Range reads can resolve the metric from existing index metadata or the native index header. The existing Top-K tag-snapshot case can follow separately once reproduced through the Top-K API. PR scope feedback

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.

@shyjsarah
shyjsarah force-pushed the feat/vector-distance-range-search branch from d2f9135 to 34e1558 Compare December 3, 2026 09:32

@jerry-024 jerry-024 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +439 to +446
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.
  2. Pure-Java planner/driver nodes without the native vector library installed will fail with UnsatisfiedLinkError during plan().

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +570 to +572
synchronized void stop() {
stopped = true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +143 to +149
} 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +107 to +110
synchronized (pending) {
while (!closed && pending.size() == MAX_QUEUED_CHUNKS) {
pending.wait();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two lifecycle/concurrency concerns here:

  1. When backing NativeCentroidRoutedIndexReader (which probes all shards concurrently on the JVM-wide GlobalIndexReadThreadPool), blocking in offer() while holding RangeDelivery's synchronized lock parks the remaining shard threads on RangeDelivery's monitor as well. A slow Parquet consumer (or an open RecordReader that pauses between batches) can tie up GlobalIndexReadThreadPool threads for other queries in the same JVM.
  2. readBatch() spawns a raw unmanaged Thread per createReader(), and close() returns after search.cancel(true) without waiting for the producer thread to finish releasing native reader / SeekableInputStream handles (JNI calls do not respond to Java interrupts until the next callback).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +122 to +125
DataEvolutionVectorScan.ScanPlan plan =
new DataEvolutionVectorScan(
table, partitionFilter, null, vectorColumn, options, snapshot)
.scanWithIndexFiles();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +140 to +144
RawVectorSearchSplit raw = (RawVectorSearchSplit) split;
for (Range range : raw.rowRanges()) {
sources.add(new Source(range, null, raw.indexType()));
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +563 to +569
float distance =
VectorSearchMetric.computeDistance(queries[query], stored, metric);
if (distanceRange.contains(distance)) {
hitIds[size] = ids[i];
scores[size++] =
VectorSearchMetric.computeScore(queries[query], stored, metric);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants