Skip to content

GEODE-vector-pr1: Add KnnFloatVectorField, SQ8 Scalar Quantization Codec, Zero-Copy PDX Vector Mapping, and Bounded Segment Compaction - #8154

Draft
gouthamaenugu wants to merge 4 commits into
apache:developfrom
gouthamaenugu:feature/GEODE-vector-pr1-knn-field
Draft

gouthamaenugu wants to merge 4 commits into
apache:developfrom
gouthamaenugu:feature/GEODE-vector-pr1-knn-field

Conversation

@gouthamaenugu

@gouthamaenugu gouthamaenugu commented Nov 24, 2026 •

Copy link
Copy Markdown

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: be90eff48bf290dab051686b08e0202000efa67b (27 files changed, +3026 / -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.)
  • Has your PR been rebased against the latest commit within the target branch (typically develop)?
  • Is your initial contribution a single, squashed commit? (Currently 4 clean logical commits — feature implementation, review hardening, bounded merge/compaction tuning, and VectorIndexMetadata no-arg deserialization + assembly_content.txt Javadoc entry — ready to squash on upstream submission.)
  • Does gradlew build run cleanly? (Verified :geode-lucene:spotlessCheck, :geode-lucene:checkPom, :geode-lucene:javadoc, :geode-lucene:test --rerun, and AnalyzeLuceneSerializablesIntegrationTest.testSerializables.)
  • Have you written or updated unit tests to verify your changes? (46 new unit tests across 5 dedicated JUnit suites.)
  • If adding new dependencies to the code, are these dependencies licensed in a way that is compatible for inclusion under ASF 2.0? (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 & Assembly Manifest: Registered org/apache/geode/cache/lucene/VectorIndexMetadata in sanctioned-geode-lucene-serializables.txt (with a private no-arg constructor populating valid defaults for AnalyzeLuceneSerializablesIntegrationTest deserialization checks) and added javadoc/org/apache/geode/cache/lucene/VectorIndexMetadata.html to geode-assembly/src/integrationTest/resources/assembly_content.txt.

Exact Gradle Verification Commands & Pass Counts

(Baseline counts captured on 8b51aa312a; follow-up commit be90eff48b adds the private no-arg VectorIndexMetadata constructor and assembly_content.txt entry.)

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

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)

@JinwooHwang

Copy link
Copy Markdown
Contributor

Welcome, @gouthamaenugu, and thank you for this contribution! Vector indexing is an exciting direction for geode-lucene, and the amount of care here shows: the detailed description, the unit tests, and the attention to keeping lexical-only indexes unchanged.

I've approved the CI workflows so you can get test signal while this is still a draft.

Since this adds public API and touches serialization and wire compatibility, a few steps will help it move smoothly:

  1. Design discussion on dev@geode.apache.org. A short proposal covering the API shape, the compatibility impact, and how the PRs in the series fit together lets the community weigh in before detailed code review.
  2. A JIRA ticket, with the PR title and commits updated to reference it.
  3. An ICLA on file with the ASF, if you haven't submitted one already, given the size of the contribution.
  4. The dependency order of the stacked PRs (I see this one and 8155), so reviewers know where to start.

One small question: a commit message refers to "critic findings PR1-B1 through PR1-B5". Could you share where that review lives, so the context is available to everyone?

Once the dev@ thread has settled and this is marked ready for review, I'll be glad to go through it in detail. Thanks again, and welcome to the community!

@gouthamaenugu

Copy link
Copy Markdown
Author

Thank you for the warm welcome and for approving the CI workflows, @JinwooHwang!

Here's where each of those items stands:

  1. dev@geode.apache.org design thread: I've just posted a [DISCUSS] thread ("[DISCUSS] Native HNSW Vector Indexing and Distributed Hybrid Search in geode-lucene for Geode 2.1") covering the public API shape, serialization/wire compatibility impact, and how the four draft PRs fit together.
  2. JIRA ticket: My ASF Jira account (gouthamaenugu) is now active. Once the dev@ thread settles on whether to track this under one umbrella GEODE ticket with subtasks or individual linked tickets, I'll file the ticket(s) and update the PR titles and squashed commits to reference them.
  3. ASF ICLA: I am preparing and submitting my ICLA to secretary@apache.org now.
  4. PR dependency & recommended review order:

On "critic findings PR1-B1 through PR1-B5" in commit 8a38329976: Those were labels from my own local pre-submission hardening checklist (not an external/private review). For full public context, the five items addressed in that commit were:

  • PR1-B1: VectorIndexMetadata ObjectInputFilter safety — serialize similarityFunctionName as a String instead of the third-party Lucene enum and enforce invariants in readObject.
  • PR1-B2: FlatFormatSerializer support for top-level and nested vector fields.
  • PR1-B3: Race-free ClassValue<ConcurrentHashMap<...>> field lookup cache in VectorFieldMapper.
  • PR1-B4: Defensive float[] copy on extraction plus float32 COSINE norm overflow/underflow validation.
  • PR1-B5: Reject duplicate vector field registrations and text/vector field-name collisions in LuceneIndexFactoryImpl.

When squashing the branch to reference the JIRA ticket before marking ready for review, I'll make sure the final commit message is completely self-contained without internal checklist labels. I'm also looking into the integrationTest failure from the CI run you enabled. Thanks again!

@JinwooHwang

Copy link
Copy Markdown
Contributor

Thanks for the thorough update, @gouthamaenugu, and for clarifying the PR1-B1 through B5 labels. Let's settle the JIRA structure on the dev@ thread, and take your time with the integrationTest failure.
Looking forward to the discussion on the list.

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.

2 participants