Skip to content

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
apache:developfrom
gouthamaenugu:feature/GEODE-vector-pr2-hybrid-knn
Draft

gouthamaenugu wants to merge 15 commits into
apache:developfrom
gouthamaenugu:feature/GEODE-vector-pr2-hybrid-knn

Conversation

@gouthamaenugu

@gouthamaenugu gouthamaenugu commented Nov 24, 2026 •

Copy link
Copy Markdown

PR 2: Dual-Epoch Tier-0 Vector Delta Buffer and Distributed Hybrid k-NN Function

  • Draft PR: #8156
  • Branch: feature/GEODE-vector-pr2-hybrid-knn
  • Base: develop (46643af515)
  • Head Commit: 7229bcc2bdc274916ce4f124fb68cf79ba18e7fe (21 files changed, +13484 / -19)
  • 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 15 clean logical commits — feature implementation, review 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, AEQ-delta promotion hydration with deleteIfAbsent & strict iso-efS rerankBeamCandidates, snapshot seqlock fence + Path-B write barrier + AEQ-delta shadow ordering/telemetry, cross-tier searcherEpoch fence + stale-index reconciliation + true flush-cycle telemetry, atomic Tier-0 mutationVersion overlay 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-bucket ownershipGeneration fence across Path A and Path B, and canonical per-bucket single-flight flushLock + explicit retry-exhaustion abort exits — 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, :geode-lucene:distributedTest --tests "*HybridKnn*" --rerun, and :geode-lucene:integrationTest --tests "*AnalyzeLuceneSerializablesIntegrationTest*" --rerun.)
  • Have you written or updated unit tests to verify your changes? (66 new unit tests across 4 JUnit suites + 15 multi-node DUnit tests.)
  • 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

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, Path-A Seq Binding & Cross-Tier searcherEpoch Fence: 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. LuceneEventListener.process captures seqBeforeRead = eventBuffer.getKeySequence(key) strictly BEFORE getValue(region.getEntry(key)) reads the live region payload so evictCommitted never evicts newer overlay writes. snapshot() verifies (active.writerState.get() & WRITER_MASK) == 0 BEFORE reading m1 = mutationVersion.get() and validates activeWriterStateAfter == 0 before m2, while insertIfAbsent, recordMutation, and restoreEntryToActive increment mutationVersion both before and after mutating active.entries inside the writer pin—paired with IndexRepository searcherEpoch validation (tryQueryAtEpoch / tryQueryWithFp32RerankAtEpoch) across Tier-0 and Tier-1.
  2. Exact Filter Parity, Path-B Barrier & Sequence-Fenced Authoritative Promotion: 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). Unsupported queries (e.g., FuzzyQuery/SpanQuery) acquire the per-bucket pathBBarrierLock write lock across flush, snapshot, and IndexSearcher acquisition so T_mask is guaranteed empty at the searcher cut. On primary promotion, Tier0VectorBucketListener.afterPrimary seeds provisional AEQ deltas (DeltaEntry.provisionalHydration=true) via tryHydrateFromAeqDelta AND unconditionally runs sequence-fenced putIfSequenceBefore(..., 0L) / deleteIfSequenceBefore(..., 0L) in hydrateFromFullBucketScan so authoritative bucket live entries, tombstones, and stale Lucene docs (collectIndexedKeysIfReady() \ liveKeySet) ALWAYS overwrite conflicting provisional AEQ state while preserving concurrent live recordPut/recordDestroy entries (!provisionalHydration && seq >= 1).
  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, Pre-Pin Seqlock Fence & Sequence-Fenced Authoritative Promotion

  • 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.
    • Atomic Pre-Pin Overlay Snapshot Fence (evictionVersion + mutationVersion): Increments mutationVersion BOTH before and after mutating active.entries inside the writer pin in recordMutation(), insertIfAbsent(), and restoreEntryToActive(), guards beginFlush(), completeFlush(), and abortFlush() with pathBBarrierLock.readLock() (pathBBarrierLock -> evictionLock order everywhere; clear() synchronizes on evictionLock/generation/SEALED_BIT without taking pathBBarrierLock.readLock() so bucket deposition callbacks cannot deadlock against an in-flight Path-B write barrier), and drains sealed E_flushing writers in insertIfAbsent(). Optimistic snapshot() requires (v1 & 1) == 0 && (active.writerState.get() & WRITER_MASK) == 0 BEFORE reading m1 = mutationVersion, scans E_flushing then E_active, reads activeWriterStateAfter BEFORE m2, and validates v1 == v2 && m1 == m2 && after.active == active && after.flushing == flushing && (activeWriterStateAfter & WRITER_MASK) == 0, falling back to pathBBarrierLock.writeLock() -> synchronized (evictionLock) when contended. Enforces (epoch, sequence) precedence (DeltaEntry.isNewerThan) so older E_flushing puts never mask newer E_active deletes (tombstonedKeys & maskedKeys).
    • Sequence-Fenced Promotion & Provisional Hydration: Exposes nextSequence(), putIfSequenceBefore(..., maxExclusiveSeq), deleteIfSequenceBefore(..., maxExclusiveSeq), package-private provisional AEQ helpers (putProvisionalIfAbsent / deleteProvisionalIfAbsent), and DeltaEntry.provisionalHydration. shouldOverwriteEntry overwrites absent, provisionalHydration, or seq < maxExclusiveSeq entries across (E_active, E_flushing) while preserving non-provisional live mutations (!provisionalHydration && seq >= maxExclusiveSeq).
    • Per-Bucket Path-B Write Barrier (pathBBarrierLock): Uses a per-bucket ReentrantReadWriteLock (readLock on put/destroy/putIfAbsent/deleteIfAbsent/evictCommitted/beginFlush/completeFlush/abortFlush; writeLock via lockPathBWrite() / unlockPathBWrite() across unsupported-filter flush -> snapshot() -> IndexSearcher acquisition).
  • Tier0VectorRegistry, Tier0VectorBucketListener, PartitionedRepositoryManager, & LuceneEventListener:
    • Tracks per-index, per-bucket Tier-0 buffers plus a monotonic, ABA-free per-bucket ownershipGeneration (getOwnershipGeneration, advanceOwnershipGeneration, ownershipFenceRetryCount, pinned flushBuffer) advanced on every afterPrimary, afterSecondary, afterBucketRemoved, beginHydration, completeHydration, removeBucket, removeIndex, removeRegion, and clearAll transition, plus a canonical per-bucket single-flight ReentrantLock (getBucketFlushLock shared with Tier0VectorDeltaBuffer.getFlushLock), hooking into PartitionedRepositoryManager, LuceneBucketListener, LuceneEventListener, IndexRepositoryImpl, LuceneIndexImpl, and LuceneServiceImpl.
    • Single-Flight flushLock & Path-A Payload-to-Seq Binding: LuceneEventListener.process groups events by IndexRepository and holds flushLock across the entire bucket cycle (awaitHydration -> seqBeforeRead = buffer.getKeySequence(key) strictly BEFORE getValue(region.getEntry(key)) -> repo.update/delete -> repo.commitAndRefreshBlocking() -> buffer.evictCommitted(committedKeySeqs)), while Tier0VectorRegistry.flushBuffer holds the same flushLock across beginFlush -> update/delete -> commitAndRefreshBlocking -> completeFlush/abortFlush (preserving lock hierarchy flushLock -> pathBBarrierLock -> evictionLock via non-blocking flushLock.tryLock() when pathBWrite is held), preventing competing flushers from interleaving commits, refreshes, evictions, or aborts and ensuring evictCommitted(k -> seqBeforeRead) never drops a newer post-read overlay put or destroy (seq2 > seq1).
    • 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 provisional AEQ-delta hydration + unconditional sequence-fenced authoritative reconciliation: tryHydrateFromAeqDelta populates provisional AEQ entries (provisionalHydration=true) from AsyncEventQueueImpl -> ParallelGatewaySenderQueue / ConcurrentParallelGatewaySenderQueue using ShadowEventRecord ordering (effectiveShadowKey, timestamp, shadowBucket=0 < tempQueue=1, orderIndex), and hydrateFromFullBucketScan unconditionally runs sequence-fenced putIfSequenceBefore(..., 0L) / deleteIfSequenceBefore(..., 0L) over (1) bucket.keySet(), (2) bucket.getRegionMap().regionEntries() (re.isTombstone()), and (3) PartitionedRepositoryManager.collectIndexedKeysIfReady(bucketId) \ liveKeySet so authoritative bucket state ALWAYS overwrites conflicting provisional AEQ state while preserving concurrent live recordPut/recordDestroy entries (!provisionalHydration && seq >= 1).
    • True Flush-Cycle Telemetry (FlushCycleRing / FlushCycleSample): Tier0VectorRegistry provides bounded per-bucket recordFlushCycle, drainFlushCycleSamples, and setFlushCycleSamplingEnabled (zero overhead when disabled), populated by LuceneEventListener.process with (batchSize, preEvictTier0Size, flushDurationNanos).
    • 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, lastHydrationEventsInspected, lastHydrationKeysRestored, reconciledStaleIndexKeysCount).

