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

gouthamaenugu wants to merge 29 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: 41316b8c9e87ae9228b6df69b9fea9724830dee6 (23 files changed, +21548 / -17)
  • 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 29 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, canonical per-bucket single-flight flushLock + explicit retry-exhaustion abort exits, immutable DeltaEntry.regionValue binding eliminating Path-A/Path-B publication-window races, Path-A pre-pin fence + monotonic committedKeySequences stale-AEQ regression rejection + post-commit/pre-refresh recovery, primary-crash replicate-before-pin overwrite & delete promotion-adoption verification, committed-sequence hydration fence rejecting stale promotion-scan installs after new-term flush & eviction, unified promotion hydration sequence guard (PROVISIONAL_HYDRATION_SEQUENCE = 0L vs LIVE_SEQUENCE_START = 1L) + Path-B full drain > B_max across commit/refresh aborts, unconditional Path-B mask/snapshot reset + atomic evictionLock cross-epoch E_flushing seal-to-commit hydration fence, RegionEntry-synchronized hydration reads + t_hyd promotion cut linearization at hydrationLatch release + chained second-promotion verification, unconditional Path-A stale-AEQ drop guard before boundEntry lookup across live overwrites and tombstones, primary-crash verification at the backup-replication-to-recordPut/recordDestroy boundary for overwrite & destroy across two chained rf=2 promotions, two-tier global cross-promotion vs. ownership-term-local linearizability specification with explicit inter-promotion read & pre-recovery rollback-boundary verification, Theorem 2(1) observable read contract documentation, History Class G/L cross-promotion partition, and fully-replicated unpinned write & VersionTag recovery ordering verification, deterministic Tier-0 (score DESC, key ASC) tie-break fix + per-codec merge semantics & Path-B non-blocking flushLock.tryLock() drop-and-retry lock-order documentation + arbitrary rf >= 2 Class G/L partition generalization + 3-backup partial-subset & Path-B contention/demotion/post-commit-pre-refresh abort verification, exhaustive FP32 pre-truncation (score DESC, key ASC) base collector (exhaustiveFp32 / executeQueryExhaustiveFp32) + 1-visible-doc-per-key invariant docs + Class G sufficiency/observable-rollback Javadoc & acked-overwrite supersession verification, and shared canonical total key order (CanonicalKeyOrder) across Tier-0/Lucene FP32/final merge + injective keyTerm & shared FP32 scorer bit-identity documentation + full abstract bucket state M(t) Class G/L observations-through-absence specification & reference-oracle tests — 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? (88 new unit tests across 4 JUnit suites + 21 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, Immutable Payload Binding, Path-A Pre-Pin/Stale-AEQ Fences & Cross-Tier searcherEpoch Fence: Dual-epoch Tier0VectorDeltaBuffer captures puts (with immutable DeltaEntry.regionValue), updates, and tombstones immediately on the primary bucket via Tier0VectorBucketListener, tracks monotonic per-key committedKeySequences and canonical (membershipID, realThreadID, sequenceID) pinnedEventSequences, and retires entries only after AEQ flush + Lucene commit + searcher refresh. Under per-bucket single-flight flushLock, LuceneEventListener.process eliminates unfenced empty-buffer fallbacks on Tier-0-managed buckets: unpinned AEQ events defer cleanly (return false) until Tier-0 pins them (preventing pre-linearization publication), pinned entries index strictly immutable DeltaEntry payloads and advance committedKeySequences atomically before evictCommittedEntries, and delayed stale AEQ events with pinnedSeq <= maxCommittedSequence(k) are dropped without overwriting Lucene; Path B drains strictly immutable FlushBatch<K> payloads sealed by beginFlush(). 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) and per-bucket ownershipGeneration fencing across Tier-0 and Tier-1.
  2. Exact Filter Parity, Path-B Barrier & Unified 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 and drain both E_active and E_flushing completely until buffer.getTotalSize() == 0 && !buffer.isFlushing() across flush, snapshot, and IndexSearcher acquisition so T_mask is guaranteed empty at the searcher cut even with > B_max pending keys. On primary promotion, Tier0VectorBucketListener.afterPrimary seeds provisional AEQ deltas at PROVISIONAL_HYDRATION_SEQUENCE = 0L via tryHydrateFromAeqDelta AND unconditionally runs sequence-fenced putIfSequenceBefore(..., LIVE_SEQUENCE_START) / deleteIfSequenceBefore(..., LIVE_SEQUENCE_START) (LIVE_SEQUENCE_START = 1L) in hydrateFromFullBucketScan so authoritative bucket live entries, tombstones, and stale Lucene docs (collectIndexedKeysIfReady() \ liveKeySet) ALWAYS overwrite conflicting provisional AEQ state (seq < 1L) while preserving concurrent live or already-committed new-term mutations (seq >= 1L or committedKeySequences >= 1L).
  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).
    • Unified Sequence-Fenced Promotion & Atomic Cross-Epoch evictionLock Hydration Fence: Defines PROVISIONAL_HYDRATION_SEQUENCE = 0L (stamped by putProvisionalIfAbsent / deleteProvisionalIfAbsent without advancing sequenceGenerator) vs LIVE_SEQUENCE_START = 1L (stamped by live mutations and authoritative bucket-scan installs), removing any separate provisionalHydration shadow flag. insertOrOverwrite wraps pin + cross-epoch (E_flushing, committedKeySequences, E_active) check-and-install atomically inside synchronized (evictionLock) (strictly after pathBBarrierLock.readLock(), preserving lock hierarchy flushLock -> pathBBarrierLock -> evictionLock -> active.writerState) and enforces the single unified predicate (existing == null || existing.sequence < maxExclusiveSeq) && !isBlockedByCommittedSequence(key, maxExclusiveSeq) alongside checking stateRef.get().flushing inside active.entries.compute(key, ...) — so a delayed hydration scan resuming in the beginFlush seal-to-commit window deterministically observes sealed E_flushing entries (or advanced committedKeySequences >= 1L if completeFlush acquired evictionLock first) and rejects stale installs (-1L), while completeFlush merges only seq > 0L into committedKeySequences and clear() is invoked exclusively by Tier0VectorRegistry strictly after detaching the buffer and advancing ownershipGeneration.
    • 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.
    • Immutable DeltaEntry Payload Binding, Monotonic committedKeySequences & Canonical Event-ID Tracking (getEntry, evictCommittedEntries, pinnedEventSequences): Extends DeltaEntry<K> with private final Object regionValue (getRegionValue()) populated directly by Tier0VectorBucketListener from event.getNewValue() (and authoritative bucket values on promotion hydration); tracks per-key committedKeySequences (getMaxCommittedSequence, recordCommittedSequence) updated atomically under flushLock + evictionLock strictly BEFORE clearing/evicting in completeFlush(long), evictCommitted, and evictCommittedEntries across puts, overwrites, deletes, and recreations (never advanced on abortFlush); and normalizes EventID via ThreadIdentifier.getRealThreadID(id.getThreadID()) into pinnedEventSequences / nonVectorEventIds (publishing eventId -> seq strictly after E_active installation and releasing via acknowledgeEventIds only after a batch returns true, bounding memory to O(|AEQ_b|)).
    • Single-Flight flushLock, Path-A Pre-Pin/Stale-AEQ Fences & Post-Commit/Pre-Refresh Recovery: On Tier-0-managed buckets (Tier0VectorRegistry.markIndexManaged/isIndexManaged), LuceneEventListener.process holds flushLock across the entire bucket cycle and eliminates unfenced empty-buffer fallbacks: (1) unpinned AEQ events (pinnedSeq < 0L or buffer == null) defer cleanly (deferredUnpinnedAeqEventsCount, returning false for AEQ retry without writing to Lucene or bumping searcherEpoch), (2) strictly before buffer.getEntry(k), delayed stale AEQ events (eventId != null && maxCommittedSeq > 0L && pinnedSeq <= maxCommittedSeq) are dropped unconditionally (staleAeqEventsDroppedCount, zero Lucene writes/commits, live Tier-0 entry undisturbed, preserving seq == 0L provisional shadow events when maxCommittedSeq == 0L), and (3) pinned boundEntry entries verify boundEntry.getSequence() > maxCommittedSeq (and pinnedSeq >= boundEntry.getSequence() on legacy metadata-only fallback), bind strictly immutable boundEntry (DeltaEntry.regionValue/tombstone), commit & blocking-refresh, advance committedKeySequences, and call buffer.evictCommittedEntries(committedEntries) without regressing Lucene across overwrites or tombstones. Tier0VectorRegistry.flushBuffer holds the same flushLock across beginFlush -> update/delete -> commitAndRefreshBlocking -> completeFlush/abortFlush (flushLock -> pathBBarrierLock -> evictionLock), and interruption after IndexWriter.commit() before maybeRefreshBlocking() / eviction restores even searcherEpoch, keeps w_1 visible in E_active (masking Lucene via T_mask), and drains cleanly to 0 on retry.
    • 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), synchronizes each bucket-entry/tombstone read on its per-key RegionEntry monitor (synchronized (re), released strictly before putIfSequenceBefore/deleteIfSequenceBefore so hydration never observes an un-replicated local write prior to UpdateOperation.startOperation() / distributeDestroyOperation() and every scan-observed write survives subsequent chained promotions), and performs provisional AEQ-delta hydration + unconditional sequence-fenced authoritative reconciliation: tryHydrateFromAeqDelta populates provisional AEQ entries (PROVISIONAL_HYDRATION_SEQUENCE = 0L) from AsyncEventQueueImpl -> ParallelGatewaySenderQueue / ConcurrentParallelGatewaySenderQueue using ShadowEventRecord ordering (effectiveShadowKey, timestamp, shadowBucket=0 < tempQueue=1, orderIndex), and hydrateFromFullBucketScan unconditionally runs sequence-fenced putIfSequenceBefore(..., LIVE_SEQUENCE_START) / deleteIfSequenceBefore(..., LIVE_SEQUENCE_START) (1L) 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 (seq == 0L) while preserving concurrent live or already-committed new-term mutations (seq >= 1L or committedKeySequences >= 1L), linearizing the promotion cut at t_hyd immediately before completeHydration releases hydrationLatch.
    • 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 and optimistic-retry fallbacks unconditionally reset tier0Snapshot = null and maskedKeys = Collections.emptySet() strictly before entering acquireLatestPathBWriteBarrier / flushBucketForUnsupportedFilter (guaranteeing zero stale S_live/T_mask carryover even when the buffer is already empty after an epoch mismatch), loop inside flushBucketForUnsupportedFilter until BOTH E_active and E_flushing are completely empty (buffer.getTotalSize() == 0 && !buffer.isFlushing())—draining strictly immutable entry.getRegionValue() already sealed inside FlushBatch<K> from beginFlush() without touching live mutable BucketRegion.getEntry(k) or acquiring RegionEntry locks; while holding pathBBarrierLock.writeLock(), Tier0VectorRegistry.flushBuffer acquires flushLock strictly via non-blocking flushLock.tryLock() (never blocking, preserving zero AB-BA lock-order inversion against Path A's flushLock -> pathBBarrierLock.readLock -> evictionLock), dropping pathBWrite immediately on contention to back off in bounded <= 10 ms slices before re-acquiring pathBWrite and re-validating ownershipGeneration (aborting cleanly via PrimaryBucketException if demoted during retry, and preserving non-regressing Tier-0 visibility via abortFlush + monotonic searcherEpoch on post-commit/pre-refresh abort)—then execute snapshot() and IndexSearcher acquisition (onSearcherAcquired 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 (even with > B_max pending keys or after a commit/refresh abort) and concurrent matching overwrites are never dropped.
    • Introduces shared canonical total key ordering (CanonicalKeyOrder.compareCanonicalKeys, SCORE_DESC_KEY_ASC, WORST_FIRST) comparing (k.getClass().getName(), String.valueOf(k)) with an unsigned SerializerUtil.toKeyTerm(k).bytes() tie-break fallback (null first, so Integer(1) < Long(1L) < String("1") never collide), wired identically across all 4 stages (Tier0VectorDeltaBuffer.Snapshot.search, IndexRepositoryImpl.executeQueryExhaustiveFp32, IndexRepositoryImpl.executeQueryWithFp32Rerank, and DistributedHybridKnnFunction.SCORE_DESC_COMPARATOR), paired with an explicit exhaustiveFp32 mode (HybridKnnQueryContext.exhaustiveFp32(boolean), IndexRepository.queryExhaustiveFp32 / tryQueryExhaustiveFp32AtEpoch, and IndexRepositoryImpl.executeQueryExhaustiveFp32) scanning every eligible live doc across all LeafReaderContext leaves via a bounded k' min-heap ordered by CanonicalKeyOrder.WORST_FIRST before base top-k' truncation, documented injective SerializerUtil.toKeyTerm key domain + 1-visible-doc-per-key Lucene invariant (writer.updateDocuments/delete + APPLY_ALL_DELETES=true so oversampling by k' = k + |T_mask| is strictly sufficient across multi-leaf indexes), and bit-identical shared VectorSimilarityScorer FP32 kernels (scoreBatch vs score) pre- and post-flush.
    • Tracks server-side INLINE_MASK_QUERY_COUNT, OVERSAMPLE_FALLBACK_QUERY_COUNT, unsupportedFilterFlushFallbackCount, and ownershipFenceRetryCount telemetry counters.
    • Documents per-codec Theorem 2(1) observable read & merge semantics (strict exact FP32 top-k with pre-truncation canonical (score DESC, key ASC) for exhaustiveFp32; unified FP32 scale cut-consistent visibility for SQ8+RR-iso/RR-m and unquantized FP32 HNSW ANN; cut-consistent cross-tier visibility for plain SQ8), exact Path-B lock order, 1-visible-doc-per-key invariant, and arbitrary rf >= 2 (S subseteq P(b)) History Class G vs. Class L defined uniformly over full abstract bucket state M(t): K -> (V x Meta) U {bot} and query dependence r = Q_{F,k}(M(t_r)) (covering live hits, tombstones/bot, filter exclusions, top-k omissions, and observations through absence across both partially replicated creates and partially replicated destroys — unconditionally covering 100% of acknowledged writes, 100% of fully-replicated unpinned writes S = P(b) with zero re-replication, pre-hydration recovery, and acked-overwrite/destroy supersession) in Tier0VectorDeltaBuffer, DistributedHybridKnnFunction, Tier0VectorRegistry, Tier0VectorBucketListener, SerializerUtil, and VectorSimilarityScorer Javadoc.

New Unit & Distributed Tests (88 Unit + 21 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 seq == 0L provisional entries while preserving seq >= 1L 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 seq == 0L provisional AEQ state with seq >= 1L 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 (43 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, deterministic (score DESC, key ASC) tie-break ordering across Tier-0 and hybrid merge when > k entries tie (deterministicTieBreakOrdersEqualScoresByKeyAscendingAcrossTier0AndMerge), exhaustive FP32 pre-truncation (score DESC, key ASC) across multi-leaf (>= 2 leaves) 1-live-doc-per-key Lucene base + Tier-0 proving exhaustiveFp32(true) selects "a" over lower-docId "b" and tied Tier-0 "c" across Path A (inline mask + oversample fallback k' = k + |T_mask|) and Path B (exhaustiveFp32TieBreakAppliesScoreDescKeyAscBeforeBaseTruncationAcrossLeavesAndTier0), shared CanonicalKeyOrder total key order across tied Integer(1), Long(1L), String("1"), Integer(2), String("2") + all-4-metric scoreBatch vs score bit-identity + injective toKeyTerm + exact bit-identical pre-flush (inline mask + oversample fallback), Path B flush, and post-flush top-k (k=1..8) against a reference oracle (exhaustiveFp32TotalKeyOrderAndPrePostFlushScoreEquivalenceAgainstReferenceOracle), observations through absence across partially replicated create x on B1 only and partially replicated destroy of acked y=v0 on B1 only proving Class L rollback boundaries vs. Class G preservation under transfer and acked destroy/re-put supersession on both Path A and Path B (observationsThroughAbsencePartiallyReplicatedCreateAndDestroyShowClassLBoundaryAndClassGPreservation), observed partially replicated unacked write w_1(x=v1) superseded by acked overwrite w_2(x=v2) replicating directly v0 -> v2 onto B2 preserving global linearizability across B1 crash and B2 promotion on Path A and Path B (observedPartiallyReplicatedWriteSupersededByAckedOverwritePreservesGlobalLinearizability), 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), Path-B contention drop-and-retry against Path A flushLock + demotion-during-retry ownership abort + post-commit/pre-refresh non-regressing recovery (pathBContentionDropAndRetryDemotionDuringRetryAndPostCommitPreRefreshAbort), and permanent demotion failover, explicit retry-exhaustion abort throws across ownership/stuck odd epoch/Path-B stuck flush, single-flight flushLock serialization across AEQ commit/evict vs Path-B flush/abort preventing stale v1 overwriting v2 with zero deadlock, writer paused between BucketRegion update and Tier-0 pin verified across both Path A and Path B (0 BucketRegion reads, 0 deadlock, 0 unpinned w_2 leakage, evictCommittedEntries preserving mid-commit w_2), Path-A pre-pin fence + committedKeySequences stale-AEQ regression rejection (across overwrite and delete-recreate) + unconditional stale-AEQ drop guard when seq=1 arrives delayed while seq=2 is committed and seq=3 is live in Tier-0 for both overwrite and tombstone through refresh and eviction (pathADelayedSeq1EventDroppedWhenSeq2CommittedAndSeq3LiveOverwriteInTier0, pathADelayedSeq1EventDroppedWhenSeq2CommittedAndSeq3LiveTombstoneInTier0) + post-commit/pre-refresh interruption recovery, primary crash at replicate-before-pin boundary adopting interrupted overwrite and delete atomically at t_adopt before hydrationLatch opens, primary crash strictly after backup replication and before old-primary recordPut/recordDestroy adopting both overwrite and destroy cleanly at t_hyd with explicit inter-promotion read r_1 on B1 and surviving chained second promotion onto B2 once B1 -> B2 redundancy recovery completes (primaryCrashAfterReplicationBeforeRecordPutAndDestroyAdoptsAtHydrationAndSurvivesSecondPromotion), pre-recovery crash of B1-only unacknowledged write demonstrating the ownership-term-local rollback boundary onto B2 (preRecoveryCrashOfB1OnlyUnackedWriteDemonstratesOwnershipTermLocalRollbackBoundary), 3-backup partial-subset {B1, B3} vs B2 tracing both Class L local rollback before B3 -> B2 and Class G preservation after B3 -> B2 completes before t_hyd(B2) (threeBackupPartialSubsetDemonstratesClassLRollbackAndClassGRecoveryPreservation), fully-replicated unpinned overwrite & destroy surviving chained B1 -> B2 promotions with zero re-replication (fullyReplicatedUnpinnedWriteSurvivesChainedPromotionsWithZeroReReplication), Geode VersionTag (VersionStamp.processVersionTag / ConcurrentCacheModificationException) recovery ordering preserving newer B1-term write w_new over stale adopted old-term GII chunk w_old across B1 -> B2 promotion (redundancyRecoveryVersionTagOrderingPreservesNewerB1TermWriteOverAdoptedOldTermWrite), delayed promotion scan rejecting stale captured values/tombstones via committedKeySequences after new-term overwrite/destroy/recreate flushes and evicts, Path-B full drain of 1,200 (> B_max) pending keys across post-commit/pre-refresh interruption leaving getTotalSize() == 0 && !isFlushing() and zero tombstoned ghosts, Path-B already-empty fallback after 16 optimistic epoch mismatches resetting tier0Snapshot/maskedKeys cleanly, delayed promotion scan resuming in beginFlush seal-to-commit window rejecting stale installs via atomic evictionLock + E_flushing check, new-term writer paused before recordPut during afterPrimary adopted cleanly at hydrationLatch with idempotent post-resume pin, post-generation-change pre-pin writer linearizing strictly inside [inv(w_2), resp(w_2)] at t_hyd (hydrationLatch release) with synchronized (re) hydration mutual exclusion, atomic multi-key cut, monotonic w_2' overwrite, and chained second-promotion survival (postGenerationChangePrePinWriterLinearizesAtHydrationLatchPreservesMultiKeyCutAndSurvivesSecondPromotion), 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 (21 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, 3-VM live region.put(v2) paused inside BucketRegion.basicPutPart2 (synchronized (RegionEntry) held, before Tier-0 pin) during BOTH Path B (FuzzyQuery) and Path A (LuceneEventListener.processEvents), 3-VM end-to-end Path-A pre-pin fence + delayed stale AEQ rejection across Path-B commit/evict & delete-recreate + post-commit/pre-refresh interruption recovery, 3-VM primary crash strictly after synchronous replication of both an overwrite and a destroy prior to Tier-0 pin verifying continuous reader observes strictly pre-adoption or atomic adopted cut at t_hyd, 3-VM post-promotion new-term overwrite/destroy/recreate flush & eviction rejecting delayed promotion-scan installs (putIfSequenceBefore/deleteIfSequenceBefore/putIfAbsent/deleteIfAbsent returning -1L) on both Path A and Path B, 4-VM rf=2 chained second-promotion kill -9 verification of post-generation-change writer gating, t_hyd hydration cut, pre-flush w_2' overwrite, and lossless survival across a second promotion on both Path A and Path B (postGenerationChangeWriterDuringPromotionLinearizesAtHydrationCutAndSurvivesSecondPromotion), 4-VM rf=2 primary crash strictly after synchronous backup replication of both overwrite and destroy prior to old-primary recordPut/recordDestroy (with zero client retry onto promoted1), verifying explicit inter-promotion read r_1 on promoted1 (ownershipGeneration > 0), backup2 successor-durable state, and lossless r_2 survival across immediate second kill -9 onto backup2 before Lucene flush on both Path A and Path B (primaryCrashAfterBackupReplicationBeforeRecordPutAndDestroySurvivesTwoPromotions), 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 exhaustiveFp32:boolean and 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 371 367 0 4 (pre-existing) PASS
PR 2 Unit Test Suites (subset of above: 43 + 5 + 23 + 17) 88 88 0 0 PASS
:geode-lucene:distributedTest --tests "*HybridKnn*" --rerun (DistributedHybridKnnFunctionDistributedTest) 21 21 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 20 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.
…ttedKeySequences stale-AEQ rejection, and post-commit/pre-refresh recovery
…ittedKeySequences after new-term flush/eviction
…=0 provisional vs seq>=1 live) and verify Path-B full drain > B_max after commit/refresh abort
…tomically fence seal-to-commit hydration via evictionLock, and verify paused-before-pin adoption
…nitor, linearize promotion cut at t_hyd (hydrationLatch release), and verify post-gen-change writer + second promotion
…lushLock before boundEntry lookup (seq=1 delayed, seq=2 committed, seq=3 live overwrite/tombstone)
…Put/recordDestroy boundary (overwrite + destroy) across two chained promotions
…linearizability, strengthen inter-promotion read checks, and verify pre-recovery rollback boundary
… history partition, add fully-replicated unpinned write & VersionTag recovery ordering tests
…ge & Path-B lock-order docs, rf>=2 Class G/L docs & contention/demotion/abort/3-backup tests
…ey ASC) base collector & 1-doc-per-key docs, Class G sufficiency/rollback Javadoc & overwrite test
… toString) across Tier-0/Lucene FP32/final merge, injective keyTerm domain & shared FP32 scorer docs, Class G over M(t) incl. observations through absence & tests
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