Repository navigation
[spark] Support centroid-based sharding for vector global indexes - #11249
Conversation
leaves12138
left a comment
There was a problem hiding this comment.
Reviewed the full diff at head f5c88177 against master (d90a902d), including the generic core paths.
Core / generic semantics touched (flagging per review policy): IndexManifestFileHandler (global-index range-overlap validation), DataEvolutionConflictDetection + CommitScanner (commit conflict path), GlobalIndexQuery / DataEvolutionGlobalIndexScanner / DataEvolutionVectorScan / AbstractDataEvolutionVectorRead (query planning and read for all vector layouts), GlobalIndexer.resolveOptions, ScoredGlobalIndexResult.topK, plus the Python reader boundary. These affect non-centroid tables too, not just the new Spark build.
What I verified:
validateRetainedIndexFilesrewrite to per-partition/fieldTreeRangeMappreserves the old rejection semantics: the two-pass file-local/table-wide split still rejects mixed-kind overlaps and still skips file-local vs file-local, while sibling shards sharing one range no longer false-positive. Nested/duplicate additions and endpoint conflicts are covered inIndexManifestFileHandlerTest.checkCentroidSourceChangesonly activates for wrapped router additions, walks snapshots strictly after each router's own baseline, and resolves written field IDs per(schemaId, writeCols)so partial-column updates to other fields do not abort the build. Multi-router baselines and same-range appends are tested inConflictDetectionTest.- The
CentroidIndexMetaenvelope keeps ordinary range metadata byte-identical (isWrappedfalse path returns the same array), validates version/role/lengths on decode, and round-trips throughIndexFileMetaSerializerand split serialization. Core never loads the vector plugin to recognize routers/shards. DataEvolutionVectorScannow groups by(range, indexType)instead of failing on mixed types; all-null router-only ranges keep coverage without emitting search splits, and the scalar-file prefix-max grouping matches the previous intersection semantics. Raw fallback keeps a deterministic scoring type.ScoredGlobalIndexResult.topKmaterializes selected scores so truncated results no longer retain the full candidate score map; exact score bits (signed zero, NaN payload) are asserted after the input map is cleared.- Writer/reader:
SearchScopeserializes the row-ID filter once per invocation and shares it across shards and probe rounds; empty shards short-circuit before opening files;sampleIndexoverflow guard and the lazy spill buffer keep large-range builds bounded. Deterministic sampling is verified byte-for-byte across build parallelisms inCentroidVectorIndexTest. - Python explicitly rejects centroid builds and routed reads with clear
NotImplementedErrors instead of misreading the envelope; boundary tests included.
Non-blocking notes:
paimon-vectornow depends onpaimon-vector-index-java:0.7.0-SNAPSHOT. Fine for master development, but please pin a released version before the next Paimon release cut so release builds do not resolve a moving artifact.- CI:
Flink 1 / Connectors and CDCfailed in the "Set up JDK 8" step with atarexit-code-2 cache error — infrastructure flake, unrelated to this change. The remaining jobs were queued/running at review time; please re-run the flaky job and confirm everything is green before merge.
No blocking findings. Test coverage is thorough: all five algorithms end-to-end, layout switching, mixed-batch probe policies, legacy-descriptor compatibility, concurrent source-change conflicts, and serializer round-trips.
|
Hi, @JingsongLi Thank you for this contribution! Centroid-based sharding is a valuable improvement for reducing query fan-out across index shards, especially under high QPS. I wonder would it make sense to make the implementation more backend-independent? For example, we could have a shared centroid build and query layer responsible for training the router, assigning vectors to centroids, and selecting shards at query time. Each shard’s writer and reader could then be created through a backend-specific factory, supporting Native IVF/DiskANN as well as Lumina. This would let other vector index backends reuse the routing layer while retaining their own indexing and search implementations. What do you think about this separation? |
Hi @lxy-9602 , Since this layer is essentially the same as IVF, it should be considered part of the index implementation. I believe the Lumina module could either implement its own IVF partitioning or, alternatively, rely directly on the |
@JingsongLi Thanks for the clarification! Keeping the routing logic within the index implementation layer makes sense. For Lumina, we could either reuse the existing IVF-FLAT router or implement IVF partitioning in the Lumina module. We can discuss both options and the concrete integration approach in a follow-up. |
Purpose
Enable centroid-based sharding in Spark for Data Evolution append tables with the existing
ivf-flat,ivf-pq,ivf-sq,ivf-rqanddiskannindex types. Set<index-type>.sharding=centroidinsys.create_global_index. The default isrange. For example,index_type => 'ivf-pq'withoptions => 'ivf-pq.sharding=centroid,ivf-pq.centroid.nlist=64,ivf-pq.nlist=32'builds 64 outer shard slots per contiguous range and requests 32 IVF lists per populated shard. Searches select the layout from persisted file metadata. PIP-47Spark uses the same contiguous row-ID grouping as BTree. Each such range within a partition with any non-null vectors gets its own router and native shards. Spark pins a snapshot, counts vectors per split and plans a deterministic sample with the ordinary IVF-FLAT trainer. Each map task reads the selected rows from its own splits. For each range, one task trains a router on the sampled rows in reservoir order. Spark broadcasts the router, shuffles by centroid ID and builds a local IVF or DiskANN index in each populated shard. A single commit replaces the selected partitions' files of the requested type.
The router and every associated shard carry the same
GlobalIndexMeta.rowRange. Planning, visibility, raw fallback and conflict checks use the standard range. A gap can therefore be searched from source data when the query uses detail or chunk mode. The centroid writer stores each assigned row’s offset from the start of the group range. Both ordinary and centroid readers use the standard OffsetGlobalIndexReader to translate filter bitmaps and restore table row IDs for single and batch searches. Row-ID reassignment can reuse files when the whole group range moves by a constant offset. Paimon Core wraps the router and shard entries inGlobalIndexMeta.indexMetawith the model ID, file role, and outer center count or shard ID. It unwraps the original writer metadata before opening a reader. Ordinary range files retain their existing metadata. For indexes created with this PR's pre-release centroid-specific names, drop them with the previous build and rebuild with the new option.The native router and deterministic sample planner are available in Apache’s published
paimon-vector-index-java:0.7.0-SNAPSHOT. Validation used0.7.0-20261119.003537-3. apache/paimon-vector-index#131Sharding option and persisted layout (049241f)
Spark 3 on JDK 8 and Spark 4 on JDK 17 each passed 543 Java tests and 13 Spark integration tests. These cover all five native algorithms, different outer and inner list counts, default range files, switching the build option, distributed reader dispatch, field-level option resolution, and routing metadata after query split serialization. Spotless and Checkstyle passed. The Python build and vector reader suites passed 79 tests, including explicit diagnostics for the Spark-only layout. The Flink 1.20 reader suite passed 8 tests.
Retained heap for batched top-K results (ca0c6c7)
A truncated top-K result now stores the scores of the selected rows. Once a centroid query finishes merging its shards, the returned result can release the score map for the full candidate set.
Three pairs of fresh JDK 17 processes searched the same native files with all 64 shards selected. Each process warmed up with the full batch. After the measured batch, we closed the reader and compared heap usage after GC with the results held and after GC with the results released. This measures retained Java heap after the search. Across all runs, the 25,600 returned row IDs and their raw float score bits matched byte for byte.
The regression test clears the input score map after truncation and verifies the selected rows and exact scores, including a boundary tie and a NaN payload. Spark 3 on JDK 8 and Spark 4 on JDK 17 each passed 542 Java tests and 13 Spark integration tests. Spotless and Checkstyle passed for paimon-common.
Filtered shard reads and commit plugin discovery (8e22041)
A routed query serializes its row-ID filter once per reader invocation. All selected data shards and adaptive probe rounds use the same serialized filter and effective top-K. At commit
8e220412ef, a Data Evolution conflict check resolved the router predicate once per index type. The current implementation reads the core layout marker directly and no longer discovers a vector plugin during the commit check.Both readers searched the same native files with the same alternating-row filter over four million row IDs and eight I/O threads. Each query opened a fresh reader with a warm local filesystem cache. Three paired JVM runs each had 32 warm-ups and 64 timed queries. All paired row IDs and float score fingerprints matched. The timing table gives the median of the three per-run statistics. The commit probe exercised actual plugin discovery with four warm-ups and eight timed checks per JVM.
The regression suite passed 533 tests on JDK 8 / Spark 3 and 533 on JDK 17 / Spark 4. Tests check filter reuse with one I/O permit across 64 shards and multiple rounds, and factory discovery once per type across successive conflict checks. Spotless and Checkstyle passed.
Planning and build measurements (9b36307)
Paired local runs against a9bbf30 used the same input and JVM settings for each comparison. The scan benchmark called the Data Evolution vector planner with in-memory manifest entries. The commit benchmark ran the manifest combiner. Both report the median of six timed calls after two warm-ups.
On local Spark with four slots, each build had a large range of 128 input splits and three single-row ranges. Counting, sampling and routing the large range each used four map tasks after the change, up from one. The table shows the median of four timed end-to-end SQL rebuilds after two warm-ups per version and dataset. The four serialized router payloads matched across all builds.
Instrumenting actual Spark reduce tasks recorded four router deserializations per build before and zero after. The new reducer receives the center count and calls the local writer directly. File digests matched for empty shards, larger vectors and a write spanning multiple 8 MiB buffers. An independent differential check also matched the reference conflict and scalar-file intersection rules on 6,000 randomized cases.
For each Spark dataset, 64 inner-product queries at K=10 produced identical row IDs and float score bits before and after, with both automatic and exhaustive local IVF probing. Exhaustive local probing gave 100% recall against brute force on both datasets. Automatic local probing gave 0% on the 2-D dataset and 13.75% on the 32-D dataset on both versions. These synthetic inputs measure build skew. The automatic probe settings have low absolute recall on these inputs.
The same 532 focused tests passed with JDK 8 / Spark 3 and JDK 17 / Spark 4, including 13 Spark integration tests on each. Spotless and Checkstyle passed. Benchmark drivers and generated data were kept outside the repository.
File opens for 64-by-64 automatic IVF probes (a9bbf30)
The writer records each IVF-FLAT or IVF-PQ shard’s actual list count and metric in its private index metadata. A search chooses its probe widths before opening the data files. Batch queries that choose different widths can share the same open shard in a probe round. Older shards without these fields use the same open reader for the header check and candidate searches. The oldest preview router format also needs a separate router-prefix read for metric discovery.
Paired local benchmark against 790dfba used the same 32,768 eight-dimensional L2 vectors, immutable native index files and top-10 queries. The router had 64 centroids. One shard had eight local lists and the others had 64. Each of three runs used a fresh reader per query, four I/O threads, a warm local filesystem cache, 120 warm-up queries and 384 timed queries per index family. Half of the timed queries exercised each path. File opens include the router. Reported P95 is the median of the three runs’ P95s.
Each new-format query read exactly 256 fewer logical bytes. Result fingerprints covering row IDs and float score bits matched for every paired query, including searches of older shards. Older PQ shards can evaluate both probe widths while the file is open. Their mean logical reads in this workload rose by 3.6 KiB per four-shard query and 4.3 KiB per eight-shard query. Targeted tests also compare individual IDs and scores and check that every touched shard opens once and closes with a single I/O permit.
530 focused tests passed with JDK 8 / Spark 3 and 146 with JDK 17 / Spark 4, including all 12 Spark centroid integration cases in each run. Spotless and Checkstyle passed.
Previous review fixes (790dfba)
global-index.thread-num=1, both scalar and batched searches finish. On the same 8,192-row inner-product index with 256 populated shards, the peak number of open shard streams fell from 256 to 1 and the count on query return fell from 256 to 0. The query returned ten hits in both runs. Batches group queries by shard during every round of adaptive probing.Tests
Validation after the centroid review
centroid.nprobecontinues to select a fixed width.Range → centroid, same-recall comparison. Three fresh builds per layout on Spark local[4] and arm64 macOS, using the same immutable SIFT100k files across four disjoint ranges. Build values are medians. Each query opens fresh readers with a warm OS page cache. P95 is the median of the three per-run P95s. File and logical byte counts include routing reads. The five L2 rows use the previously calibrated settings, 2,000 held-out queries per family and 3,500 for PQ. The paired bootstrap resamples query IDs 5,000 times after averaging the three repetitions per query. All five meet the prespecified tolerance of an absolute mean difference ≤ 1 percentage point and a lower 95% bound above −1 point.
The fixed local IVF probes for range/centroid were FLAT 4/8, SQ 4/8, PQ 8/5 and RQ 4/12. Centroid selected two of four outer shards per range. DiskANN used graph search widths 16/64 with the same outer width. RQ traded more logical read bytes for fewer file opens. Absolute latency and build times are local measurements. The benchmark used JDK 17 and the release-mode JNI library from native commit
6396154(apache/paimon-vector-index#133).Metric-specific checks. On the same vectors, 500 held-out queries per metric were scored against an exhaustive dot-product or cosine ground truth. Both layouts searched all 16 local IVF lists. Inner product used automatic outer routing and cosine used four explicit outer probes. These measure ANN reader cost, including logical index-file reads. The separate Spark SQL and batch regressions exercise cosine exact reranking.
Earlier four-range SIFT100k measurements
Use the first 100,000 SIFT1M vectors (128D, L2). The target partition contains four runs of 25,000 rows separated by three rows allocated to another partition. The ordinary range builder produced 19 aligned shards at 6,251 rows per shard. The previous centroid layout at
643346bdd9has one router and 16 shards. The current layout has four routers and four shards per router. Every query visits all four intervals. The ordinary and four-router layouts were rebuilt and timed after switching to range-relative row IDs. In a paired comparison with the previous four-router build, 0 of 34,500 measured query executions changed their exact top-10 hit count. Both centroid layouts have 16 native shards in total.Each cell gives ordinary range / previous partition router / current interval routers.
Run on an Apple M4 Pro, Java 17, Spark
local[4], four native threads, no refinement. Build includes distributed sampling, model training, shuffling, writes and commit. Four families used 300 calibration queries and 2,000 separate measured queries. For IVF-PQ the first measured difference was +1.285 percentage points against ordinary range (78.640% vs 77.355%), outside the matching tolerance. PQ probe settings were recalibrated on 1,200 queries from the original calibration corpus and confirmed on 3,500 previously unused queries. Each layout was rebuilt three times and compared against exact ground truth for this 100k base. Each query opened fresh readers after warming the OS page cache. P95 includes router and shard reads and merging results. Manifest planning, Spark SQL query scheduling and fetching source rows are excluded. Reads include router files and measure logical bytes returned by Paimon. Build times, round P95 and mean bytes/query are medians across the three rounds.Paired Recall@10 differences use percentage points, with 95% intervals from 5,000 bootstrap resamples of the held-out query IDs, averaging each query's three measurements first. The existing matching rule requires an absolute mean difference of at most 1 point and a lower confidence bound above −1 point.
IVF in all layouts used 16 local lists and a training sample ratio of 1. Ordinary IVF probes were 4/4/8/4 for FLAT/SQ/PQ/RQ. The current routers probed two of four centroids per range, with local IVF probes of 8/8/5/12. The previous router probed 6/6/4/4 centroids, with local IVF probes of 8/8/5/8. IVF-PQ used 32-byte codes. DiskANN used graph degree 32, build width 64, 32 PQ subquantizers and F16 raw vectors. Ordinary DiskANN searched with graph width 16. The previous router selected eight shards and the current routers selected two per range, with graph width 64 for both.
The four-router layout opens 12 files per query. For IVF-PQ, the three layouts open 19, 5 and 12 files. The four routers reduce logical reads by 62% against ordinary range. IVF-RQ reads 3.21 MiB with four routers versus 2.31 MiB with ordinary range. With a query spanning every interval, additional routers add fan-out compared with the previous single partition router.
Joint automatic probes for unfiltered centroid IVF
For an L2 IVF-FLAT or IVF-PQ query with K from 10 through 100 and both widths automatic, a 64-center router that initially selects eight centers can instead search four shards with 16 local probes each. Paimon uses the stored local layout of the four nearest shards, reading headers during search for earlier shard formats. Each must have exactly 64 local lists and at least 16 × K indexed vectors. The regular search path handles filters, explicit widths, other layouts and metrics, other families, and underfilled local searches. A batch groups queries by physical shard and executes the required local probe policies on the same reader within a round. Existing index files work directly. The integration uses the existing native API.
On identical pinned SIFT1M and normalized GloVe 500k indexes, 21 paired scenarios covered 8,828 query pairs, including fallback controls. Every enabled query returned the same row-ID / score fingerprint and logical bytes as explicit 4/16. The fallback controls matched the previous automatic reader on every query. In the 2,048-query independent GloVe IVF-PQ K=10 run, the mean recall difference was +0.29 percentage points (paired bootstrap 95% interval −0.22 to +0.80). Exploratory K=1 runs on GloVe had lower bounds below the −1 point threshold, so the shipped policy starts at K=10.
K=100 timing used 384 queries per cell, fresh readers, warm page cache, four native threads and randomized arm order per query. For same-process timing, the old-width control explicitly selects eight outer shards and keeps inner auto. Its per-query IDs, scores and bytes matched the pre-change real auto reader. Files/query decreased from 9 to 5 in all four cells. Byte counts include the router.
Local verification passed 40 vector tests, eight Spark Java tests and nine Spark SQL integration tests on JDK 8 / Spark 3, plus Spotless and Checkstyle. The new native-backed test exercises shared and mixed shard layouts, single and batch search, partial overrides, a row-ID filter, and K outside the tuning window on a single-thread executor.
Automatic outer probes with filters and larger top-K
Local verification passed 32 focused tests on Spark 3 / JDK 8 and all nine centroid SQL integration tests on Spark 4.1 / JDK 17. The Spark 4.0 shared test sources also compiled with the vector index test dependency.
Paimon computes
centroid.nprobeper row-ID range for all five algorithms when centroid sharding is enabled. The four- and eight-centroid floors, filter and top-K expansion, and the 64-by-64 joint plan are in the Paimon reader. Native ranks centroids and searches the chosen shards. The published snapshot containing the router API is sufficient. A newer native library can also be used.Verified the migration against the previous Paimon reader (
22f2f74744) using the merged native policy. The current reader used the earlier native library (e794291). The initial width matched for all 69,632 parameter combinations. On identical pinned SIFT snapshots, 864 paired queries across 14 search plans covered all five index families, 4/8/64/128 outer centers, 5%/50%/80% eligible masks, top-K up to 5,000, and explicit width controls. Every pair matched on the row-ID/score fingerprint, recall, file count and routing bytes. Total logical bytes also matched on every IVF query. For the filtered DiskANN case, mean logical MiB/query was 33.20 and 33.13 respectively. Repeating the same previous build gave 33.10, and repeating the current build gave 33.14. On current Paimon, switching between the two native libraries also reproduced all results and bytes across 320 paired IVF-FLAT queries with four, eight and 64 outer centers. The Spark 3 / JDK 8 run passed all 72 focused tests, including nine SQL integration tests.The original small-router tuning benchmark below compared the original and tuned native policies on the same pinned index snapshot for each pair, with
e794291as the baseline. The Paimon benchmark omitscentroid.nprobein both arms. The dataset contains 100,000 SIFT vectors (L2, 128 dimensions) in four disjoint row-ID ranges. Random masks retain exactly 80%, 50% or 5% of rows per range. Ground truth is exhaustive L2 within the eligible set. Each pair used the same 80–512 held-out queries and identical shard-local settings. Inputs came from original SIFT query positions 8000–9249. Fresh readers counted all logical bytes returned by Paimon streams, including the routers, on an Apple M4 Pro with four native threads.All 32 paired scenarios met the existing recall criterion, an absolute mean difference of at most 1 percentage point and a paired 95% bootstrap lower bound above −1 point. The largest measured recall decrease was 0.111 points (IVF-FLAT, 8 centers, K=1000, 100% eligible). The lowest lower bound was -0.180 points. 10,944 paired query measurements were taken across scenarios. Scenarios can reuse query IDs. The table gives old → new.
Earlier single-range SIFT1M results
Each cell below gives ordinary range → centroid for a single range. These previously reported measurements used one million vectors and the earlier option syntax. The four-range measurements above exercise the layout in this PR.
The four IVF results come from earlier runs with independently trained shard models. Build time, P95 and reads are medians over three rounds. IVF-PQ used 32-byte codes in both layouts and 3,500 held-out queries. Each other family used 2,000 held-out queries. All five comparisons met the prespecified matching rule, which requires an absolute mean recall difference of at most one percentage point and a paired 95% bootstrap lower bound above −1 point.
DiskANN was rebuilt once per layout using the unified IVF-FLAT outer sampler. Both builds used 64 shards, graph degree 32, build search width 64, 32 PQ subquantizers and F16 raw vectors. Range searched 64 shards with graph search width 16. Centroid searched 10 shards with width 128. The recall difference was −0.105 percentage points (paired 95% interval [−0.260, +0.055]). Centroid took 8.12 s longer to build and reduced query P95 from 46.75 ms to 13.26 ms.