Metadata Filtering, Cross-Tier searcherEpoch Validation & 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, & IndexRepository / IndexRepositoryImpl:
    • Cross-Tier searcherEpoch, Bucket ownershipGeneration Fence & Explicit Retry-Exhaustion Abort: IndexRepositoryImpl maintains AtomicLong searcherEpoch (incrementing even -> odd before writer.commit() and odd -> even after searcherManager.maybeRefreshBlocking() / maybeRefresh() inside synchronized commit() / commitAndRefreshBlocking()) and implements getSearcherEpoch(), tryQueryAtEpoch(...), tryQueryWithFp32RerankAtEpoch(...), and collectIndexedKeys(), extracting acquireSearcher / acquireSearcherAtEpoch across both executeQuery and executeQueryWithFp32Rerank so searcherManager.acquire() precedes post-acquire searcherEpoch validation (releasing mismatched searchers cleanly and checking expectedEpoch on the k <= 0 || oversampleK <= 0 guard). DistributedHybridKnnFunction wraps Path A (optimistic + contention fallback) and Path B (unsupported-filter write barrier) in an outer ownership-fence retry loop (MAX_OWNERSHIP_FENCE_RETRIES=16) validating ownershipGeneration == expectedGen, local primary ownership (BucketAdvisor.isPrimary()), !isHydrating, getBuffer == expectedBuffer, and !repo.isClosed() BOTH before snapshot() AND immediately after IndexSearcher acquisition (inside onSearcherAcquired, before searcher.search() and while holding pathBWrite on Path B), failing over via PrimaryBucketException -> InternalFunctionInvocationTargetException on permanent demotion, ownership retry exhaustion, Path-A odd-epoch/contention wait exhaustion, Path-B flush-wait exhaustion, and an explicit post-loop if (!cutCompleted) guard (never falling through to merge an unvalidated cut), or refreshing repo/buffer/ownershipGeneration on local re-promotion.
    • 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.
    • Path-B unsupported-filter queries acquire the latest re-hydrated bucket buffer's pathBBarrierLock write lock via acquireLatestPathBWriteBarrier across flushBucketForUnsupportedFilter (reading BucketRegion.getRegionEntry lock-free in VM before fault-in via readRegionValueForFlush to prevent AB-BA deadlocks with RegionMapPut/Destroy, and releasing pathBWrite while waiting on flushLock or in-flight flush backoff before re-validating ownershipGeneration so completeFlush/abortFlush/AEQ flush cannot livelock), snapshot(), and IndexSearcher acquisition (onSearcherAcquired callback on IndexRepository.query / queryWithFp32Rerank validating ownershipGeneration and local primary ownership under pathBWrite), releasing the write lock cleanly via finally once the searcher cut is acquired so T_mask is guaranteed empty and concurrent matching overwrites are never dropped.
    • Tracks server-side INLINE_MASK_QUERY_COUNT, OVERSAMPLE_FALLBACK_QUERY_COUNT, unsupportedFilterFlushFallbackCount, and ownershipFenceRetryCount telemetry counters.

