gouthamaenugu opened a new pull request, #8156:
URL: https://github.com/apache/geode/pull/8156

   # PR 2: Dual-Epoch Tier-0 Vector Delta Buffer and Distributed Hybrid k-NN 
Function
   
   - **Branch:** `gouthamaenugu:feature/GEODE-vector-pr2-hybrid-knn`
   - **Base:** `apache:develop` (`46643af515`)
   - **Head Commit:** `c11b6a01b5460fbecb39d083bd7d33be3c7eeab8` (`21 files 
changed, +7513 / -1`)
   - **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 7 
clean logical commits — feature implementation, critic hardening, 
snapshot/abortFlush concurrency hardening, promotion hydration barrier & 
unsupported-filter fallback, optional FP32 `.vec` reranking & masking path 
telemetry, sparse-leaf `FloatVectorValues.advance` guard & symmetric 
deserialization clamp, and AEQ-delta promotion hydration with `deleteIfAbsent` 
reconciliation & strict iso-efS `rerankBeamCandidates` — 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`, 
`:geode-lucene:distributedTest --tests "*HybridKnn*"`, and 
`AnalyzeLuceneSerializablesIntegrationTest` 6/6.)*
   - [x] Have you written or updated unit tests to verify your changes? *(38 
new unit tests across 4 JUnit suites + 7 multi-node DUnit tests.)*
   - [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
   
   Geode's `geode-lucene` index updates flow asynchronously through an 
`AsyncEventQueue` (AEQ) before committing to region-backed Lucene HNSW 
segments. Under concurrent ingestion, this creates a read-after-write 
visibility gap where recently written or deleted vectors are invisible (or 
stale) until AEQ flush, commit, and `SearcherManager.maybeRefreshBlocking()` 
complete.
   
   This PR introduces a lock-free dual-epoch Tier-0 in-memory vector delta 
buffer (`E_active` / `E_flushing`) paired with a distributed hybrid k-NN 
function (`DistributedHybridKnnFunction`) that unions fresh Tier-0 vectors with 
committed Lucene HNSW segments while masking deleted/superseded keys:
   1. **Zero Read-After-Write Visibility Gap:** Dual-epoch 
`Tier0VectorDeltaBuffer` captures puts, updates, and tombstones immediately on 
the primary bucket via `Tier0VectorBucketListener` and retires them only after 
AEQ flush + Lucene commit + searcher refresh.
   2. **Exact Filter Parity:** `Tier0MetadataMatcher` evaluates Lucene `Query` 
predicates over buffered Tier-0 entries with exact parity against Lucene 
`IndexSearcher` (including `TermRangeQuery`, `WildcardQuery`, `PrefixQuery`, 
`RegexpQuery`, `AutomatonQuery`, `TermInSetQuery`, 1D `PointRangeQuery`, 
`BooleanQuery`, `BoostQuery`, `ConstantScoreQuery`, and `MatchNoDocsQuery`).
   3. **Bucket-Aligned Distributed Hybrid Execution & Iso-efS FP32 Reranking:** 
`DistributedHybridKnnFunction` executes per-bucket filtered k-NN across both 
Tier-0 and Tier-1 (Lucene HNSW), handles tombstone masking with adaptive 
oversampling fallback, supports exact FP32 `.vec` reranking (both oversampled 
`SQ8+RRk` and strict iso-efSearch `rerankBeamCandidates` at 
`rerankOversampleFactor=1`), and merges per-bucket top-k results across the 
cluster.
   
   ---
   
   ## Key Changes
   
   ### Tier-0 Dual-Epoch Delta Buffer & AEQ-Delta Promotion Hydration
   - **`Tier0VectorDeltaBuffer`** 
(`org.apache.geode.cache.lucene.internal.vector`):
     - Lock-free dual-epoch (`E_active` / `E_flushing`) map using `SEALED_BIT` 
pinning so concurrent writes never block flush handoff and 
`evictCommitted(...)` cleans both epochs without stranding entries.
     - Exposes atomic `putIfAbsent(...)` and `deleteIfAbsent(K key)` sharing a 
unified `insertIfAbsent(...)` CAS path (pin-before-seq, skipping if `flushing` 
contains `key`, inserting via `computeIfAbsent` without overwriting concurrent 
live post-promotion puts).
     - Monotonic `generation` and `lastClearedEpoch` guards in `abortFlush` / 
`completeFlush` ensure concurrent `clear()` calls can never resurrect cleared 
entries; `snapshot()` reads `E_flushing` strictly before `E_active` and 
re-validates volatile `stateRef` against concurrent `beginFlush()` / 
`abortFlush()` / `clear()` so migrating entries are never missed.
     - Reverse-epoch precedence (`E_active` -> `E_flushing` -> Tier-1 Lucene) 
with tombstone masking for deleted or overwritten keys.
   - **`Tier0VectorRegistry`**, **`Tier0VectorBucketListener`**, & 
**`LuceneEventListener`**:
     - Tracks per-index, per-bucket Tier-0 buffers and hooks into 
`PartitionedRepositoryManager`, `LuceneBucketListener`, `LuceneEventListener`, 
`IndexRepositoryImpl`, `LuceneIndexImpl`, and `LuceneServiceImpl`.
     - Enforces full registry cleanup (`removeIndex`, `removeRegion`, 
`removeCache`) across `destroyIndex`, `destroyDefinedIndex`, `destroyIndexes`, 
`beforeRegionDestroyed`, `afterRegionDestroy`, `cleanupFailedInitialization`, 
and `close` so destroy/recreate cycles leak zero stale entries.
     - `afterPrimary` removes the `bucket.isEmpty()` early return, enforces 
`setPdxReadSerializedOverride(true)` (restored in `finally`), and performs 
**AEQ-delta promotion hydration**: inspects Lucene's `AsyncEventQueueImpl` 
(`LuceneServiceImpl.getUniqueIndexName(indexName, pr.getFullPath())`) -> 
`ParallelGatewaySenderQueue` / `ConcurrentParallelGatewaySenderQueue` shadow 
bucket + temp queue for uncommitted `GatewaySenderEventImpl` puts and 
destroys/invalidates (reconciling tombstones via `deleteIfAbsent` and live 
entries via `putIfAbsent` in `O(|AEQ_b|)` so committed keys drain cleanly on 
`evictCommitted`), with fallback scanning `bucket.keySet()` + 
`bucket.getRegionMap().regionEntries()` (`re.isTombstone()` -> 
`deleteIfAbsent`).
     - Coordinates readers and AEQ flush via a per-bucket promotion hydration 
barrier (`beginHydration` / `awaitHydration` / `completeHydration` wired in 
both `DistributedHybridKnnFunction` and `LuceneEventListener`) and records 
hydration telemetry counters (`hydratedKeysCount`, `hydratedTombstonesCount`, 
`aeqDeltaHydrationCount`, `fullScanHydrationCount`).
   
   ### Metadata Filtering, Similarity Scoring & Distributed Query Execution
   - **`Tier0MetadataMatcher`** & **`VectorSimilarityScorer`**:
     - Evaluates Lucene metadata filter queries over Tier-0 buffered attributes 
with score equivalence to `KnnFloatVectorQuery` across `COSINE`, `DOT_PRODUCT`, 
and `EUCLIDEAN`.
     - Exposes `Tier0MetadataMatcher.isSupported(Query)` recursive AST 
checking; decodes 1D `PointRangeQuery` strictly by enclosing Lucene point class 
(`IntPoint`/`FloatPoint`/`LongPoint`/`DoublePoint`), rejects `NaN`, returns 
`false` on empty or pure-`MUST_NOT` `BooleanQuery` (matching Lucene 
`IndexSearcher`), and fails closed (`false`) on unsupported query subclasses or 
multi-dimensional point queries.
   - **`DistributedHybridKnnFunction`** & **`HybridKnnQueryContext`** 
(`org.apache.geode.cache.lucene.internal.distributed`):
     - Cluster-wide `Function` executing bucket-local hybrid k-NN (awaiting any 
in-flight primary hydration, unioning Tier-0 + Lucene `KnnFloatVectorQuery` 
with inline masked-key filtering and oversampling fallback when masked keys 
exceed the inline threshold, tracked via server-side `INLINE_MASK_QUERY_COUNT` 
/ `OVERSAMPLE_FALLBACK_QUERY_COUNT` telemetry counters mirrored on 
`Tier0VectorRegistry`).
     - Exact FP32 `.vec` reranking via 
`IndexRepository.queryWithFp32Rerank(...)` / `IndexRepositoryImpl`: supports 
both `rerankOversampleFactor` in `[1, 64]` (default `1`) and 
`rerankBeamCandidates(boolean)` (`isRerankBeamCandidates()`), so when 
`rerankOversampleFactor == 1 && rerankBeamCandidates == true` (`SQ8+RR-iso`), 
`queryK = luceneK` (strict iso-efSearch with zero beam inflation) still 
executes `repo.queryWithFp32Rerank(...)` over HNSW beam candidates. Groups hits 
per leaf in ascending docID order for monotonic 
`FloatVectorValues.advance(...)`, rescores raw FP32 vectors via 
`VectorSimilarityScorer`, and returns top-`k`.
     - Automatically triggers a synchronous bucket flush + 
`commitAndRefreshBlocking()` fallback (tracked via 
`unsupportedFilterFlushFallbackCount`) whenever 
`!Tier0MetadataMatcher.isSupported(filterQuery)` encounters non-empty Tier-0 
entries (e.g., `FuzzyQuery`/`SpanQuery`), eliminating silent fail-closed drops.
   
   ### New Unit & Distributed Tests (38 Unit + 7 DUnit)
   - `Tier0VectorDeltaBufferJUnitTest` (15 tests): dual-epoch concurrency 
stress (`put`/`evict`/`flush`/`abort`/`clear`), atomic `deleteIfAbsent` 
tombstone insertion without overwriting concurrent live post-promotion puts or 
flushing entries, 10,000-iteration concurrent `snapshot()` vs 
`beginFlush()`/`abortFlush()` zero-miss stress test, `> 3 * B_max` concurrent 
partial-drain RAW visibility stress test, zero visibility gap, tombstone 
masking, and score equivalence across all similarity functions.
   - `Tier0MetadataMatcherParityJUnitTest` (5 tests): `isSupported(Query)` AST 
classification, ground-truth parity against Lucene `IndexSearcher`, cross-type 
1D `PointRangeQuery` decoding, pure-`MUST_NOT` boolean behavior, and 
fail-closed checks.
   - `Tier0VectorLifecycleAndBucketListenerJUnitTest` (8 tests): deterministic 
concurrent promotion hydration barrier test, PDX read-serialized override 
without domain deserialization, primary AEQ-delta hydration reconciling 
uncommitted puts and pre-crash tombstones in `O(|AEQ_b|)`, empty-bucket 
pre-crash tombstone hydration, `RegionMap` tombstone fallback scan on empty 
buckets, primary hydration tombstone safety, and full registry cleanup on 
destroy/close.
   - `DistributedHybridKnnFunctionJUnitTest` (10 tests): multi-bucket union, 
tombstone masking, oversampling fallback, server-side inline vs oversample mask 
telemetry counters, SQ8 multi-leaf 256-D exact FP32 `.vec` reranking recall & 
score parity, strict iso-efSearch `rerankBeamCandidates` FP32 rerank without 
beam inflation, sparse/mixed-leaf `FloatVectorValues.advance` monotonicity 
guard under `-ea`, symmetric `rerankOversampleFactor` deserialization clamp, 
flush/abort error handling, and end-to-end `FuzzyQuery` unsupported-filter 
flush-and-refresh fallback verification.
   - `DistributedHybridKnnFunctionDistributedTest` (7 DUnit tests): 
read-after-write visibility before AEQ flush, filtered selectivity regimes (1%, 
5%, 50%), concurrent writes + continuous queries, bucket rebalancing recall 
parity, failover AEQ-delta hydration reconciling pre-crash tombstones with zero 
ghosts and draining `|T_mask|` to zero on `evictCommitted`, destroy/recreate 
zero-leak verification, and multi-VM `FuzzyQuery` unsupported-filter 
flush-and-refresh fallback with paused AEQ.
   
   ---
   
   ## Backward Compatibility & Serialization Notes
   
   - **Zero Public API Breakage:** All new classes reside under 
`org.apache.geode.cache.lucene.internal.*`. Existing `IndexRepository` and 
`LuceneBucketListener` additions are internal interfaces/hooks that do not 
alter existing lexical query or AEQ behavior when no Tier-0 vector buffer is 
registered.
   - **Sanctioned Serializables:** Registered `DistributedHybridKnnFunction` 
and `HybridKnnQueryContext` (including `rerankBeamCandidates:boolean`, and 
using `similarityFunctionName: String` rather than third-party Lucene enums for 
`ObjectInputFilter` compatibility) in 
`sanctioned-geode-lucene-serializables.txt`, verified via 
`AnalyzeLuceneSerializablesIntegrationTest` (6/6 PASS).
   
   ---
   
   ## 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:distributedTest --tests "*HybridKnn*"
   
   ./gradlew --no-daemon --max-workers=2 \
     :geode-lucene:integrationTest \
     --tests "*AnalyzeLuceneSerializablesIntegrationTest*"
   ```
   
   | Verification Suite | Total | Passed | Failed | Skipped | Status |
   | :--- | ---: | ---: | ---: | ---: | :--- |
   | `:geode-lucene:test --rerun` | 321 | 317 | 0 | 4 *(pre-existing)* | 
**PASS** |
   | PR 2 Unit Test Suites (subset of above) | 38 | 38 | 0 | 0 | **PASS** |
   | `:geode-lucene:distributedTest --tests "*HybridKnn*"` 
(`DistributedHybridKnnFunctionDistributedTest`) | 7 | 7 | 0 | 0 | **PASS** |
   | `AnalyzeLuceneSerializablesIntegrationTest` | 6 | 6 | 0 | 0 | **PASS** |
   | `:geode-lucene:spotlessCheck`, `:checkPom`, `:javadoc` | — | — | 0 | — | 
**PASS** |
   


-- 
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]

Reply via email to