Repository navigation
GEODE-vector-pr2: Add Dual-Epoch Tier-0 Vector Delta Buffer and Distributed Hybrid k-NN Function - #8156
Draft
gouthamaenugu wants to merge 15 commits into
Draft
GEODE-vector-pr2: Add Dual-Epoch Tier-0 Vector Delta Buffer and Distributed Hybrid k-NN Function#8156gouthamaenugu wants to merge 15 commits into
gouthamaenugu wants to merge 15 commits into
Conversation
added 9 commits
November 21, 2026 04:01
…hybrid k-NN function - Add per-bucket lock-free dual-epoch (E_active, E_flushing) Tier0VectorDeltaBuffer with stamped epochs/sequences, writer quiescence on atomic flush swap, strict post-commit/maybeRefreshBlocking flush completion, tombstone/override masking, and cardinality/epoch metrics. - Add SIMD-friendly unrolled VectorSimilarityScorer matching Lucene 9.12.3 VectorSimilarityFunction score semantics (COSINE, DOT_PRODUCT, EUCLIDEAN, MAXIMUM_INNER_PRODUCT) and Tier0MetadataMatcher for unified filter predicates. - Add Tier0VectorRegistry and Tier0VectorBucketListener for synchronous bucket capture, rebalancing lifecycle, and commitAndRefreshBlocking flush coordination. - Add DistributedHybridKnnFunction and HybridKnnQueryContext executing per-primary-bucket pre-filtered KnnFloatVectorQuery unioned with Tier-0 under highest-epoch precedence and reduced via TopEntriesCollectorManager / TopEntriesFunctionCollector. - Add comprehensive unit tests and multi-bucket DUnit tests covering dual-epoch concurrency, zero visibility gap, 1%/5%/50% filtered selectivity, concurrent writes, and bucket rebalancing.
- PR2-B1: Wire Tier0VectorRegistry cleanup on index destroy (LuceneIndexImpl.destroy, LuceneServiceImpl.destroyIndex/destroyDefinedIndex/destroyIndexes), region destroy (LuceneServiceImpl.beforeRegionDestroyed/cleanupFailedInitialization, Tier0VectorBucketListener.afterRegionDestroy), and cache close (LuceneServiceImpl.close). - PR2-B2 & PR2-B5: Harden Tier0MetadataMatcher to evaluate TermRangeQuery, WildcardQuery, PrefixQuery, RegexpQuery, AutomatonQuery, TermInSetQuery, BoostQuery, ConstantScoreQuery, MatchNoDocsQuery; decode 1D PointRangeQuery strictly by enclosing Lucene point class (IntPoint/FloatPoint/LongPoint/DoublePoint); return false on pure-MUST_NOT/empty BooleanQuery; and fail closed on unsupported query subclasses and non-1D point queries. - PR2-B3: Run Tier0VectorBucketListener.afterPrimary with pdxReadSerializedOverride=true using EntrySnapshot.getRawValue(true) and lock-free Tier0VectorDeltaBuffer.putIfAbsent so hydration never deserializes PDX domain classes or resurrects concurrent afterDestroy tombstones. - PR2-B4: Pin active epoch and evict from both E_active and E_flushing in evictCommitted, and guard abortFlush with a monotonic clear generation so concurrent clear() can never have entries resurrected. - Add reproducing unit tests (Tier0MetadataMatcherParityJUnitTest, Tier0VectorLifecycleAndBucketListenerJUnitTest, Tier0VectorDeltaBufferJUnitTest concurrency stress tests) and DUnit test destroyAndRecreateIndexClearsTier0AndLeaksZeroStaleEntries.
…ush() and |T_mask| capping - Harden Tier0VectorDeltaBuffer.snapshot() to read E_flushing strictly before E_active and re-validate volatile stateRef against concurrent beginFlush(), abortFlush() (which restores E_flushing -> E_active strictly before clearing E_flushing), and clear() generation resets so migrating entries are never missed. - Cap inline MUST_NOT mask terms in DistributedHybridKnnFunction by Math.min(MAX_INLINE_MASK_TERMS, Math.max(0, IndexSearcher.getMaxClauseCount() - 2)) before falling back to bounded oversampling. - Add 10,000-iteration multi-threaded concurrency stress test snapshotNeverMissesLiveEntriesAcrossTenThousandBeginAndAbortFlushIterations.
…ter flush fallback - Add per-bucket promotion hydration barrier (beginHydration/awaitHydration/completeHydration) in Tier0VectorRegistry wired into Tier0VectorBucketListener.afterPrimary and DistributedHybridKnnFunction.executeOnBucket so concurrent reads wait briefly until primary bucket hydration populates Tier0VectorDeltaBuffer, closing mid-failover RAW gaps. - Add Tier0MetadataMatcher.isSupported(Query) recursive AST check and automatic synchronous bucket flush + commitAndRefreshBlocking fallback in DistributedHybridKnnFunction when an unsupported filter (e.g., FuzzyQuery/SpanQuery) encounters non-empty Tier-0, tracked via unsupportedFilterFlushFallbackCount telemetry, eliminating silent fail-closed drops. - Add reproducing unit tests (Tier0MetadataMatcherParityJUnitTest, Tier0VectorLifecycleAndBucketListenerJUnitTest, DistributedHybridKnnFunctionJUnitTest) and multi-VM DUnit test unsupportedFuzzyFilterQueryFlushesTier0AndReturnsFreshWritesWithoutSilentDrops.
…g path telemetry - Add rerankOversampleFactor (default 1 = disabled, validated in [1, 64]) to HybridKnnQueryContext and update sanctioned-geode-lucene-serializables.txt. - Add default queryWithFp32Rerank(...) on IndexRepository and implement it on IndexRepositoryImpl using per-leaf ascending ScoreDoc ordering for monotonic FloatVectorValues.advance(docInLeaf), scoring raw FP32 .vec vectors with VectorSimilarityScorer and returning top-k hits. - Wire DistributedHybridKnnFunction.executeOnBucket(...) to invoke queryWithFp32Rerank(...) when rerankOversampleFactor > 1 while preserving masked-key exclusions and Tier-0 union precedence. - Add server-side masking path telemetry counters (INLINE_MASK_QUERY_COUNT, OVERSAMPLE_FALLBACK_QUERY_COUNT, resetMaskTelemetry, and mirrored counters on Tier0VectorRegistry). - Add reproducing unit tests for >3*B_max concurrent partial-drain RAW visibility (Tier0VectorDeltaBufferJUnitTest), SQ8 FP32 reranking over multi-leaf 256-D Lucene99HnswScalarQuantizedVectorsFormat, and inline vs oversample mask telemetry (DistributedHybridKnnFunctionJUnitTest).
…d clamp deserialized rerankOversampleFactor
…nt reconciliation and strict iso-efS rerankBeamCandidates
… and AEQ-delta ordering/telemetry - Add evictionVersion seqlock + evictionLock fallback in Tier0VectorDeltaBuffer.snapshot() alongside (epoch, sequence) precedence and in-compute sequence allocation so stale E_flushing tombstones never mask evicted newer live recreations or concurrent puts. - Add per-bucket pathBBarrierLock in Tier0VectorDeltaBuffer and hold writeLock across Path-B unsupported-filter flush, snapshot(), and IndexSearcher acquisition (IndexRepository/IndexRepositoryImpl onSearcherAcquired hook), reading BucketRegion VM entries lock-free first in readRegionValueForFlush to prevent AB-BA deadlocks. - Harden AEQ-delta shadow-event ordering by (shadowKey, timestamp, shadowBucket < tempQueue) and expose lastHydrationEventsInspected / lastHydrationKeysRestored on Tier0VectorRegistry. - Add deterministic JUnit and multi-VM DUnit regression tests.
…on, and flush telemetry
4 of 6 tasks
added 6 commits
November 25, 2026 10:53
…and promotion fallback live-key tests
…rtial AEQ promotion gap
…dence and Path-A seq binding
…cket buffers across retries, and prevent Path-B abortFlush deadlock - Extract acquireSearcher and acquireSearcherAtEpoch in IndexRepositoryImpl so searcherManager.acquire precedes post-acquire searcherEpoch validation across executeQuery and executeQueryWithFp32Rerank, releasing mismatched searchers cleanly and enforcing expectedEpoch on the k<=0 guard. - Add resolveBucketBuffer and acquireLatestPathBWriteBarrier in DistributedHybridKnnFunction to re-await promotion hydration and rebind across demotion/re-promotion retries and Path-B barriers, extract query helpers, and avoid holding pathBWrite across in-flight flush backoff so completeFlush/abortFlush cannot livelock. - Add deterministic JUnit tests in DistributedHybridKnnFunctionJUnitTest covering abortFlush epoch binding on both query paths, re-promotion retry rebinding, and Path-B barrier non-deadlock.
…ss Path A and Path B - Track a monotonic, ABA-free per-bucket ownershipGeneration in Tier0VectorRegistry advanced on every afterPrimary/hydration, afterSecondary, afterBucketRemoved, removeIndex, removeRegion, and clearAll transition (plus LuceneBucketListener.afterPrimary and Tier0PartitionListener.afterPrimary), and add ownershipFenceRetryCount telemetry plus pinned flushBuffer helper. - Remove pathBBarrierLock.readLock() from Tier0VectorDeltaBuffer.clear() (retaining evictionLock/generation/SEALED_BIT synchronization) so bucket deposition callbacks cannot deadlock against an in-flight Path-B write barrier. - Validate ownershipGeneration, local primary ownership (BucketAdvisor.isPrimary), buffer identity, !isHydrating, and !repo.isClosed both before snapshot() and immediately after IndexSearcher acquisition on Path A (optimistic and contention fallback) and Path B (unsupported-filter write barrier), failing over via PrimaryBucketException on permanent demotion or refreshing repo/buffer/generation on local re-promotion. - Add deterministic JUnit and 3-VM DUnit tests (inFlightReadInvalidatesAndRetriesAcrossBucketDemotionAndRePromotion) plus lifecycle monotonicity unit test.
…d explicit retry-exhaustion abort - Add a canonical per-bucket single-flight ReentrantLock (flushLock) in Tier0VectorRegistry shared with Tier0VectorDeltaBuffer, held across LuceneEventListener AEQ read/update/commitAndRefreshBlocking/evictCommitted and Tier0VectorRegistry.flushBuffer beginFlush/update/commitAndRefreshBlocking/completeFlush/abortFlush so competing flushers can never interleave IndexWriter writes, commits, refreshes, evictions, or aborts. - Strictly preserve lock hierarchy (flushLock -> pathBBarrierLock -> evictionLock): flushBuffer acquires flushLock non-blockingly via tryLock() when pathBWrite is held, and DistributedHybridKnnFunction.flushBucketForUnsupportedFilter releases pathBWrite while waiting on flushLock before re-validating ownershipGeneration. - Add explicit retry-exhaustion abort exits (PrimaryBucketException -> InternalFunctionInvocationTargetException) across ownership retries, Path-A odd-epoch/contention wait exhaustion, Path-B flush wait exhaustion, and post-loop !cutCompleted guard so executeOnBucket never falls through to merge an unvalidated cut. - Add deterministic JUnit tests covering retry exhaustion (ownership, odd epoch, Path-B stuck flush), AEQ vs Path-B single-flight serialization + abortFlush serialization, and canonical flushLock sharing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR 2: Dual-Epoch Tier-0 Vector Delta Buffer and Distributed Hybrid k-NN Function
feature/GEODE-vector-pr2-hybrid-knndevelop(46643af515)7229bcc2bdc274916ce4f124fb68cf79ba18e7fe(21 files changed, +13484 / -19)geode-lucene(Apache Geode 2.1, bundled Apache Lucene9.12.3)For all changes, please confirm:
GEODE-*JIRA ticket assignment and commit prefix update.)develop)?.vecreranking & masking path telemetry, sparse-leafFloatVectorValues.advanceguard & symmetric deserialization clamp, AEQ-delta promotion hydration withdeleteIfAbsent& strict iso-efSrerankBeamCandidates, snapshot seqlock fence + Path-B write barrier + AEQ-delta shadow ordering/telemetry, cross-tiersearcherEpochfence + stale-index reconciliation + true flush-cycle telemetry, atomic Tier-0mutationVersionoverlay snapshot fence + promotion fallback live-key overwrite/delete-recreate coverage, pre-pin two-writer snapshot race closure + unconditional post-AEQ full-bucket reconciliation, sequence-fenced authoritative promotion precedence + Path-A payload-to-seq binding, epoch-bound searcher acquisition + retry buffer rebinding + non-deadlocking Path-B abortFlush backoff, monotonic ABA-free per-bucketownershipGenerationfence across Path A and Path B, and canonical per-bucket single-flightflushLock+ explicit retry-exhaustion abort exits — ready to squash on upstream submission.)gradlew buildrun cleanly? (Verified:geode-lucene:spotlessCheck,:geode-lucene:checkPom,:geode-lucene:javadoc,:geode-lucene:test --rerun,:geode-lucene:distributedTest --tests "*HybridKnn*" --rerun, and:geode-lucene:integrationTest --tests "*AnalyzeLuceneSerializablesIntegrationTest*" --rerun.)9.12.3.)Summary / Motivation
Geode's
geode-luceneindex updates flow asynchronously through anAsyncEventQueue(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, andSearcherManager.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:searcherEpochFence: Dual-epochTier0VectorDeltaBuffercaptures puts, updates, and tombstones immediately on the primary bucket viaTier0VectorBucketListenerand retires them only after AEQ flush + Lucene commit + searcher refresh.LuceneEventListener.processcapturesseqBeforeRead = eventBuffer.getKeySequence(key)strictly BEFOREgetValue(region.getEntry(key))reads the live region payload soevictCommittednever evicts newer overlay writes.snapshot()verifies(active.writerState.get() & WRITER_MASK) == 0BEFORE readingm1 = mutationVersion.get()and validatesactiveWriterStateAfter == 0beforem2, whileinsertIfAbsent,recordMutation, andrestoreEntryToActiveincrementmutationVersionboth before and after mutatingactive.entriesinside the writer pin—paired withIndexRepositorysearcherEpochvalidation (tryQueryAtEpoch/tryQueryWithFp32RerankAtEpoch) across Tier-0 and Tier-1.Tier0MetadataMatcherevaluates LuceneQuerypredicates over buffered Tier-0 entries with exact parity against LuceneIndexSearcher(includingTermRangeQuery,WildcardQuery,PrefixQuery,RegexpQuery,AutomatonQuery,TermInSetQuery, 1DPointRangeQuery,BooleanQuery,BoostQuery,ConstantScoreQuery, andMatchNoDocsQuery). Unsupported queries (e.g.,FuzzyQuery/SpanQuery) acquire the per-bucketpathBBarrierLockwrite lock across flush, snapshot, andIndexSearcheracquisition soT_maskis guaranteed empty at the searcher cut. On primary promotion,Tier0VectorBucketListener.afterPrimaryseeds provisional AEQ deltas (DeltaEntry.provisionalHydration=true) viatryHydrateFromAeqDeltaAND unconditionally runs sequence-fencedputIfSequenceBefore(..., 0L)/deleteIfSequenceBefore(..., 0L)inhydrateFromFullBucketScanso authoritativebucketlive entries, tombstones, and stale Lucene docs (collectIndexedKeysIfReady() \ liveKeySet) ALWAYS overwrite conflicting provisional AEQ state while preserving concurrent liverecordPut/recordDestroyentries (!provisionalHydration && seq >= 1).DistributedHybridKnnFunctionexecutes per-bucket filtered k-NN across both Tier-0 and Tier-1 (Lucene HNSW), handles tombstone masking with adaptive oversampling fallback, supports exact FP32.vecreranking (both oversampledSQ8+RRkand strict iso-efSearchrerankBeamCandidatesatrerankOversampleFactor=1), and merges per-bucket top-k results across the cluster.Key Changes
Tier-0 Dual-Epoch Delta Buffer, Pre-Pin Seqlock Fence & Sequence-Fenced Authoritative Promotion
Tier0VectorDeltaBuffer(org.apache.geode.cache.lucene.internal.vector):E_active/E_flushing) map usingSEALED_BITpinning so concurrent writes never block flush handoff andevictCommitted(...)cleans both epochs without stranding entries.evictionVersion+mutationVersion): IncrementsmutationVersionBOTH before and after mutatingactive.entriesinside the writer pin inrecordMutation(),insertIfAbsent(), andrestoreEntryToActive(), guardsbeginFlush(),completeFlush(), andabortFlush()withpathBBarrierLock.readLock()(pathBBarrierLock -> evictionLockorder everywhere;clear()synchronizes onevictionLock/generation/SEALED_BITwithout takingpathBBarrierLock.readLock()so bucket deposition callbacks cannot deadlock against an in-flight Path-B write barrier), and drains sealedE_flushingwriters ininsertIfAbsent(). Optimisticsnapshot()requires(v1 & 1) == 0 && (active.writerState.get() & WRITER_MASK) == 0BEFORE readingm1 = mutationVersion, scansE_flushingthenE_active, readsactiveWriterStateAfterBEFOREm2, and validatesv1 == v2 && m1 == m2 && after.active == active && after.flushing == flushing && (activeWriterStateAfter & WRITER_MASK) == 0, falling back topathBBarrierLock.writeLock() -> synchronized (evictionLock)when contended. Enforces(epoch, sequence)precedence (DeltaEntry.isNewerThan) so olderE_flushingputs never mask newerE_activedeletes (tombstonedKeys&maskedKeys).nextSequence(),putIfSequenceBefore(..., maxExclusiveSeq),deleteIfSequenceBefore(..., maxExclusiveSeq), package-private provisional AEQ helpers (putProvisionalIfAbsent/deleteProvisionalIfAbsent), andDeltaEntry.provisionalHydration.shouldOverwriteEntryoverwrites absent,provisionalHydration, orseq < maxExclusiveSeqentries across(E_active, E_flushing)while preserving non-provisional live mutations (!provisionalHydration && seq >= maxExclusiveSeq).pathBBarrierLock): Uses a per-bucketReentrantReadWriteLock(readLockonput/destroy/putIfAbsent/deleteIfAbsent/evictCommitted/beginFlush/completeFlush/abortFlush;writeLockvialockPathBWrite()/unlockPathBWrite()across unsupported-filter flush ->snapshot()->IndexSearcheracquisition).Tier0VectorRegistry,Tier0VectorBucketListener,PartitionedRepositoryManager, &LuceneEventListener:ownershipGeneration(getOwnershipGeneration,advanceOwnershipGeneration,ownershipFenceRetryCount, pinnedflushBuffer) advanced on everyafterPrimary,afterSecondary,afterBucketRemoved,beginHydration,completeHydration,removeBucket,removeIndex,removeRegion, andclearAlltransition, plus a canonical per-bucket single-flightReentrantLock(getBucketFlushLockshared withTier0VectorDeltaBuffer.getFlushLock), hooking intoPartitionedRepositoryManager,LuceneBucketListener,LuceneEventListener,IndexRepositoryImpl,LuceneIndexImpl, andLuceneServiceImpl.flushLock& Path-A Payload-to-Seq Binding:LuceneEventListener.processgroups events byIndexRepositoryand holdsflushLockacross the entire bucket cycle (awaitHydration -> seqBeforeRead = buffer.getKeySequence(key)strictly BEFOREgetValue(region.getEntry(key))->repo.update/delete->repo.commitAndRefreshBlocking()->buffer.evictCommitted(committedKeySeqs)), whileTier0VectorRegistry.flushBufferholds the sameflushLockacrossbeginFlush -> update/delete -> commitAndRefreshBlocking -> completeFlush/abortFlush(preserving lock hierarchyflushLock -> pathBBarrierLock -> evictionLockvia non-blockingflushLock.tryLock()whenpathBWriteis held), preventing competing flushers from interleaving commits, refreshes, evictions, or aborts and ensuringevictCommitted(k -> seqBeforeRead)never drops a newer post-read overlay put or destroy (seq2 > seq1).removeIndex,removeRegion,removeCache) acrossdestroyIndex,destroyDefinedIndex,destroyIndexes,beforeRegionDestroyed,afterRegionDestroy,cleanupFailedInitialization, andcloseso destroy/recreate cycles leak zero stale entries.afterPrimaryremoves thebucket.isEmpty()early return, enforcessetPdxReadSerializedOverride(true)(restored infinally), and performs provisional AEQ-delta hydration + unconditional sequence-fenced authoritative reconciliation:tryHydrateFromAeqDeltapopulates provisional AEQ entries (provisionalHydration=true) fromAsyncEventQueueImpl->ParallelGatewaySenderQueue/ConcurrentParallelGatewaySenderQueueusingShadowEventRecordordering (effectiveShadowKey,timestamp,shadowBucket=0 < tempQueue=1,orderIndex), andhydrateFromFullBucketScanunconditionally runs sequence-fencedputIfSequenceBefore(..., 0L)/deleteIfSequenceBefore(..., 0L)over (1)bucket.keySet(), (2)bucket.getRegionMap().regionEntries()(re.isTombstone()), and (3)PartitionedRepositoryManager.collectIndexedKeysIfReady(bucketId) \ liveKeySetso authoritative bucket state ALWAYS overwrites conflicting provisional AEQ state while preserving concurrent liverecordPut/recordDestroyentries (!provisionalHydration && seq >= 1).FlushCycleRing/FlushCycleSample):Tier0VectorRegistryprovides bounded per-bucketrecordFlushCycle,drainFlushCycleSamples, andsetFlushCycleSamplingEnabled(zero overhead when disabled), populated byLuceneEventListener.processwith(batchSize, preEvictTier0Size, flushDurationNanos).beginHydration/awaitHydration/completeHydrationwired in bothDistributedHybridKnnFunctionandLuceneEventListener) and records hydration telemetry counters (hydratedKeysCount,hydratedTombstonesCount,aeqDeltaHydrationCount,fullScanHydrationCount,lastHydrationEventsInspected,lastHydrationKeysRestored,reconciledStaleIndexKeysCount).Metadata Filtering, Cross-Tier
searcherEpochValidation & Distributed Query ExecutionTier0MetadataMatcher&VectorSimilarityScorer:KnnFloatVectorQueryacrossCOSINE,DOT_PRODUCT, andEUCLIDEAN.Tier0MetadataMatcher.isSupported(Query)recursive AST checking; decodes 1DPointRangeQuerystrictly by enclosing Lucene point class (IntPoint/FloatPoint/LongPoint/DoublePoint), rejectsNaN, returnsfalseon empty or pure-MUST_NOTBooleanQuery(matching LuceneIndexSearcher), and fails closed (false) on unsupported query subclasses or multi-dimensional point queries.DistributedHybridKnnFunction,HybridKnnQueryContext, &IndexRepository/IndexRepositoryImpl:searcherEpoch, BucketownershipGenerationFence & Explicit Retry-Exhaustion Abort:IndexRepositoryImplmaintainsAtomicLong searcherEpoch(incrementingeven -> oddbeforewriter.commit()andodd -> evenaftersearcherManager.maybeRefreshBlocking()/maybeRefresh()inside synchronizedcommit()/commitAndRefreshBlocking()) and implementsgetSearcherEpoch(),tryQueryAtEpoch(...),tryQueryWithFp32RerankAtEpoch(...), andcollectIndexedKeys(), extractingacquireSearcher/acquireSearcherAtEpochacross bothexecuteQueryandexecuteQueryWithFp32ReranksosearcherManager.acquire()precedes post-acquiresearcherEpochvalidation (releasing mismatched searchers cleanly and checkingexpectedEpochon thek <= 0 || oversampleK <= 0guard).DistributedHybridKnnFunctionwraps Path A (optimistic + contention fallback) and Path B (unsupported-filter write barrier) in an outer ownership-fence retry loop (MAX_OWNERSHIP_FENCE_RETRIES=16) validatingownershipGeneration == expectedGen, local primary ownership (BucketAdvisor.isPrimary()),!isHydrating,getBuffer == expectedBuffer, and!repo.isClosed()BOTH beforesnapshot()AND immediately afterIndexSearcheracquisition (insideonSearcherAcquired, beforesearcher.search()and while holdingpathBWriteon Path B), failing over viaPrimaryBucketException->InternalFunctionInvocationTargetExceptionon permanent demotion, ownership retry exhaustion, Path-A odd-epoch/contention wait exhaustion, Path-B flush-wait exhaustion, and an explicit post-loopif (!cutCompleted)guard (never falling through to merge an unvalidated cut), or refreshingrepo/buffer/ownershipGenerationon local re-promotion..vecreranking viaIndexRepository.queryWithFp32Rerank(...)/IndexRepositoryImpl: supports bothrerankOversampleFactorin[1, 64](default1) andrerankBeamCandidates(boolean)(isRerankBeamCandidates()), so whenrerankOversampleFactor == 1 && rerankBeamCandidates == true(SQ8+RR-iso),queryK = luceneK(strict iso-efSearch with zero beam inflation) still executesrepo.queryWithFp32Rerank(...)over HNSW beam candidates. Groups hits per leaf in ascending docID order for monotonicFloatVectorValues.advance(...), rescores raw FP32 vectors viaVectorSimilarityScorer, and returns top-k.pathBBarrierLockwrite lock viaacquireLatestPathBWriteBarrieracrossflushBucketForUnsupportedFilter(readingBucketRegion.getRegionEntrylock-free in VM before fault-in viareadRegionValueForFlushto prevent AB-BA deadlocks withRegionMapPut/Destroy, and releasingpathBWritewhile waiting onflushLockor in-flight flush backoff before re-validatingownershipGenerationsocompleteFlush/abortFlush/AEQ flush cannot livelock),snapshot(), andIndexSearcheracquisition (onSearcherAcquiredcallback onIndexRepository.query/queryWithFp32RerankvalidatingownershipGenerationand local primary ownership underpathBWrite), releasing the write lock cleanly viafinallyonce the searcher cut is acquired soT_maskis guaranteed empty and concurrent matching overwrites are never dropped.INLINE_MASK_QUERY_COUNT,OVERSAMPLE_FALLBACK_QUERY_COUNT,unsupportedFilterFlushFallbackCount, andownershipFenceRetryCounttelemetry counters.New Unit & Distributed Tests (66 Unit + 15 DUnit)
Tier0VectorDeltaBufferJUnitTest(23 tests): dual-epoch concurrency stress (put/evict/flush/abort/clear), atomicdeleteIfAbsenttombstone insertion without overwriting concurrent live post-promotion puts or flushing entries, sequence-fencedputIfSequenceBefore/deleteIfSequenceBeforeoverwriting stale entries while preserving post-fence live writes, no-commit two-keymutationVersiontorn-cut fencing including deterministic pre-pinned two-writer schedule (snapshotNoCommitPreventsTwoKeyTornCut,snapshotNoCommitConcurrentTwoKeyScheduleNeverExposesOldXNewY,snapshotNoCommitPrePinnedTwoWritersNeverExposesOldXNewY), olderE_flushingput vs newerE_activedelete resolution, deterministic snapshot seqlock fencing againstevictCommittedandcompleteFlushmid-snapshot plus 1,500-cycle evict-and-recreate churn stress, 10,000-iteration concurrentsnapshot()vsbeginFlush()/abortFlush()zero-miss stress test,> 3 * B_maxconcurrent 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 LuceneIndexSearcher, cross-type 1DPointRangeQuerydecoding, pure-MUST_NOTboolean behavior, and fail-closed checks.Tier0VectorLifecycleAndBucketListenerJUnitTest(17 tests): deterministic concurrent promotion hydration barrier test, PDX read-serialized override without domain deserialization, Path-AevictCommittedpreserving post-read overlay puts/destroys (pathAFlushDoesNotEvictNewerOverlayPutWrittenAfterPayloadRead), primary AEQ-delta hydration reconciling uncommitted puts and pre-crash tombstones inO(|AEQ_b|), authoritative bucket overwriting conflicting provisional AEQ state while preserving post-promotion live writes, out-of-order same-keyShadowEventRecord&tempQueuetiebreak resolution, partial non-empty AEQ unconditional reconciliation of missing overwrites, inserts, deletes, and expired tombstones, empty-bucket pre-crash tombstone hydration,RegionMaptombstone fallback scan on empty buckets, fallback reconciliation of stale indexed keys with missing AEQ and expired region tombstones, fallback live-key reconciliation across acknowledged overwrites, unindexed inserts, and delete-recreates,LuceneEventListenertrue flush-cycle sample recording & disabled flag behavior, primary hydration tombstone safety, full registry cleanup on destroy/close, ABA-freeownershipGenerationstrict monotonicity across lifecycle transitions, and canonicalflushLocksharing betweenTier0VectorRegistryandTier0VectorDeltaBuffer(bucketFlushLockSharedBetweenRegistryAndDeltaBuffer).DistributedHybridKnnFunctionJUnitTest(21 tests): multi-bucket union, tombstone masking, oversampling fallback, server-side inline vs oversample mask telemetry counters, SQ8 multi-leaf 256-D exact FP32.vecreranking recall & score parity, strict iso-efSearchrerankBeamCandidatesFP32 rerank without beam inflation, supported-filtersearcherEpochvalidation preventing two-key torn cuts +abortFlushconsistent-cut binding across both query paths + 16-retry write-barrier fallback + re-promotion retry buffer rebinding, deterministic bucket demotion/re-promotion ownership fence invalidation & retry across Path A (rerankBeam=false/truewith unchangedsearcherEpoch), Path B (FuzzyQueryunderpathBWritewith zero deadlock), and permanent demotion failover, explicit retry-exhaustion abort throws across ownership/stuck odd epoch/Path-B stuck flush (retryExhaustionThrowsInsteadOfMergingUnvalidatedCut), single-flightflushLockserialization across AEQ commit/evict vs Path-B flush/abort preventing stalev1overwritingv2with zero deadlock (singleFlightFlushLockSerializesAeqCommitEvictAndPathBFlushAbort), Path-B write-barrier lock acrossonSearcherAcquiredblocking concurrent overwrites/recreations + non-deadlock against in-flightabortFlush+ exception cleanup +IndexRepositoryImplsearcher hook ordering, sparse/mixed-leafFloatVectorValues.advancemonotonicity guard under-ea, symmetricrerankOversampleFactordeserialization clamp, flush/abort error handling, and end-to-endFuzzyQueryunsupported-filter flush-and-refresh fallback verification.DistributedHybridKnnFunctionDistributedTest(15 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 onevictCommitted, failover same-keyput->destroy->recreate&put->destroywithlastHydrationEventsInspected/lastHydrationKeysRestoredtelemetry, promotion overwriting conflicting AEQ state with authoritative bucket live entries and tombstones and draining cleanly, supported-filtersearcherEpochpreventing two-key torn cuts across servers, 3-VM in-flight read ownership-generation invalidation & retry across bucket demotion/re-promotion on Path A and Path B (inFlightReadInvalidatesAndRetriesAcrossBucketDemotionAndRePromotion), promotion stale Lucene doc reconciliation with missing AEQ and expired tombstone yielding zero ghosts, promotion fallback with missing AEQ covering live overwrites, unindexed inserts, and delete-recreates, partial non-empty AEQ on promotion reconciling missing acked overwrites, inserts, and deletes, Path-BFuzzyQueryzero dropped matching entries under concurrent overwrites, destroy/recreate zero-leak verification, and multi-VMFuzzyQueryunsupported-filter flush-and-refresh fallback with paused AEQ.Backward Compatibility & Serialization Notes
org.apache.geode.cache.lucene.internal.*. ExistingIndexRepositoryandLuceneBucketListeneradditions are internal interfaces/hooks that do not alter existing lexical query or AEQ behavior when no Tier-0 vector buffer is registered.DistributedHybridKnnFunctionandHybridKnnQueryContext(includingrerankBeamCandidates:boolean, and usingsimilarityFunctionName: Stringrather than third-party Lucene enums forObjectInputFiltercompatibility) insanctioned-geode-lucene-serializables.txt, verified viaAnalyzeLuceneSerializablesIntegrationTest(6/6 PASS).Exact Gradle Verification Commands & Pass Counts
:geode-lucene:test --rerun:geode-lucene:distributedTest --tests "*HybridKnn*" --rerun(DistributedHybridKnnFunctionDistributedTest)AnalyzeLuceneSerializablesIntegrationTest:geode-lucene:spotlessCheck,:checkPom,:javadoc