New Unit & Distributed Tests (66 Unit + 15 DUnit)

  • Tier0VectorDeltaBufferJUnitTest (23 tests): dual-epoch concurrency stress (put/evict/flush/abort/clear), atomic deleteIfAbsent tombstone insertion without overwriting concurrent live post-promotion puts or flushing entries, sequence-fenced putIfSequenceBefore/deleteIfSequenceBefore overwriting stale entries while preserving post-fence live writes, no-commit two-key mutationVersion torn-cut fencing including deterministic pre-pinned two-writer schedule (snapshotNoCommitPreventsTwoKeyTornCut, snapshotNoCommitConcurrentTwoKeyScheduleNeverExposesOldXNewY, snapshotNoCommitPrePinnedTwoWritersNeverExposesOldXNewY), older E_flushing put vs newer E_active delete resolution, deterministic snapshot seqlock fencing against evictCommitted and completeFlush mid-snapshot plus 1,500-cycle evict-and-recreate churn stress, 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 (17 tests): deterministic concurrent promotion hydration barrier test, PDX read-serialized override without domain deserialization, Path-A evictCommitted preserving post-read overlay puts/destroys (pathAFlushDoesNotEvictNewerOverlayPutWrittenAfterPayloadRead), primary AEQ-delta hydration reconciling uncommitted puts and pre-crash tombstones in O(|AEQ_b|), authoritative bucket overwriting conflicting provisional AEQ state while preserving post-promotion live writes, out-of-order same-key ShadowEventRecord & tempQueue tiebreak resolution, partial non-empty AEQ unconditional reconciliation of missing overwrites, inserts, deletes, and expired tombstones, empty-bucket pre-crash tombstone hydration, RegionMap tombstone 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, LuceneEventListener true flush-cycle sample recording & disabled flag behavior, primary hydration tombstone safety, full registry cleanup on destroy/close, ABA-free ownershipGeneration strict monotonicity across lifecycle transitions, and canonical flushLock sharing between Tier0VectorRegistry and Tier0VectorDeltaBuffer (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 .vec reranking recall & score parity, strict iso-efSearch rerankBeamCandidates FP32 rerank without beam inflation, supported-filter searcherEpoch validation preventing two-key torn cuts + abortFlush consistent-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/true with unchanged searcherEpoch), Path B (FuzzyQuery under pathBWrite with zero deadlock), and permanent demotion failover, explicit retry-exhaustion abort throws across ownership/stuck odd epoch/Path-B stuck flush (retryExhaustionThrowsInsteadOfMergingUnvalidatedCut), single-flight flushLock serialization across AEQ commit/evict vs Path-B flush/abort preventing stale v1 overwriting v2 with zero deadlock (singleFlightFlushLockSerializesAeqCommitEvictAndPathBFlushAbort), Path-B write-barrier lock across onSearcherAcquired blocking concurrent overwrites/recreations + non-deadlock against in-flight abortFlush + exception cleanup + IndexRepositoryImpl searcher hook ordering, 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 (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 on evictCommitted, failover same-key put->destroy->recreate & put->destroy with lastHydrationEventsInspected / lastHydrationKeysRestored telemetry, promotion overwriting conflicting AEQ state with authoritative bucket live entries and tombstones and draining cleanly, supported-filter searcherEpoch preventing 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-B FuzzyQuery zero dropped matching entries under concurrent overwrites, 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

./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*" --rerun

./gradlew --no-daemon --max-workers=2 \
  :geode-lucene:integrationTest \
  --tests "*AnalyzeLuceneSerializablesIntegrationTest*" --rerun
Verification Suite Total Passed Failed Skipped Status
:geode-lucene:test --rerun 349 345 0 4 (pre-existing) PASS
PR 2 Unit Test Suites (subset of above: 21 + 5 + 23 + 17) 66 66 0 0 PASS
:geode-lucene:distributedTest --tests "*HybridKnn*" --rerun (DistributedHybridKnnFunctionDistributedTest) 15 15 0 0 PASS
AnalyzeLuceneSerializablesIntegrationTest 6 6 0 0 PASS
:geode-lucene:spotlessCheck, :checkPom, :javadoc — — 0 — PASS

Goutham 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.
Goutham added 6 commits November 25, 2026 10:53
…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.
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.

1 participant