Skip to content

GEODE-vector-pr4: Adaptive Chordal Voronoi Continuous Vector Listener with RVV Monotonicity - #8157

Draft
gouthamaenugu wants to merge 30 commits into
apache:developfrom
gouthamaenugu:feature/GEODE-vector-pr4-rvv-listener
Draft

gouthamaenugu wants to merge 30 commits into
apache:developfrom
gouthamaenugu:feature/GEODE-vector-pr4-rvv-listener

Conversation

@gouthamaenugu

@gouthamaenugu gouthamaenugu commented Nov 24, 2026 •

Copy link
Copy Markdown

PR 4: Adaptive Chordal Voronoi Continuous Vector Listener with RVV Monotonicity

  • Draft PR: #8157
  • Branch: feature/GEODE-vector-pr4-rvv-listener
  • Base: develop (46643af515)
  • Head Commit: d0a418420c6e1f162b9c85129f58eac9efa9927d (14 files changed, +27227 / -0)
  • 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 30 clean logical commits — feature implementation, review hardening, Higham sqrt-free cosine pruning, incremental O(|V_k|) Voronoi removal, online survival-rate SIMD guard + coalesced async RVV batch dispatch, RVV watermark heartbeats + true O((M/K)d) per-cell Voronoi CoW + Theorem 1 float64 outward rounding, float64 max-abs norm + tau stratification + periodic survival re-probe + RVV reconnect replay, equal-version v_h data-before-heartbeat FIFO ordering + reconnect sink scoping + d=1/binary32 underflow guards, contiguous RVV holdback + idle-tail heartbeat flush + IdempotentRvvConsumer crash recovery, oldest-uncovered trickle heartbeats + pending-intent watermark guard + subnormal/maxCellSize hardening, bounded holdback gap-closure/resync + out-of-order match pending-intent guard + d=1/tau=1/subnormal boundary coverage, sequential per-stream WAL staging + two-sided holdback expiry coverage, atomic durable intake + ordinary-reconnect recovery + staggered-ACK checkpoint minimum + |S|=0 version continuity, atomic per-stream consumer execution/recovery fencing + compacted replay floor V_floor resync gate + live secondary shadow-tail buffering, V_floor <= V_client < V_ckpt exact > V_client replay fix + atomic S_healthy re-admission + batch-level IdempotentRvvConsumer staging, atomic overflow V_floor <= V_ckpt reconciliation + receiver sessionEpoch fence + FIFO reconnect barrier, atomic V_floor physical-retention compaction + replicated (V_floor, V_ckpt) + V_ckpt admission lower-pin, contiguous V_S = V_contig active-gap reconnect handoff + streamExecutionFences post-lock epoch/intent revalidation + maxHoldbackGap = 128 forward-span verification, synchronous lower-pin durability point (CheckpointPinReplicator/applyReplicatedLowerPin) + reconnect uncovered heartbeat timer, V_enq/V_disp frontier separation + ordered Phase-2 WAL execution (drainPendingBeforeLocked) + 2-backup partial lower-pin guard, ordered client ingress durable-admission barrier (OrderedIngressBarrier) + immediate promotion HB(V_enq) re-emission + overflow V_floor <= V_ckpt <= V_enq, per-stream getTailSize occupancy invariant + multi-replica asymmetric lower-pin & durable t_0 crash-boundary verification, Phase-2 execution-lock rechecks + backup-floor ReplayFloorExceededException resync abort + monotone Math.min heartbeat timer anchor + probeCellsExact FLAT_SIMD latch snapshot rebuild, fair sessionEpochLifecycleLock RWLock serialization + inherited holdback gap age g_0 visibility + CRC32 FileBackedDurableDeliveryStore batched FileChannel.force(true) client-crash recovery, durable deferred covering-watermark advancement on PENDING retirement + atomic importBackupFloorLocked floor/checkpoint/subscriber/timer transition + CRC32 WAL torn-append/unforced-record prefix recovery, shared durable replay frontier V_enq_dur via LowerPinAck + atomic whole-frame OP_FRAME_BEGIN..OP_FRAME_COMMIT WAL durability + multi-blocker stepwise zero-frame retirement, replay-to-live handoff gap closure above V_enq_dur + holdback preservation for held acknowledged versions above an open gap on promotion + immutable admission match-set retention under intervening subscription churn + OP_COVERING_WM crash-prefix hardening & integrated mid-frame WAL recovery, canonical cross-replica admission match-set replication (CanonicalAdmissionMatchReplicator) + server-side sessionEpoch ACK fencing (staleSessionAcksRejectedCount) + global client WAL lock-order & Window-A Contracts S1/S2 verification + Algorithm 2 M <= M_down latch clearing + churn probe reset + (subscriptionGeneration, snapshotGeneration) rebuild guard + integrated 3-server rf=2 promotion/partial-frame-WAL/reconnect DUnit composition, Algorithm 2 NaN-safe first-sample EWMA init + probe-stat capture before burst reset + generation-checked tripSurvivalGuardToFlatSimd publication under writeLock, explicit TailMutation.AdmissionMatchState { SPECULATIVE, CANONICAL } + getDurableCanonicalFrontier + finalizeSpeculativeOnPromotionLocked, OrderedIngressBarrier L1 pre-OP_FRAME_COMMIT WAL ordering & runtime-enforced EffectHandler non-reentrancy (assertNotReentrantFromEffectHandler), and generation-local RouterSnapshot survival/re-probe statistics (zero cross-generation contamination under stale paused routes and M == 0 no-op) + monotonic canonicalTerm fencing (TermFencedCanonicalAdmissionMatchReplicator, CanonicalApplyOutcome) and promotion/reconnect/covering-HB publication guard for inherited canonical entries — 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 "*ContinuousVectorRvv*DistributedTest*" --rerun, and :geode-lucene:integrationTest --tests "*AnalyzeLuceneSerializablesIntegrationTest*" --rerun.)
  • Have you written or updated unit tests to verify your changes? (96 new unit tests across 2 JUnit suites + 25 multi-node failover chaos DUnit tests across 2 DUnit suites.)
  • If adding new dependencies to the code, are these dependencies licensed in a way that is compatible for inclusion under ASF 2.0? (No new external dependencies added; uses Geode 2.1's standard libraries.)

Summary / Motivation

Continuous Query (CQ) in Apache Geode evaluates scalar predicates over incoming region mutations, but has no native mechanism for standing semantic similarity subscriptions (cos(v, q_i) >= tau_i) over high-dimensional vector streams — nor a streaming failover delivery guarantee tied to Geode's Region Version Vectors (RVV).

This PR introduces an adaptive continuous vector matching and RVV-monotonic dispatch subsystem in org.apache.geode.cache.lucene.internal.vector.continuous:

  1. Zero-Pruning-FNR Adaptive Routing (ChordalVoronoiRouter & VectorSubscription): Normalizes all finite non-zero float32 vectors (from all-subnormal vectors to Float.MAX_VALUE) via direct binary32-to-binary64 widening before max-abs pre-scaling, and routes incoming vectors against standing cosine-similarity subscriptions by adaptively switching between direct linear scan (FLAT_SIMD) and Chordal Voronoi cell pruning (CHORDAL_VORONOI, using a closed-form crossover threshold with hysteresis to prevent mode oscillation). Supports heterogeneous-tau quantile stratification (thresholdStrata=4) so low-tau outliers do not poison high-tau cells, exposes getMaxCellSize() telemetry on RouterTelemetry, and runs periodic survival-guard O(Kd) re-probing (survivalGuardReprobeInterval=4096, survivalGuardRecoveryMargin=0.10) to recover CHORDAL_VORONOI after workload regime shifts. Stage-1 pruning operates directly in inner-product space via precomputed float64 coupled cell thresholds s_k^min = 1 - (B_k^up)^2 / 2 - epsilon_dot(d) derived from Higham's IEEE-754 Theorem 3.1 plus the binary32 FTZ/subnormal underflow bound (d * 2^-126), eliminating Math.sqrt from the hot path, safely guarding d == 1, empty clusters, and antipodal zero-sum centroids, and guaranteeing zero pruning-induced false negatives (FNR = 0 relative to Stage-2 float32 scan) across all boundary dimensions (d in {1, 7, 8, 9, ..., 4096}) even at tau_i = 1.0.
  2. RVV-Monotonic Failover, Compacted Replay Floor V_floor, Live Secondary Shadow Tail & Atomic Per-Stream Consumer Fencing (RvvMonotonicVectorDispatcher, ContinuousVectorQueryService, RvvClientGate, & IdempotentRvvConsumer): Tracks per-(bucketId, memberId) RVV high-watermarks and monotonic compacted replay floor V_floor[b, m] (advancing cleanly even during |S|=0 empty intervals; immediately flagging resyncRequired if a connecting/rejoining client presents V_client < V_floor), buffers replicated secondary vector mutations live via per-bucket BucketRegion shadow-tail CacheListeners so repeated hot-key overwrites never coalesce across failover, advances V_ckpt unconditionally to min_{i in healthy} ack[i] across staggered multi-subscriber ACKs, enforces contiguous-version holdback sequencing (enforceContiguousVersions=true, maxHoldbackGap=128, maxHoldbackAgeMillis=5000, onNonMatchingBucketVersion for destroys/invalidates/non-vector updates), provides age-bounded oldest-uncovered-mutation heartbeat flushing (flushIdleHeartbeats + optional scheduler), gates live writes behind asynchronous tail replay during primary promotion, enforces equal-version v_h data-before-heartbeat ordering within atomic per-bucket serial FIFO batches, and provides IdempotentRvvConsumer with single-lock atomic durable admission (v <= committedWatermark || isEffectApplied(id) || isPendingIntent(id) + stagePendingIntentIfAbsent inside streamStageLock, removing any unlocked RvvClientGate pre-check) plus strict per-stream execution/recovery fencing (streamExecutionFences, lock order sorted execFences -> streamStageLock) serializing in-flight handlers against concurrent versions, recover(), and prepareForReconnect().

Key Changes

Adaptive Continuous Vector Routing & Subnormal-Safe Normalization

  • VectorSubscription:
    • Immutable subscription descriptor storing subscriptionId, normalizedQueryVector, similarityThreshold, and derived chordalTolerance.
    • VectorSubscription.normalize(float[]) widens binary32 inputs to binary64 ((double) v) prior to any DAZ/FTZ operation and applies unconditional max-abs pre-scaling in float64 (maxAbs, scaled = (double) v / maxAbs, normSq += scaled * scaled, invNorm = 1.0d / Math.sqrt(normSq)) so all finite non-zero float32 vectors including all-subnormal inputs (Float.MIN_VALUE, 1e-19f, 1e-30f) and Float.MAX_VALUE normalize with zero overflow/underflow.
  • ChordalVoronoiRouter (org.apache.geode.cache.lucene.internal.vector.continuous):
    • Maintains standing VectorSubscription registrations with normalized query vectors and chordal tolerances, exposing getMaxCellSize() (max_k m_k) on both ChordalVoronoiRouter and RouterTelemetry.
    • Dynamically transitions between FLAT_SIMD and CHORDAL_VORONOI routing modes using closed-form crossover M_crit with hysteresis band to eliminate thrashing.
    • Heterogeneous-tau Quantile Stratification (thresholdStrata, default 4): Automatically stratifies subscriptions into up to min(thresholdStrata, K) quantile tau-bands when tauMax - tauMin >= 0.03f and K >= 4 with proportional K allocation per band, plus bound-aware incremental insert (minMemberThreshold / maxMemberThreshold on VoronoiCell) preferring tau-compatible cells so low-tau outliers do not poison high-tau cell bounds.
    • Theorem 1 Underflow & d = 1 / Degenerate Centroid Safety: computeHighamDotEpsilon(int dim) explicitly includes dim * FLOAT32_UNDERFLOW_QUANTUM (dim * 2^-126) alongside 2 * gamma_d + HIGHAM_DOT_SAFETY_FLOOR. buildSphericalVoronoiCells and buildSingleStratumVoronoiCells guard empty bands, d = 1 (K > |S^0| empty cluster collapse), and antipodal zero-sum centroids via deterministic fallback centroids (assignDeterministicFallbackCentroid), preserving zero pruning-induced FNR relative to the Stage-2 float32 scan across all d >= 1.
    • Precomputes float64 coupled cell bounds B_k^up = max(||q_i - c_k||_2 + rho_i^up) + delta_norm(d) (including explicit float64 arithmetic margin eta_f64(d) = 2 * gamma_{d+2}^f64 + 4 * u_f64 via computeFloat64Eta(d), plus configurable useCoupledBound(false) decoupled ablation toggle) and outward-rounded sqrt-free cosine thresholds s_k^min = Math.nextDown(1 - (B_k^up)^2 / 2 - epsilon_dot(d) - 8 * u_f64) (or -Infinity when B_k^up >= 2.0).
    • Supports true O((M/K)d) per-cell copy-on-write live incremental add and remove in CHORDAL_VORONOI mode: omits global O(Md) flat arrays from Voronoi RouterSnapshots, maintains subscriptionCellIndex for O(1) cell lookup on remove, replaces only the single affected VoronoiCell (retaining conservative cell bounds to preserve zero false negatives) with periodic spherical k-means compaction at 20% churn, and materializes flat SIMD arrays only on mode switch or survival-guard reversion.
    • Tracks online empirical survival rate using generation-local statistics scoped strictly inside each immutable RouterSnapshot (survivalSampleCount, observedSurvivalEwmaBits initialized to Double.NaN, flatRoutesSinceLastProbe, probeBurstLock/probeBurstCollected/probeBurstSurvivalSum, plus withFreshStatistics(newSnapshotGeneration) for resetSurvivalGuard() and diagnostic getSurvivalRateAtLastLatch()), with DEFAULT_SURVIVAL_EWMA_ALPHA = 0.10d, DEFAULT_SURVIVAL_GUARD_MIN_SAMPLES = 32, and configurable maxVoronoiSurvivalRate (default 0.85): routeNormalizedWithGeneration captures a single RouterSnapshot and immediately returns empty on snap.subscriptionCount == 0 without touching any statistic; recordSurvivalObservation and maybeRunSurvivalGuardProbe write strictly to their captured snap's fields so a stale route paused after snapshot validation can never contaminate a newer generation's counters, EWMA, probe burst, or mode. computeMCrit returns Integer.MAX_VALUE whenever p_bar >= 1.0 or p_bar >= maxVoronoiSurvivalRate, and sustained isotropic streams (p_bar_hat >= 0.85) automatically downgrade to FLAT_SIMD via tripSurvivalGuardToFlatSimd(expectedSnap) checking cur == expectedSnap && cur.snapshotGeneration == expectedSnap.snapshotGeneration && cur.subscriptionGeneration == expectedSnap.subscriptionGeneration under writeLock. Under writeLock, addSubscription/addSubscriptions/removeSubscription increment monotonic subscriptionGeneration (paired with snapshotGeneration on immutable RouterSnapshot and exposed via atomic routeNormalizedWithGeneration(float[]) -> RoutingDecision) and call maybeClearSurvivalLatchAtLowerThresholdLocked(subscriptions.size()) -> resetSurvivalGuardLocked() whenever M <= M_down (or count == 0) BEFORE mode evaluation and snapshot rebuild, while every fresh RouterSnapshot starts cleanly at (cs=0, ewma=NaN, cflat=0, probe=(0, 0.0)). When tripped above M_down, retains probeCells and tracks probeCellsExact, running a 16-sample (DEFAULT_SURVIVAL_GUARD_PROBE_BURST_SIZE = 16) O(Kd) re-probe burst every survivalGuardReprobeInterval routes (default 4096, 0 disables) capturing pProbe = probeBurstSurvivalSum / probeBurstCollected strictly before resetting burst accumulators without altering FLAT_SIMD results and automatically restoring CHORDAL_VORONOI when p_probe <= maxVoronoiSurvivalRate - survivalGuardRecoveryMargin—checking curSnap == snap && curSnap.snapshotGeneration == snap.snapshotGeneration before acquiring writeLock, re-verifying survivalGuardTripped && cur == expectedSnap && cur.snapshotGeneration == expectedSnap.snapshotGeneration && cur.subscriptionGeneration == expectedSnap.subscriptionGeneration under writeLock, and rebuilding/publishing a fresh RouterSnapshot covering 100% of current membership S whenever !cur.probeCellsExact || churnSinceLastCluster > 0 (tracked via survivalGuardRecoveryCount).

RVV-Monotonic Failover, Compacted V_floor Gate, Live Secondary Shadow Tail & Atomic Per-Stream Fencing

  • RvvMonotonicVectorDispatcher, ContinuousVectorQueryService, ContinuousVectorEvent, ContinuousVectorEventSink, & RvvStreamKey:
    • Coordinates per-bucket RVV sequence tracking (RvvStreamKey), bounded replay tail buffers, checkpoint compaction (ignoring regressive ACKs), and explicit tail-buffer overflow resync signals + overflow callbacks.
    • Monotonic Compacted Replay Floor (V_floor[b, m]), Atomic Backup-Compaction Floor Import, Synchronous Lower-Pin Durability Point, Atomic Overflow/Compaction Retention & Live Secondary Shadow Tail: Enforces the exact physical-retention invariant V_floor == highest version physically removed by compaction/overflow (compactToFloor, compactUpToCheckpoint, applyReplicatedFloorAndCheckpoint, getReplayFloorVersion, getReplayFloorResyncCount, ReplayFloorResyncListener, recordReplicatedCheckpoint) under subscriberRegistryLock -> state, removing ONLY <= target while atomically advancing V_floor = target in the SAME synchronized step (and replicating V_floor alongside V_ckpt so every version in (V_floor, V_head] is guaranteed physically present in tail). When overflow bumps V_floor, reconcileOverflowLocked (zero fast-path overhead) atomically evicts every lagging subscriber with V_client[i] < V_floor into resyncRequiredSubscribersByStream (isSubscriberResyncRequired, getResyncRequiredSubscribers) and recomputes V_ckpt = max(V_floor, min_{i in S_healthy'} V_client[i]) (or max(V_floor, V_enq) — never V_recv when a gap is open — preserving (V_floor, V_head] when S_healthy' is empty), keeping V_floor <= V_ckpt <= V_enq atomically across all transitions. admitSubscriberForContinuity(...), admitAndReplayForReconnect(...), and non-null replayUncheckpointedForReconnect(...) immediately flag resyncRequired (0 partial replay, not enrolled) whenever V_client < V_floor, and otherwise synchronously invoke CheckpointPinReplicator (setCheckpointPinReplicator -> applyReplicatedLowerPin / applyReplicatedLowerPinOrThrow throwing sanctioned ReplayFloorExceededException if any backup already compacted past V_client) under (subscriberRegistryLock, state) strictly BEFORE committing local lower-pin enrollment (pinCheckpointForAdmittedSubscriber) or releasing any replay batches; on ReplayFloorExceededException, importBackupFloorLocked atomically advances V_floor = max(V_floor, importedFloor), compacts local tail <= V_floor, transitions EVERY subscriber < V_floor (both reconnecting and active healthy subscribers) into RESYNC_REQUIRED, recomputes V_ckpt = min(V_enq, max(V_floor, minRemainingHealthyAck)) (or V_enq if empty, preserving V_floor <= V_ckpt <= V_enq), and reconciles the uncovered heartbeat timer (clearing when V_enq <= V_ckpt or preserving the monotone Math.min anchor otherwise), while BucketState.ensureUncoveredHeartbeatTimerInitialized (getOldestUncoveredMutationTimeMs) enforces a strictly monotone Math.min(existingOldest, anchorTs) timer anchor and emitPromotionWatermarksLocked immediately enqueues covering HB(V_enq) on promotion for every active stream with V_enq > V_ckpt even if arrivals stop. Wires per-bucket BucketRegion secondary shadow-tail CacheListener inside createPartitionListener (afterRegionCreate/afterBucketCreated/afterSecondary) with hardened secondary member-ID fallback in extractFromEntryEvent, buffering replicated vector mutation versions live on secondaries so repeated overwrites to hot keys never suffer state-store coalescing loss on primary failover.
    • Multi-Subscriber Staggered-ACK Tracking & |S|=0 Continuity: Adds registerSubscriberForCheckpoint, unregisterSubscriberForCheckpoint, and acknowledgeSubscriberCheckpoint advancing V_ckpt unconditionally to min_{i in healthy} ack[i] on idle tails and subscriber exit without regression, plus |S|=0 empty-subscription version continuity (getLastDispatchedVersion, getNextExpectedVersion, and zero tail overflow across empty intervals).
    • Contiguous Version Holdback Buffer, Inherited Gap Age g_0 & Bounded Gap-Closure (enforceContiguousVersions, default true): Holds out-of-order regionVersion > nextExpected entries in holdbackByMember (up to maxHoldbackGap=128 and age DEFAULT_MAX_HOLDBACK_AGE_MILLIS=5000, configurable via setMaxHoldbackAgeMillis), exposes getHoldbackGapStartTimeMs(bucketId, memberId) and getHoldbackGapAgeMillis(bucketId, memberId, nowMillis) preserving inherited open-gap age g_0 = max(0, t_0 - gapStartMs) across lower-pin reconnect and promotion (exact Theorem 3(6) precondition g_0 + Delta_tot < T_gap), and drains contiguous ready versions strictly in ascending order; exposes onNonMatchingBucketVersion(bucketId, memberId, regionVersion) wired into ContinuousVectorQueryService.createCacheListener (afterDestroy, afterInvalidate, null/non-vector updates). flushExpiredHoldbackGaps(...) (also integrated into flushIdleHeartbeats/scheduler) deterministically closes stalled gaps exceeding maxHoldbackGap or maxHoldbackAgeMillis, marks resyncRequiredStreams, notifies HoldbackGapListener, increments holdbackGapClosedCount, and drains ready successors contiguously so a missing predecessor can never stall delivery indefinitely (while gaps repaired before expiry preserve resyncRequired=false).
    • Age-Bounded Oldest-Uncovered Heartbeat Flush: Tracks oldestUncoveredMutationTimeMsByMember (set only when eventsSinceHeartbeat transitions 0 -> 1 and cleared on heartbeat reset) and lastDispatchedVersionByMember, firing flushIdleHeartbeats(long nowMillis, long maxAgeMillis) (and startIdleHeartbeatScheduler / stopIdleHeartbeatScheduler) whenever eventsSinceHeartbeat > 0 and (nowMillis - oldestUncoveredMs) >= maxAgeMillis, preventing heartbeat starvation under both idle tails and steady sub-interval zero-match trickles.
    • Emits lightweight per-(bucketId, memberId) RVV watermark heartbeats (ContinuousVectorEvent.watermarkHeartbeat(..., replayed)) periodically every heartbeatIntervalEvents primary mutations (default 64, configurable, 0 disables) and at the end of primary-promotion and reconnect replays.
    • Equal-Version v_h Data-Before-Heartbeat Ordering & Serial Per-Bucket FIFO: When a mutation at v_h produces both match events and emitHeartbeat == true, evaluateAndDispatch places all match events for v_h strictly before watermarkHeartbeat(..., v_h) in one atomic PendingDispatchBatch enqueued onto BucketState.pendingDispatchBatches. Both synchronous and multi-threaded async executors drain each bucket serially (dispatchDraining CAS + drainOwnerThread reentrancy guard) without concurrent overlapping sink dispatches.
    • Uses an async replay barrier during primary failover promotion that gates live writes until tail replay completes, eliminating reordering and duplicate windows.
    • Provides getReceivedHeadVersion(bucketId, memberId) (V_recv), getEnqueuedHeadVersion(bucketId, memberId) (V_enq, aliased by getContiguousHeadVersion, strictly Math.max(V_floor, nextExpected - 1) when holdbackByMember is non-empty — separated from getSinkDispatchedVersion (V_disp, updated strictly after sink delivery in dispatchBatchToSinks) and getPendingDispatchQueueSize(bucketId) so physical entries strictly above V_enq remain unconditionally bounded by maxHoldbackGap = 128 independent of async FIFO backlog), applyReplicatedFloorAndCheckpoint (capping delayed older checkpoints at min_{s in S_healthy} ack[s] so a delayed checkpoint cannot overwrite a surviving backup's lower pin), LowerPinAck(bucketId, memberId, backupFloor, backupContiguousEnq) / AckCheckpointPinReplicator / applyReplicatedLowerPinWithAck(..., sessionEpoch) + ReconnectAdmissionResult (admitAndReplayForReconnectWithResult(..., sessionEpoch, ...)) computing shared durable replay frontier V_enq_dur = min(localContiguousEnq, min_{r in P(b)} V_enq^(r)) across all promotable replicas while atomically enqueuing the full local contiguous suffix (Math.max(V_floor[b, m], clientHighWaterByMember[m]), V_enq^(local)] plus trailing HB(V_enq^(local)) (including trailing non-matching versions when tailByMember is empty) onto the per-bucket serial FIFO strictly before onReplayedUnderLock attaches live dispatch at V_enq^(local) + 1, server-side sessionEpoch ACK fencing (advanceCheckpointWithEpoch, recordSubscriberAckWithEpoch, acknowledgeCheckpoint(b, m, ver, sessionEpoch), acknowledgeSubscriberCheckpoint(subId, b, m, ver, sessionEpoch), advanceClientSessionEpoch/advanceSubscriberSessionEpoch, propagated to backups via applyReplicatedLowerPinWithAck so delayed ACKs with sessionEpoch < currentClientSessionEpoch are strictly rejected via staleSessionAcksRejectedCount++ without advancing V_ckpt or compacting tail), replayTailOnPromotionLocked preserving shadow-buffered entries strictly above an open gap v inside holdbackByMember with nextExpectedVersion = v (plus onSecondaryNonMatchingBucketVersion in ContinuousVectorQueryService recording secondary afterDestroy/afterInvalidate/non-vector markers to prevent false holes), cross-replica canonical admission match-set agreement with monotonic canonicalTerm fencing & promotion/reconnect/covering-HB publication guard (INITIAL_CANONICAL_TERM = 1L, TailMutation.AdmissionMatchState { SPECULATIVE, CANONICAL }, TailMutation.canonicalTerm, CanonicalMatchRecord.canonicalTerm, sanctioned CanonicalApplyOutcome, TermFencedCanonicalAdmissionMatchReplicator / CanonicalAdmissionMatchReplicator invoked on primary strictly before live dispatch/ACK, Rule 1 BucketState.applyCanonicalAdmissionMatches + fenceCanonicalTerm + applyReplicatedCanonicalAdmissionMatches(..., long canonicalTerm) accepting incoming (matches, subGen, term) iff !existing.isCanonicalConfirmed() || term > existing.getCanonicalTerm() — overwriting stale lower-term canonical decisions, rejecting delayed strictly-lower-term deliveries via getStaleCanonicalTermRejectedCount(), treating equal-term re-deliveries as idempotent no-ops, and staging reverse-order arrivals in pendingCanonicalMatchesByMember with the same higher-term precedence — and Rule 2 beginPromotionTerm advancing canonicalTerm/promotedPrimaryTerm on onPrimaryPromotion/completeAsyncPromotion paired with finalizeSpeculativeOnPromotionLocked, needsCanonicalPublicationLocked, and publishBeforeReconnectExposureLocked replicating BOTH newly finalized speculative entries AND inherited canonical entries with canonicalTerm < promotedPrimaryTerm as (matches, subGen, newTerm) to all surviving promotable backups strictly BEFORE dispatch, covering HB, or durableCanonicalFrontier [isDurablyCanonicalLocked] advancement, tracked via speculativeEntriesFinalizedOnPromotionCount and getInheritedCanonicalRepublishedCount(), so live dispatch and multi-crash promoted-backup/reconnect replays reproduce identical canonical admission match tuples even under r=3, f=2 chained failovers and adversarial subscription churn), admitAndReplayForReconnect(...), and replayUncheckpointedForReconnect(int bucketId, Map<String, Long> clientHighWaterByMember[, ContinuousVectorEventSink targetSink, Runnable onReplayedUnderLock]) under synchronized (state) across all retained streams m (both pre-crash m_P and post-promotion m_S) onto the same per-bucket serial FIFO queue (PendingDispatchBatch.barrierAction / enqueueOrDispatchBarrierLocked, tracked via totalReconnectReplaysHandled).
  • RvvClientGate & IdempotentRvvConsumer:
    • RvvClientGate enforces strictly monotonic per-(subscriptionId, bucketId, memberId) delivery across out-of-order and multi-subscription streams (tryAccept and tryAcceptBatch), serializes concurrent callbacks on the same stream, advances highWaterVersion monotonically on watermark heartbeats without invoking match listeners, enforces strict Theorem 3 Invariant 4 safe checkpoint bounds across all active subscriptions, exposes getSafeHighWaterByMember(int bucketId) for slow-reconnect handoff, and documents its gate-delivery contract in Javadoc.
    • IdempotentRvvConsumer keys durable delivery strictly by (subscriptionId, bucketId, memberId, regionVersion) (EventDeliveryId), enforces a strictly acyclic global lock hierarchy across L1: OrderedIngressBarrier (standalone around ingress wait/advance, holding frame admission until OP_FRAME_COMMIT + force(true) completes so covering heartbeats processCoveringWatermark cannot overtake an uncommitted frame, always released before L2..L5), L2: streamExecutionFences[subId|b|m] (multi-fence paths recover/prepareForReconnect acquiring strictly in ascending lexicographic order via acquireSortedExecutionFences with recoverUnderFencesLocked deferring un-held fences to the outer sorted re-acquisition loop, while single-stream drainPendingBeforeLocked filters strictly to (subId, b, m)), L3: sessionEpochLifecycleLocks[b] (fair ReentrantReadWriteLock: readLock() inside L2 or standalone in Phase 1/heartbeat before L4; writeLock() strictly standalone in advanceSessionEpoch/onSessionDisconnect/prepareForReconnect Step 1 before incrementing activeSessionEpochByBucket[b]), L4: streamStageLocks[b|m], and L5: leaf locks (FileBackedDurableDeliveryStore.walLock, RvvClientGate.StreamState), explicitly documents AND runtime-enforces the EffectHandler non-reentrancy contract via assertNotReentrantFromEffectHandler() (rejecting re-entry into L1..L5-acquiring consumer methods from inside effectHandler.apply(...) with IllegalStateException), and explicitly documents Window A Contracts S1 (idempotent sink keyed by (subId, b, m, v)) and S2 (transactional sink atomically committing (effect, dedupKey=(subId, b, m, v)) in one sink transaction). Phase-1 staging, heartbeat watermark commits, and Phase-2 execution (drainPendingBeforeLocked -> final isStaleSessionEpoch & isAppliedOrRetiredLocked check -> effectHandler.apply -> markEffectAppliedIfAbsent -> forceAppliedAndWatermarkDurability() -> markPendingCompleted + committed watermark advance) all hold sessionEpochLifecycleLocks[bucketId].readLock(), proving zero old-session handler or heartbeat can execute after epoch transition even if paused immediately after its final epoch check. Persists per-(bucketId, memberId) highestReceivedCoveringWatermark (persistCoveringWatermark / OP_COVERING_WM = 6, forced on heartbeat receipt even when blocked behind a PENDING intent) and enforces V_client = min(max(completed, highestReceivedCoveringWatermark), lowestPendingVersion - 1) across all three OP_COVERING_WM(v_h) crash-prefix classes (absent, torn/CRC-invalid truncated on open(), and intact checksum-valid unforced recovered as W_cov but unconditionally capped by durable PENDING blockers, with recoverUnderFencesLocked calling store.forceAppliedAndWatermarkDurability() whenever non-pending watermark restoration advances from recovered OP_COVERING_WM before emitting ACKs), advancing stepwise as each blocking PENDING version retires and reaching W_cov upon retirement of the last blocker <= W_cov with zero additional server frames. Includes CRC32-framed append-only FileBackedDurableDeliveryStore ([int payloadLen][int crc32][byte[] payload] with atomic whole-frame OP_FRAME_BEGIN = 7 / OP_FRAME_COMMIT = 8 brackets carrying expectedPendingCount around stageBatchPhase1, open(Path) scanning longest CRC32-valid prefix and atomically truncating both partial/corrupt EOF bytes [getTruncatedTailBytesOnOpen()] and any incomplete multi-match frame lacking OP_FRAME_COMMIT back to OP_FRAME_BEGIN [getIncompleteFramesTruncatedOnOpen()] via channel.truncate + force(true), simulateCrashCloseWithoutFlush(), forcePendingDurability(), forceAppliedAndWatermarkDurability()) enforcing batched frame-level FileChannel.force(true) boundaries (1 PENDING force strictly before ingress release/callback; 1 APPLIED force strictly before retirement/watermark advance/ACK) across onEventBatch/processEventBatch/processOrderedFrameBatch, guaranteeing strictly ordered, zero-loss, zero-duplicate notifications/effects across ordinary connection loss and client crashes across all four admissible WAL prefixes.

New Unit & Distributed Chaos Tests (96 Unit + 25 Failover DUnit)

  • ChordalVoronoiRouterTest (24 tests): zero-FNR verification across thousands of random and boundary vectors, unconditional max-abs float64 widening/normalization across all-subnormal/extreme vectors (Float.MIN_VALUE, 1e-19f, 1e-30f, Float.MAX_VALUE) + d=1/tau=1.0 + boundary d in {1, 7, 8, 9} + exact dot == tau threshold equality + getMaxCellSize() telemetry with FNR == 0, heterogeneous-tau quantile stratification + bound-aware incremental insert outlier isolation with FNR == 0, periodic survival-guard 16-sample O(Kd) re-probe restoring CHORDAL_VORONOI after isotropic-to-clustered regime shift with FNR == 0, subscription add/remove during FLAT_SIMD latch above M_down triggering atomic RouterSnapshot rebuild on Voronoi re-entry (probeCellsExact) with 100% recall of new subs, 0 stale removed subs, and 0 FNR (subscriptionAddAndRemoveDuringFlatSimdLatchRebuildsSnapshotOnVoronoiReentryWithZeroFnrAndZeroStaleMatches), Algorithm 2 latch clearing at M <= M_down, unconditional probe burst reset on churn, and (subscriptionGeneration, snapshotGeneration) stale re-probe rebuild rejection under writeLock (survivalLatchClearsAtLowerSwitchThresholdResetsProbeOnChurnAndRejectsStaleReprobeRebuild), NaN-safe first-sample EWMA initialization after reset and stale-snapshot route rejection against latching a newer snapshot under writeLock (resetToLatchEwmaInitAndStaleSnapshotRouteCannotLatchNewerSnapshot, asserting g+1 starts fresh at (0, NaN) and requires its own 32 samples), stale route paused strictly after snapshot validation (afterSnapshotValidationHookForTest) across subscription churn unable to contaminate newer generation snap' counters/EWMA/probe burst/mode on BOTH CHORDAL_VORONOI EWMA/latch (32nd sample) and FLAT_SIMD re-probe paths plus M == 0 no-op (staleRoutePausedAfterValidationCannotContaminateNewGenerationCountersOrEwma), d == 1 cluster collapse + antipodal zero-sum centroid fallback + (1,1) at tau=1.0 zero pruning FNR + binary32 underflow bound d * 2^-126, sqrt-free Higham cosine bound adversarial verification at x == c_k == q_i with tau_i in {1.0, 1 - 1e-7, 0.9999} across d in {128, 1536, 4096}, Theorem 1 eta_f64(d) + 8 * u_f64 + Math.nextDown outward rounding verification near B_k^up >= 2.0 and antipodal pairs with tau = 1.0, true O((M/K)d) per-cell CoW verification, coupled B_k^up vs decoupled R_k + rho_k^max tightness, incremental removal until 20% churn, computeMCrit survival-ceiling handling, online EWMA survival-rate guard reversion to FLAT_SIMD, 4096-D safety epsilon, high-selectivity pruning efficiency, closed-form M_crit + hysteresis anti-oscillation, live add/remove/recluster safety, and invalid input rejection.
  • RvvMonotonicVectorDispatcherTest (72 tests): failover replay exactly-once monotonic delivery, out-of-order holdback ordering 65,66 strictly behind delayed 64 + non-vector destroy/gap without drops, temporary predecessor gap repaired before expiry preserving contiguous delivery without resync, delayed predecessor exceeding maxHoldbackAgeMillis closing gap + emitting HoldbackGapListener resync notification + unblocking zero-match checkpoints, exact DEFAULT_MAX_HOLDBACK_GAP = 128 forward-span bound (127 <= 128 buffered vs 129 > 128 closing gap) + delayed hole/continuing arrivals/age trigger near C_tail, inherited open-gap age g_0 = 4,900 ms near T_gap = 5,000 ms across lower-pin reconnect and async promotion (4,950 < 5,000 ms -> 0 resync vs 5,000 >= 5,000 ms -> deterministic MAX_HOLDBACK_AGE_EXCEEDED, inheritedHoldbackGapAgeNearExpiryAcrossLowerPinAndPromotion), active holdback gap (65 held behind missing 64) V_S = V_enq = 63 reconnect handoff + concurrent arrival + simulated crash during lower-pin admission, delayed FIFO (200 undispatched queued batches) + newly opened gap separating V_enq vs V_disp frontiers near C_tail, ordered client ingress barrier preventing later match v=4 and covering HB(4) from overtaking paused pre-streamStageLock v=3 + clean disconnect rejection on pre-stage crash, delayed frame admission paused before OP_FRAME_COMMIT + force(true) blocking covering HB(10) via L1, crash truncation (pending=0, applied=27, W_cov=9, V_client=9), reconnect replay + pre-APPLIED crash recovery (pending=0, applied=30, W_cov=10, V_client=10, ACK(10)), and runtime EffectHandler reentrancy rejection (delayedFrameAdmissionFollowedByCoveringHeartbeatCrashAndReconnectPreservesWalOrdering), Phase-2 execution-lock rechecks of isAppliedOrRetiredLocked and isStaleSessionEpoch after OrderedIngressBarrier release (phase2ExecutionLockRechecksAppliedRetiredAndSessionEpochAfterIngressBarrierRelease), fair sessionEpochLifecycleLock RWLock serialization with old Phase-2 worker and old heartbeat worker paused strictly AFTER final isStaleSessionEpoch check and BEFORE handler/watermark commit (sessionEpochBumpSerializesWithPhase2WorkerPausedAfterFinalEpochCheckBeforeHandler, sessionEpochBumpSerializesWithHeartbeatWorkerPausedAfterFinalEpochCheckBeforeCommit, zero post-bump execution, zero deadlock), CRC32 FileBackedDurableDeliveryStore batched FileChannel.force(true) client-crash recovery (M = 32 subs/frame = 32 tuples/force) across BOTH Window A (after PENDING force, mid-batch before APPLIED force) and Window B (after APPLIED force, before retirement/ACK + server replay) yielding 192/192 exact tuples with 0 post-Window-B duplicates (fileBackedBatchedWalClientCrashRecoveryAcrossWindowAAndWindowB), Window-A crash recovery with proper-prefix valid OP_APPLIED(sub-1) and torn OP_APPLIED(sub-2) preserving exact-once external state under both Contracts S1 and S2 (windowACrashRecoveryWithProperPrefixValidAppliedAndTornAppliedPreservesExactOnceUnderContractsS1AndS2), cross-subscription concurrent predecessor drains + recover() + prepareForReconnect(0) maintaining strict global lock order with zero deadlock (crossSubscriptionConcurrentPredecessorDrainAndRecoverMaintainsStrictLockOrderWithoutDeadlock), server-side stale sessionEpoch ACK rejection after reconnect lower-pin on both primary and promoted backup (staleSessionEpochAckRejectedAfterReconnectLowerPinOnPrimaryAndPromotedBackup), canonical admission match-set replication from primary to backup under both adversarial churn and reverse arrival order (canonicalAdmissionMatchSetReplicatesFromPrimaryToBackupUnderAdversarialChurnSchedule), partial canonical-publication crash promoting unconfirmed SPECULATIVE backup B2 with in-place finalization to CANONICAL + reverse arrival + partial lower-pin epoch (partialCanonicalPublicationCrashPromotesUnconfirmedBackupAndHandlesReverseArrivalAndPartialLowerPinEpoch), r=3, f=2 monotonic canonicalTerm fencing where B2 promotes first (term 2), derives C2 != C1, overwrites B1's stale term-1 C1, rejects delayed (C1, term=1), crashes, and B1 promotes (term 3) replaying strictly C2 (canonicalTermFencingB2PromotesFirstOverwritesStaleC1RejectsDelayedOldTermAndSecondCrashReplaysC2), r=3, f=2 promotion publication guard where B1 promotes first (term 2), replicates inherited (C1, term=2) to B2 strictly before D6, covering HB6, and durableCanonicalFrontier advancing past 5, rejects delayed (C1, term=1), crashes, and B2 promotes (term 3) replaying strictly C1 (publicationGuardB1PromotesFirstReplicatesInheritedC1BeforeExposureAndSecondCrashReplaysC1), durable deferred highestReceivedCoveringWatermark (HB(8) blocked behind PENDING v=5) advancing V_client to 8 and emitting ACK(8) immediately on PENDING retirement with zero additional server frames across normal execution and WAL Windows A & B (deferredCoveringHeartbeatAdvancesClientWatermarkAndEmitsAckOnPendingRetirementWithoutNewFrames), multiple blocking PENDING versions {5, 7} under W_cov = 8 advancing stepwise (4 -> 6 -> 8) and emitting ACK(6)/ACK(8) across normal retirement and mixed Window B + Window A WAL recovery with zero new server frames (multipleBlockingPendingVersionsStepwiseAdvanceWatermarkToCoveringWithZeroNewFrames), atomic backup-compaction floor-import transition updating V_floor <= V_ckpt <= V_enq, evicting < V_floor subscribers (including active healthy ones), and reconciling the heartbeat timer (backupCompactionFloorImportAtomicallyUpdatesFloorCheckpointSubscribersAndHeartbeatTimer), shared durable replay frontier V_enq_dur excluding B1-only unacked version 65 across a post-lower-pin-ACK pre-dispatch two-crash schedule AND verifying surviving B1 (durableReplayFrontier=64, localContiguousEnq=65) delivers 64, 65, 66 contiguously with zero skip (durableReplayFrontierExcludesPrimaryOnlyUnackedVersionAcrossTwoCrashSchedule), held acknowledged version above an open gap draining in strict ascending order after reconnect on both surviving B1 and promoted B2 (heldAcknowledgedVersionAboveOpenGapDrainsInOrderAfterReconnectOnPrimaryAndPromotedBackup), promoted-backup & reconnect replay reproducing exact admission match sets across intervening subscription churn rounds (promotedBackupReplayPreservesExactAdmissionMatchSetUnderInterveningSubscriptionChurn), integrated mid-frame client crash & reconnect across INTACT_UNFORCED, TORN, and ABSENT OP_COVERING_WM(12) variants reconciling ACK-time oracle, recovered WAL, committed idempotent sink effects, and final ACK(12) (integratedMidFrameClientCrashAndReconnectWithCoveringWatermarkReconcilesAllOracles), atomic whole-frame OP_FRAME_BEGIN..OP_FRAME_COMMIT WAL truncation of incomplete multi-match frames replaying all 3 subscriptions from V_client = 9 to ACK(10) (atomicWholeFrameWalTruncatesIncompleteMultiMatchFrameAndReplaysAllSubsToAck), CRC32 WAL recovery over complete unforced PENDING records, torn partial PENDING appends + bit-flipped CRC corruption, and torn partial APPLIED appends (fileBackedWalRecoveryHandlesCompleteUnforcedRecordsTornPendingAndTornAppliedAppends), primary crash strictly between count-triggered HB(4) enqueue and wire dispatch immediately re-emitting HB(4) on promotion even when arrivals stop, reconnect against lower-floor primary aborting cleanly to RESYNC_REQUIRED via ReplayFloorExceededException when backup already compacted past V_client (reconnectAgainstLowerFloorPrimaryAbortsToResyncRequiredWhenBackupAlreadyCompactedPastClient), pre-t_0 partial-replication crash across 2 backups B1/B2 promoting both in turn with arrivals stopped (preT0PartialReplicationCrashAcrossTwoBackupsPromotesB1AndB2InTurnWithArrivalsStopped), disjoint pre-t_0 holdbacks merged on promotion under universal union bound U_0 + arrivals < C_tail + strictly monotone Math.min heartbeat timer anchor across repeated reconnects (disjointPreT0HoldbacksPromotionMergeAndReconnectPreserveUnionCapacityBoundAndMonotoneHeartbeatTimer), multi-replica asymmetric tail occupancy after partial lower-pin (|tail_{B2}(t_0)|=24 > |tail_P|=|tail_{B1}|=21, 31 < C_tail=32) promoting largest replica B2 with zero overflow, primary crash on both sides of durable replication boundary t_0 with arrivals stopped, old-session staged batch pausing before streamExecutionFences rejected after disconnect or reconnect recovery, ordered Phase-2 execution draining earlier pending intents ([1, 2, 3, 4] and [1..6] across prepareForReconnect) when later staged v+1 races into streamExecutionFences, 2-backup partial lower-pin crash window (B1 pinned 63, B2 at 64 compacted or uncompacted, plus delayed (60, 64) checkpoint guard) guaranteeing zero silent skip for every promotable survivor, synchronous lower-pin durability point exercising BOTH crash sides + oldestUncoveredMutationTimeMs initialization & idle heartbeat flush across reconnect, staggered ACKs from multiple healthy subscribers advancing V_ckpt to exact min_i ack[i] on idle tails, |S|=0 empty-subscription version continuity with zero tail overflow, subscriber rejoin below compacted V_floor immediately flagging resyncRequired, V_floor <= V_client < V_ckpt exact > V_client replay (V_floor=60, V_client=63, V_ckpt=64 -> replays [64..70] with atomic S_healthy pin + V_client=59 -> immediate resyncRequired), atomic tail overflow reconciliation evicting lagging subscribers < V_floor and preserving V_floor <= V_ckpt <= V_enq for both non-empty and empty S_healthy' (including open-gap empty-registry check V_recv=13, V_enq=8, V_ckpt=8, V_floor=4), receiver sessionEpoch fence rejecting stale covering heartbeats after disconnect between match batch and heartbeat, idle heartbeat + floor-to-checkpoint reconnect near C_tail - 1 advancing V_ckpt >= v_0 with zero overflow, post-compaction < V_floor resync vs uncompacted V_floor <= V_client < V_ckpt admission lower-pinning V_ckpt across promotion near capacity with concurrent heartbeat, multi-subscription (sub-A/sub-B) repeated-key promotion + delayed match pinned below covering HB(63) + lagging reconnect, promotion + slow consumer + pending checkpoint at C_tail - 1 vs C_tail + 1 (C_tail=64 and DEFAULT_MAX_TAIL_PER_STREAM=100,000), repeated-key failover preserving every per-version (b, m, v) notification without coalescing loss, timed idle-tail heartbeat flush advancing V_ckpt after 63 zero-match mutations, steady zero-match trickle (40 ms interval) firing age-bounded heartbeats without starvation, IdempotentRvvConsumer crash-injection, ordinary-reconnect per-stream execution/recovery fencing, and durability boundary verification (BEFORE_DURABLE_PENDING_STAGE, AFTER_WATERMARK_PERSIST_BEFORE_EFFECT, AFTER_EFFECT_BEFORE_WATERMARK_COMMIT, connection loss after durable PENDING staging before effect retires, out-of-order match commit pending-intent guard, delayed PENDING intent blocking later matches and heartbeats through restart recovery), slow client reconnect replaying both pre-crash m_P and post-promotion m_S retained streams with trailing heartbeats under concurrency, match-on-mutation-64 (v_h) delivering matches strictly before v_h watermark while advancing 0%-match client watermark, slow reconnect with 4-thread async executor + concurrent live m_S writes + two clients at V_client_A != V_client_B, healthy 0%-match subscriber advancing V_ckpt across 5 * maxTail writes + failover replay via periodic & promotion RVV watermark heartbeats with 0 tail overflows and 0 spurious match callbacks, async replay barrier gating live writes, coalesced onEventBatch + async per-bucket serial FIFO dispatch preserving strict RVV monotonicity across live writes & primary failover, concurrent tryAccept callback serialization, client gate multi-subscription ordering, checkpoint compaction + regressive ACK handling, unsubscription gate cleanup + tail compaction, tail-buffer overflow resync signaling, and service facade lifecycle/telemetry (getTailSize).
  • ContinuousVectorRvvFailoverDistributedTest (20 tests) + ContinuousVectorRvvFloorImportDistributedTest (5 tests, 25 DUnit total): kills the primary server mid-ingestion on a real Geode cluster with enforceContiguousVersions=true, real afterDestroy non-matching version tracking, matching subscriptions, and a healthy 0%-match orthogonal subscriber, slow reconnect after primary kill with concurrent post-promotion m_S writes, slow reconnect with 4-thread async executor + two clients + exact mutation GEODE-649: add more logging to see the reason of future failure. #64 boundary, steady-trickle + idle-tail age-bounded heartbeat flush advancing checkpoints across the cluster, two-phase holdback gap behavior (repaired before expiry vs exceeding maxHoldbackAgeMillis), connection loss after durable PENDING staging before effect retires, staggered multi-subscriber ACKs + |S|=0 empty-subscription interval continuity across the cluster, ordinary reconnect fencing an in-flight handler against duplicate admission/overlap, 3-server promotion at C_tail - 1 (0 resync) vs C_tail + 1 overflow + rejoin below V_floor immediate rejection, 3-server repeated-key live kill -9 failover delivering exact 32/32 per-version (b, m, v) notifications across 4 hot keys, 3-server reconnect between V_floor and V_ckpt replaying intermediate versions + < V_floor immediate resync, 3-server multi-subscription (sub-A/sub-B) repeated-key kill -9 promotion + delayed match pinned below covering HB(63) + lagging reconnect delivering 152/152 (subId, b, m, v) effects with 0 misses/duplicates/resyncs, 3-server disconnect between match batch and covering heartbeat rejecting stale-session heartbeats, 3-server idle heartbeat + floor-to-checkpoint reconnect near C_tail - 1 + atomic overflow subscriber eviction, 3-server kill -9 reconnect after compaction (V_client=63 < V_floor=64 -> resyncRequired) vs uncompacted V_floor=60 <= V_client=63 < V_ckpt=64 near C_tail - 1 = 31 with concurrent heartbeat + compactUpToCheckpoint delivering 91/91 versions, 3-server active-gap V_S = V_enq reconnect + live primary kill -9 during lower-pin admission + delayed-hole continuing-arrivals maxHoldbackAgeMillis age trigger near C_tail=32, 3-server kill -9 verification of BOTH sides of the lower-pin durability point (pre-durability compaction -> resyncRequired vs post-durability replication -> lossless [64..68] replay) plus oldestUncoveredMutationTimeMs idle heartbeat flush across reconnect, 3-server kill -9 crash strictly between count-triggered HB(4) enqueue and wire dispatch proving promoted backup immediately re-emits HB(4) even when arrivals stop, 3-server rf = 2 live kill -9 verification of both durable t_0 replication-boundary crash sides + asymmetric partial lower-pin promotion of largest-occupancy backup B2, 3-server rf = 2 verification of backup-floor RESYNC_REQUIRED abort (primary floor 60 vs backup compacted 64, V_client = 63 -> 0 events released) plus pre-t_0 partial replication across two backups promoting both in turn with arrivals stopped (partialBackupCompactionResyncAndPreT0TwoBackupPartialReplicationAcrossCluster), 3-server rf = 2 cross-JVM atomic backup-compaction floor-import verification (ContinuousVectorRvvFloorImportDistributedTest.backupCompactionFloorImportAcrossTwoSurvivingReplicasPreservesFloorCheckpointAndSubscribers), 3-server rf = 2 post-lower-pin-ACK pre-dispatch primary crash verifying shared durable replay frontier V_enq_dur = 64 (excluding B1-only unacked 65) replayed losslessly on promoted B2 with 0 resync (ContinuousVectorRvvFloorImportDistributedTest.postLowerPinAckPreDispatchPrimaryCrashReplaysSharedDurableFrontierOnSurvivingBackup), 3-server rf = 2 failover with intervening unregisterSubscription("sub-old") + registerSubscription("sub-new") before primary crash verifying promoted-backup replay reproduces exact admission match sets (ContinuousVectorRvvFloorImportDistributedTest.promotedBackupReplayReproducesExactAdmissionMatchSetUnderInterveningSubscriptionChurn), 3-server rf = 2 adversarial cross-replica subscription churn pausing primary P after backups speculatively capture {sub-persist, sub-old} for v=6, committing unregister("sub-old") + register("sub-new") cluster-wide, replicating canonical {sub-persist, sub-new} (gen g1) before dispatch/ACK, crashing P, and verifying promoted B1 replays exact {sub-persist, sub-old} for v=1..5 and {sub-persist, sub-new} for v=6 (ContinuousVectorRvvFloorImportDistributedTest.crossReplicaCanonicalAdmissionMatchesAgreeUnderAdversarialSubscriptionChurnAndPrimaryCrash), and 3-server rf = 2 integrated composition test combining primary crash + promotion, multi-sub mid-frame file-backed WAL client crash under Contract S2 (1 Window-A retry deduplicated), reconnect in sessionEpoch=2 rejecting stale epoch=1 ACK(12) (staleSessionAcksRejectedCount=1), and covering HB(12) advancing V_ckpt=12, V_floor=12, tailSize=0 with exact 30/30 oracle == WAL == S2 sink == promoted B1 agreement (ContinuousVectorRvvFloorImportDistributedTest.integratedPromotionPartialFrameClientCrashReconnectAndCoveringWatermarkTest).

Backward Compatibility & Serialization Notes

  • Zero Public API Breakage: All changes are purely additive (+27227 / -0 across 14 files) under org.apache.geode.cache.lucene.internal.vector.continuous and sanctioned-geode-lucene-serializables.txt. Zero existing production classes are modified.
  • Sanctioned Serializables: Registered ChordalVoronoiRouter$RoutingMode, ContinuousVectorEvent (including heartbeat:boolean), IdempotentRvvConsumer$CrashPhase, RvvMonotonicVectorDispatcher$CanonicalApplyOutcome, RvvMonotonicVectorDispatcher$ReplayFloorExceededException, RvvMonotonicVectorDispatcher$TailMutation$AdmissionMatchState, RvvStreamKey, and VectorSubscription 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 "*ContinuousVectorRvv*DistributedTest*" --rerun

./gradlew --no-daemon --max-workers=2 \
  :geode-lucene:integrationTest --rerun \
  --tests "*AnalyzeLuceneSerializablesIntegrationTest*"
Verification Suite Total Passed Failed Skipped Status
:geode-lucene:test --rerun 379 375 0 4 (pre-existing) PASS
PR 4 Continuous Vector Unit Suites (ChordalVoronoiRouterTest 24/24, RvvMonotonicVectorDispatcherTest 72/72) 96 96 0 0 PASS
ContinuousVectorRvv*DistributedTest (Failover 20/20 + FloorImport 5/5) 25 25 0 0 PASS
AnalyzeLuceneSerializablesIntegrationTest 6 6 0 0 PASS
:geode-lucene:spotlessCheck, :checkPom, :javadoc — — 0 — PASS

Goutham added 9 commits November 21, 2026 03:55
… with RVV monotonicity

- Implement ChordalVoronoiRouter (Theorem 1 zero-false-negative chordal Voronoi metric pruning on S^{d-1} with IEEE-754 float32 safety bound; Proposition 1 analytical M_crit crossover with dual-threshold hysteresis [0.85 M_crit, 1.15 M_crit], live add/remove, spherical k-means++, telemetry & FNR verification hooks).
- Implement RvvMonotonicVectorDispatcher and RvvClientGate (Theorem 3 RVV-stamped events sourced from Geode VersionTag/VersionStamp/RegionVersionVector, per-bucket replayable delta tail buffer bounded by V_ckpt <= V_client, promoted-bucket snapshot recovery, and client high-water deduplication & strict per-(subscriptionId, bucketId, memberId) monotonicity).
- Implement ContinuousVectorQueryService facade with Geode CacheListener and PartitionListener bridges.
- Register new Serializable classes in sanctioned-geode-lucene-serializables.txt.
- Add unit tests (ChordalVoronoiRouterTest, RvvMonotonicVectorDispatcherTest) and 4-node failover chaos DUnit test (ContinuousVectorRvvFailoverDistributedTest).
…gate cleanup, serialized callbacks, overflow signal, high-d epsilon)

- PR4-B1 [CRITICAL]: Add per-bucket async primary-promotion barrier (beginAsyncPromotion / completeAsyncPromotion / cancelAsyncPromotion) in RvvMonotonicVectorDispatcher and ContinuousVectorQueryService.createPartitionListener so live post-promotion writes buffer until async tail replay completes and drain in ascending version order.
- PR4-B2 [CRITICAL]: Add RvvClientGate.removeSubscription(String) and ContinuousVectorQueryService.attachClientGate/detachClientGate + compactUpTo so unregisterSubscription purges stale high-water entries and never pins V_ckpt.
- PR4-B3 [HIGH]: Serialize high-water check, advance, and downstream listener delivery per (subscriptionId, bucketId, memberId) StreamState in RvvClientGate.tryAccept to guarantee strict monotonic delivery under concurrent callers.
- PR4-B4 [HIGH]: Replace silent tail eviction on maxTailPerStream overflow with explicit tailOverflowCount, resyncRequired stream tracking, Log4j warn log, and TailOverflowListener callback.
- PR4-B5 [MEDIUM]: Scale ChordalVoronoiRouter float32 dot-product safety epsilon linearly with dimension (max(1e-4, d * 1e-6)) and validate finiteness (reject NaN/Inf) in routeNormalized.
- Add reproducing unit tests covering all 5 defects (PR4-B1..B5).
…ronoi CoW, and Theorem 1 float64 outward rounding

1. Periodic & promotion-end per-bucket RVV watermark heartbeats:
   - Add ContinuousVectorEvent.watermarkHeartbeat(...) and heartbeat flag
     (sanctioned-geode-lucene-serializables.txt updated).
   - Advance RvvClientGate highWaterVersion monotonically across all active
     subscriptions on heartbeat without invoking match callbacks; compute
     strict Theorem 3 Invariant 4 safe checkpoint across all active subscriptions.
   - Emit periodic heartbeats every heartbeatIntervalEvents (default 64,
     configurable, 0 disables) in RvvMonotonicVectorDispatcher and promotion
     watermarks on primary failover so healthy 0%-match subscribers advance
     V_ckpt without tail buffer overflow.
2. True O((M/K)d) per-cell copy-on-write in ChordalVoronoiRouter:
   - Omit global O(Md) flat arrays from CHORDAL_VORONOI RouterSnapshots and
     maintain subscriptionCellIndex for O(1) cell lookup on incremental remove.
   - Copy only the affected VoronoiCell on live insert/remove; materialize
     flat SIMD arrays only on mode switch / survival guard reversion.
3. Exact Theorem 1 float64 arithmetic margin & outward rounding:
   - Add FLOAT64_UNIT_ROUNDOFF (2^-53) and computeFloat64Eta(d) = 2*gamma_{d+2}^f64 + 4*u_f64
     into computeNormMargin(d).
   - Round VoronoiCell.minCosineThreshold outward via
     Math.nextDown(1 - 0.5*(B_k^up)^2 - epsilon_dot - 8*u_f64) (and -Infinity
     when B_k^up >= 2.0).
…ng, reconnect scoping, d=1 & underflow bounds
…ush, and IdempotentRvvConsumer crash recovery
Goutham added 20 commits November 25, 2026 10:49
…tent watermark guard, subnormal/maxCellSize hardening
…er match pending guard, and d=1/tau=1/subnormal tests
…ery, staggered-ACK minimum, and |S|=0 continuity
…ealthy admission, and multi-sub failover trace
…ionEpoch fence, and FIFO reconnect barrier
…Fence epoch/intent revalidation, and holdback bound tests

- RvvMonotonicVectorDispatcher / ContinuousVectorQueryService (R1 M2 / R2 M2):
  Expose V_recv (getReceivedHeadVersion) and V_contig (getContiguousHeadVersion),
  strictly capping V_S = V_contig (nextExpectedVersion - 1 when an active holdback
  gap exists) inside collectReplayableTailForReconnect so reconnect replay never
  emits a trailing heartbeat covering a missing hole and hands off live dispatch
  contiguously at V_contig + 1.
- IdempotentRvvConsumer (R2 M4):
  Revalidate captured sessionEpoch, committed watermark, applied ledger, and
  durable PENDING intent after acquiring streamExecutionFences so an old-session
  staged batch paused before the execution fence cannot execute out of order after
  disconnect or reconnect recovery; add test-only setBeforeExecutionFenceHookForTest.
- JUnit + DUnit coverage (R1 M2 / R2 M2, R2 M4, R1 M3 / R2 M3):
  Add deterministic JUnit tests for active-gap reconnect + crash during lower-pin,
  old-session staged batch pausing before execution fence, and exact maxHoldbackGap=128
  forward-span bound + combined delayed hole/continuing arrivals/age trigger near
  C_tail, plus a 3-server cluster DUnit test covering active-gap reconnect, primary
  crash during lower-pin admission, and near-capacity holdback age trigger.
…nnect uncovered heartbeat timer

- RvvMonotonicVectorDispatcher / ContinuousVectorQueryService (R1 M2, R1 M3, R2 M2):
  - Add CheckpointPinReplicator synchronous replication hook invoked under
    (subscriberRegistryLock, state) strictly BEFORE local lower-pin enrollment or
    releasing any reconnect replay batches in admitAndReplayForReconnect and
    admitSubscriberForContinuity, plus applyReplicatedLowerPin on backups so
    promoted survivors honor lowered (V_floor, V_ckpt_lowered) under
    compactUpToCheckpoint.
  - Initialize oldestUncoveredMutationTimeMs (anchored to the oldest resident
    entry in (V_ckpt, V_contig]) whenever reconnect lower-pin or recovery leaves
    a contiguous uncheckpointed suffix (V_ckpt, V_contig], and clear uncovered
    heartbeat counters in advanceCheckpoint once a stream is fully checkpointed
    and compacted; expose getOldestUncoveredMutationTimeMs.
- JUnit + 3-server DUnit coverage:
  - Add lowerPinDurabilityPointBothCrashSidesAndUncoveredHeartbeatTimerAcrossReconnect
    (JUnit) and lowerPinDurabilityPointCrashSidesAndHeartbeatTimerAcrossCluster
    (3-server kill -9 DUnit) exercising BOTH sides of the lower-pin durability
    point (crash before replication -> survivor compacts to 64 -> resyncRequired;
    crash after replication -> survivor stops compaction at 63 and replays [64..68])
    and verifying oldestUncoveredMutationTimeMs across reconnect lower-pin.
…-2 WAL execution, and 2-backup partial lower-pin guard

- RvvMonotonicVectorDispatcher / ContinuousVectorQueryService (R1 M3 / R2 M2, R1 M4):
  - Separate V_enq (getEnqueuedHeadVersion / getContiguousHeadVersion, strictly
    max(V_floor, nextExpected - 1) while holdback is non-empty so physical entries
    above V_enq are unconditionally bounded by maxHoldbackGap=128 independent of
    async FIFO backlog) from V_disp (getSinkDispatchedVersion, updated strictly
    after sink delivery in dispatchBatchToSinks); expose getPendingDispatchQueueSize.
  - Guard applyReplicatedFloorAndCheckpoint so delayed older checkpoint updates
    cannot raise V_ckpt above min_{s in S_healthy} ack[s] for surviving lower-pinned
    subscribers with ack >= V_floor.
- IdempotentRvvConsumer (R2 M3):
  - Add drainPendingBeforeLocked inside streamExecutionFences in Phase 2 so any
    earlier unapplied PENDING intents (< ver) execute in strictly ascending
    EventDeliveryId order before effectHandler runs for ver, eliminating reverse-order
    handler execution when staged v+1 races ahead of pending v or across recovery.
- Deterministic JUnit coverage:
  - Add delayedFifoWithNewlyOpenedGapSeparatesEnqueuedAndDispatchedFrontiersNearCapacity,
    orderedPhase2ExecutionDrainsEarlierPendingIntentWhenLaterStagedIntentRacesIntoExecutionFence,
    and twoBackupPartialLowerPinApplicationCrashWindowGuaranteesZeroSilentSkipForEveryPromotableSurvivor;
    update legacy out-of-order consumer tests to assert strictly ascending handler order.
…tion HB(V_enq) re-emission, and overflow V_ckpt<=V_enq invariant

- IdempotentRvvConsumer (R1 M2 / R2 M3):
  - Add per-(bucketId, memberId, sessionEpoch) OrderedIngressBarrier via
    processOrderedFrame(event, sessionEpoch, ingressSeq) and
    createOrderedSessionSink(bucketId, sessionEpoch), enforcing synchronous
    Phase-1 durable PENDING staging before releasing the ingress turn for frame
    k+1 (preventing later matches or covering heartbeats from overtaking an
    unstaged earlier match); wake blocked ingress waiters on advanceSessionEpoch
    and expose test-only setBeforeDurableStageHookForTest.
- RvvMonotonicVectorDispatcher (R1 M3, R2 m1):
  - Update emitPromotionWatermarksLocked to immediately enqueue covering HB(V_enq)
    for every active stream with V_enq > V_ckpt on promotion so count-triggered
    heartbeats lost before wire dispatch on primary crash are immediately
    re-emitted even when arrivals stop.
  - Fix reconcileOverflowLocked empty-registry fallback to advance V_ckpt to
    max(V_floor, V_enq) instead of V_recv, preserving V_floor <= V_ckpt <= V_enq
    unconditionally when a holdback gap is open.
- JUnit + 3-server DUnit coverage:
  - Add orderedClientIngressPreventsLaterMatchAndHeartbeatFromOvertakingPausedEarlierStaging
    (JUnit) and primaryCrashBetweenCountTriggerHeartbeatEnqueueAndDispatchReEmitsHeartbeatOnPromotionWhenArrivalsStop
    (JUnit + 3-server kill -9 DUnit), plus open-gap empty-registry overflow check.
… asymmetric lower-pin tests, and durable t_0 boundary tests

- RvvMonotonicVectorDispatcher / ContinuousVectorQueryService (R1 M2, R2 M2):
  - Expose getTailSize(int bucketId, String memberId) and document the monotone
    multi-replica occupancy invariant across partial lower-pin replication and
    up to f promotions: |tail_{r*}(t)| <= max_{r in P(b)} |tail_r(t_0)| +
    |arrivals(t_0, t]| < C_tail.
- Deterministic JUnit + 3-server rf=2 DUnit coverage:
  - Add multiReplicaAsymmetricTailOccupancyAfterPartialLowerPinPromotesLargestReplicaWithoutOverflow
    (JUnit): verifies largest-occupancy backup B2 (missing lower-pin, |tail_{B2}(t_0)|=24 >
    |tail_P|=|tail_{B1}|=21) promotes and replays without overflow under
    max_r |tail_r(t_0)| + arrivals = 31 < C_tail = 32.
  - Add primaryCrashOnBothSidesOfReplicationBoundaryWithArrivalsStoppedPreservesDurableHeartbeatLiveness
    (JUnit): exercises crash before v_0=5 replicates (survivor stays at V_enq=V_ckpt=4,
    zero phantom HB) vs crash after v_0=5 replicates before dispatch (survivor immediately
    emits covering HB(5) with arrivals stopped).
  - Add multiReplicaAsymmetricTailAndDurableReplicationBoundaryCrashSidesAcrossCluster
    (3-server rf=2 kill -9 DUnit): exercises both durable t_0 crash sides and asymmetric
    partial lower-pin promotion of the largest-occupancy replica B2 across a live cluster.
…t, monotone timer anchor, and FLAT_SIMD latch snapshot rebuild

- IdempotentRvvConsumer (R1 M1):
  - Route processOrderedFrame directly into executeStagedPhase2 after releasing
    OrderedIngressBarrier; explicitly recheck isStaleSessionEpoch and
    isAppliedOrRetiredLocked inside (streamExecutionFences, streamStageLock)
    before invoking effectHandler; add JUnit tests for both pause schedules.
- RvvMonotonicVectorDispatcher / ContinuousVectorQueryService (R1 M2, R2 M1, R1 M3 + R2 M2):
  - Have applyReplicatedLowerPin return boolean (false + resyncRequired if
    backup V_floor > V_client) and add applyReplicatedLowerPinOrThrow /
    ReplayFloorExceededException (sanctioned in serializables.txt) so primary
    reconnect admission atomically aborts into RESYNC_REQUIRED if any backup
    already compacted past V_client.
  - Enforce strictly monotone Math.min(existingOldest, anchorTs) in
    ensureUncoveredHeartbeatTimerInitialized so reconnect/lower-pin never moves
    oldestUncoveredMutationTimeMs forward.
  - Add JUnit + 3-server rf=2 DUnit tests for backup-floor resync abort, pre-t_0
    2-backup partial-replication promotion of both B1 and B2 in turn, and
    disjoint pre-t_0 holdbacks merged under universal union bound U_0 + monotone
    heartbeat timer.
- ChordalVoronoiRouter (R2 M3):
  - Track probeCellsExact on RouterSnapshot so any subscription add/remove
    while latched in FLAT_SIMD above M_down forces rebuilding and atomically
    publishing a single immutable RouterSnapshot covering current membership S,
    centroids, r_max, and cell lists on Voronoi re-entry; add JUnit test
    verifying 100% recall of newly added subs and 0 stale removed subs.
… age g_0, and add file-backed batched WAL crash recovery
…nt, atomic backup-compaction floor import, and CRC32 WAL torn-append recovery tests
…c whole-frame WAL durability, and multi-blocker zero-frame tests
…ation, immutable admission match sets, and OP_COVERING_WM integrated recovery
…tion, sessionEpoch ACK fencing, S1/S2 Window-A WAL recovery, Algorithm 2 latch/gen guards, and integrated rf=2 DUnit
…VE/CANONICAL promotion finalization & durableCanonicalFrontier, and L1 WAL barrier / handler non-reentrancy hardening
…orithm 2) and monotonic canonicalTerm fencing + promotion publication guard (Theorem 3)
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