gouthamaenugu opened a new pull request, #8154: URL: https://github.com/apache/geode/pull/8154
# PR 1: Add `KnnFloatVectorField`, SQ8 Scalar Quantization Codec, Zero-Copy PDX Vector Mapping, and Bounded Segment Compaction - **Branch:** `gouthamaenugu:feature/GEODE-vector-pr1-knn-field` - **Base:** `apache:develop` (`46643af515`) - **Head Commit:** `8b51aa312a752246f8e1d57d3600d49680159c11` (`26 files changed, +3014 / -39`) - **Module:** `geode-lucene` (Apache Geode 2.1, bundled Apache Lucene `9.12.3`) --- ### For all changes, please confirm: - [ ] Is there a JIRA ticket associated with this PR? Is it referenced in the commit message? *(Draft PR ready for upstream `GEODE-*` JIRA ticket assignment and commit prefix update.)* - [x] Has your PR been rebased against the latest commit within the target branch (typically `develop`)? - [ ] Is your initial contribution a single, squashed commit? *(Currently 3 clean logical commits — feature implementation, review hardening, and bounded merge/compaction tuning — ready to squash on upstream submission.)* - [x] Does `gradlew build` run cleanly? *(Verified `:geode-lucene:spotlessCheck`, `:geode-lucene:checkPom`, `:geode-lucene:javadoc`, `:geode-lucene:test --rerun`, and `AnalyzeLuceneSerializablesIntegrationTest.testSerializables`.)* - [x] Have you written or updated unit tests to verify your changes? *(46 new unit tests across 5 dedicated JUnit suites.)* - [x] If adding new dependencies to the code, are these dependencies licensed in a way that is compatible for inclusion under [ASF 2.0](http://www.apache.org/legal/resolved.html#category-a)? *(No new external dependencies added; uses Geode 2.1's bundled Apache Lucene `9.12.3`.)* --- ## Summary / Motivation Apache Geode 2.1 ships with Apache Lucene `9.12.3`, which natively supports HNSW approximate nearest-neighbor indexing (`KnnFloatVectorField`) and 8-bit scalar quantization (`Lucene99ScalarQuantizedVectorsFormat`), yet `geode-lucene` currently exposes only lexical text indexing. This PR introduces the foundational vector indexing layer in `geode-lucene`: 1. Declarative, immutable vector field metadata (`VectorIndexMetadata`) with cluster-wide profile consistency checks. 2. Zero-copy extraction of `float[]`, `List<Float>`, `double[]`, and `Number[]` embeddings from both `PdxInstance` (via `PdxInstance.getField(...)` without ever triggering `PdxInstance.getObject()`) and POJOs (via `ClassValue`-cached reflection). 3. Native Lucene `9.12.3` `KnnFloatVectorField` emission across `PdxLuceneSerializer`, `ReflectionLuceneSerializer`, `HeterogeneousLuceneSerializer`, and `FlatFormatSerializer`, plus optional SQ8 quantization via a `Lucene912Codec` override wrapping `Lucene99HnswScalarQuantizedVectorsFormat` and `Lucene99HnswVectorsFormat`. 4. Vector-aware bounded `TieredMergePolicy` + `RAMBufferSizeMB` tuning and an internal `maybeCompactSegments(int maxSegments)` helper to prevent tiny HNSW segment proliferation under frequent AEQ commits (while leaving non-vector Lucene indexes completely untouched). --- ## Key Changes ### Public & Internal API Additions - **`VectorIndexMetadata`** (`org.apache.geode.cache.lucene`): Immutable descriptor holding `fieldName`, `dimension`, `VectorSimilarityFunction` (`COSINE`, `DOT_PRODUCT`, `EUCLIDEAN`), HNSW graph parameters (`maxConnections` M, `beamWidth` efConstruction), and `quantizeSQ8` flag. Rejects invalid dimensions, non-positive `M`/`efConstruction`, and null/blank names. - **`LuceneIndexFactory`** & **`LuceneIndex`** (`org.apache.geode.cache.lucene`): - Added `default` fluent methods `.addVectorField(String name, int dimension, VectorSimilarityFunction similarity, boolean quantizeSQ8)` and `.addVectorField(String name, int dimension, VectorSimilarityFunction similarity, int maxConnections, int beamWidth, boolean quantizeSQ8)`. - Added `default Map<String, VectorIndexMetadata> getVectorFields()` on `LuceneIndex`. - **`LuceneIndexFactoryImpl`**, **`LuceneIndexImpl`**, **`LuceneServiceImpl`**, **`LuceneRegionListener`**, **`LuceneIndexCreation`**: - Wired vector field definitions end-to-end into index creation and region listener registration. - Enforced fail-fast validation rejecting duplicate vector field names and collisions between lexical text fields and vector fields in both directions. - Preserved pure-vector index creation (allowing empty lexical `fieldNames` when at least one vector field is configured). ### Vector Extraction, Codec Integration & Bounded Segment Compaction - **`VectorFieldMapper`** (`org.apache.geode.cache.lucene.internal.repository.serializer`): - Extracts vectors from `PdxInstance` (including dot-separated nested paths) using `getField(...)` only — zero domain-class deserialization. - Uses `ClassValue<ConcurrentHashMap<String, Field>>` for classloader-safe, leak-free POJO field caching. - Defensively copies caller `float[]` arrays, validates exact dimension match and finite values, and checks float32 `COSINE` squared-norm overflow/underflow before Lucene ingestion (`!Float.isFinite(normSqFloat32) || normSqFloat32 <= 0.0f`). - Configures per-field Lucene `9.12.3` `KnnVectorsFormat` (`Lucene99HnswScalarQuantizedVectorsFormat` when `quantizeSQ8=true`, otherwise `Lucene99HnswVectorsFormat`). - Provides `configureVectorIndexWriterConfig(IndexWriterConfig, Map<String, VectorIndexMetadata>)` setting `RAMBufferSizeMB=64.0`, `ConcurrentMergeScheduler`, and a bounded `TieredMergePolicy` (`segmentsPerTier=4.0`, `maxMergeAtOnce=8`, `floorSegmentMB=16.0`, `maxMergedSegmentMB=1024.0`) for vector indexes only. - **`IndexRepositoryFactory`**, **`IndexRepository`**, **`IndexRepositoryImpl`**, **`PartitionedRepositoryManager`**, **`LuceneIndexForPartitionedRegion`**: - Wired `createIndexWriterConfig` to apply vector merge/RAM tuning exclusively when `vectorFields` is non-empty (leaving lexical-only `IndexWriterConfig` defaults 100% unchanged). - Exposed internal `maybeCompactSegments(int maxSegments)` (default method on `IndexRepository`, synchronized two-phase merge/sync + bounded `forceMerge` fallback in `IndexRepositoryImpl`, and bucket-wide helpers on `PartitionedRepositoryManager` / `LuceneIndexForPartitionedRegion`) that returns `false` with zero write amplification when already within budget. - **Serializers (`PdxLuceneSerializer`, `ReflectionLuceneSerializer`, `HeterogeneousLuceneSerializer`, `FlatFormatSerializer`)**: - Updated all built-in serializers to emit `KnnFloatVectorField` alongside existing lexical fields while leaving non-vector indexing behavior unchanged. ### New Unit Test Suites (46 Tests) - `VectorIndexMetadataJUnitTest` (10 tests): metadata validation, immutability, Java serialization round-trip, and strict `readObject` invariant checks. - `VectorIndexProfileAndFactoryJUnitTest` (13 tests): fluent factory API, duplicate/collision rejection, cluster profile compatibility checks, and `Version.GEODE_1_4_0` / `GEODE_2_1_0` serialization wire compatibility. - `VectorFieldMapperJUnitTest` (14 tests): zero-copy `PdxInstance` extraction (asserting `getObject()` is never invoked), nested paths, `FlatFormatSerializer` coverage, float32 norm overflow/underflow rejection, and defensive array copying. - `VectorCodecRecallJUnitTest` (4 tests): end-to-end Lucene `9.12.3` HNSW FP32 and SQ8 codec indexing and synthetic clustered top-k recall verification. - `VectorSegmentCompactionJUnitTest` (5 tests): verifies vector-index `TieredMergePolicy`/`RAMBufferSizeMB`/`ConcurrentMergeScheduler` config, non-vector default preservation, natural `<= 4` segment consolidation across 5,000 docs / 50 commits without `forceMerge(1)` with preserved FP32 & SQ8 Recall@10, and `IndexRepositoryImpl` / `PartitionedRepositoryManager` `maybeCompactSegments` behavior. --- ## Backward Compatibility & Serialization Notes - **Zero Public API Breakage:** All new methods on public interfaces (`LuceneIndexFactory`, `LuceneIndex`) and internal `IndexRepository` (`maybeCompactSegments`) are declared `default`. Existing callers using lexical-only indexes hit unchanged code paths (including preserving legacy 8-argument `LuceneRegionListener` delegation and default Lucene `IndexWriterConfig` when `vectorFields` is empty). - **Rolling-Upgrade Wire Compatibility:** `LuceneIndexCreationProfile` adds versioned `toDataPre_GEODE_2_1_0_0` / `fromDataPre_GEODE_2_1_0_0` methods and null-guards `getFieldNames()`/`getFieldAnalyzers()` for legacy pre-1.4 profiles. `sanctionedDataSerializables.txt` is updated with exact bytecode lengths. - **`ObjectInputFilter` Safety:** `VectorIndexMetadata` serializes `similarityFunctionName` (`String`) rather than the third-party Lucene `VectorSimilarityFunction` enum (which is held in a `transient volatile` cache and re-validated in `readObject`), avoiding Geode P2P `InvalidClassException` rejections. - **Sanctioned Serializables:** Registered `org/apache/geode/cache/lucene/VectorIndexMetadata` in `sanctioned-geode-lucene-serializables.txt` and verified via `AnalyzeLuceneSerializablesIntegrationTest.testSerializables`. --- ## Exact Gradle Verification Commands & Pass Counts ```bash ./gradlew --no-daemon --max-workers=2 \ :geode-lucene:spotlessCheck \ :geode-lucene:checkPom \ :geode-lucene:javadoc \ :geode-lucene:test --rerun ./gradlew --no-daemon --max-workers=2 \ :geode-lucene:integrationTest \ --tests "org.apache.geode.codeAnalysis.AnalyzeLuceneSerializablesIntegrationTest.testSerializables" ``` | Verification Suite | Total | Passed | Failed | Skipped | Status | | :--- | ---: | ---: | ---: | ---: | :--- | | `:geode-lucene:test --rerun` | 329 | 325 | 0 | 4 *(pre-existing)* | **PASS** | | PR 1 Vector Unit Test Suites (subset of above) | 46 | 46 | 0 | 0 | **PASS** | | `AnalyzeLuceneSerializablesIntegrationTest.testSerializables` | 1 | 1 | 0 | 0 | **PASS** | | `:geode-lucene:spotlessCheck`, `:checkPom`, `:javadoc` | — | — | 0 | — | **PASS** | ### Per-Suite Vector Test Breakdown ```text PR 1 (:geode-lucene:test) Summary: total=329, passed=325, failed=0, errors=0, skipped=4 PR 1 Vector Test Suites: - org.apache.geode.cache.lucene.VectorIndexMetadataJUnitTest: 10/10 passed (0 failed, 0 errors, 0 skipped, 0.008s) - org.apache.geode.cache.lucene.internal.VectorIndexProfileAndFactoryJUnitTest: 13/13 passed (0 failed, 0 errors, 0 skipped, 0.011s) - org.apache.geode.cache.lucene.internal.VectorSegmentCompactionJUnitTest: 5/5 passed (0 failed, 0 errors, 0 skipped, 4.367s) - org.apache.geode.cache.lucene.internal.repository.serializer.VectorCodecRecallJUnitTest: 4/4 passed (0 failed, 0 errors, 0 skipped, 0.525s) - org.apache.geode.cache.lucene.internal.repository.serializer.VectorFieldMapperJUnitTest: 14/14 passed (0 failed, 0 errors, 0 skipped, 0.016s) ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
