gouthamaenugu opened a new pull request, #8157: URL: https://github.com/apache/geode/pull/8157
# PR 4: Adaptive Chordal Voronoi Continuous Vector Listener with RVV Monotonicity - **Branch:** `gouthamaenugu:feature/GEODE-vector-pr4-rvv-listener` - **Base:** `apache:develop` (`46643af515`) - **Head Commit:** `07c68919d5b53e857e358473099ada79906b4014` (`12 files changed, +7312 / -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.)* - [x] Has your PR been rebased against the latest commit within the target branch (typically `develop`)? - [ ] Is your initial contribution a single, squashed commit? *(Currently 7 clean logical commits — feature implementation, 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, and v9 float64 max-abs norm + `tau` stratification + periodic survival re-probe + RVV reconnect replay — ready to squash on upstream submission.)* - [x] Does `gradlew build` run cleanly? *(Verified `:geode-lucene:spotlessCheck`, `:geode-lucene:checkPom`, `:geode-lucene:javadoc`, `:geode-lucene:test --rerun`, `:geode-lucene:distributedTest --tests "*ContinuousVectorRvvFailoverDistributedTest*"`, and `:geode-lucene:integrationTest --tests "*AnalyzeLuceneSerializablesIntegrationTest*" --rerun`.)* - [x] Have you written or updated unit tests to verify your changes? *(27 new unit tests across 2 JUnit suites + 2 4-node failover chaos DUnit tests.)* - [x] If adding new dependencies to the code, are these dependencies licensed in a way that is compatible for inclusion under [ASF 2.0](http://www.apache.org/legal/resolved.html#category-a)? *(No new external dependencies added; uses Geode 2.1's 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-False-Negative Adaptive Routing (`ChordalVoronoiRouter` & `VectorSubscription`):** Normalizes all finite non-zero float32 vectors (from subnormals to `Float.MAX_VALUE`) via unconditional float64 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, plus 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 IEE E-754 Theorem 3.1, eliminating `Math.sqrt` from the hot path and avoiding the `1 / sqrt(1 - s)` singularity even at `tau_i = 1.0` and `d = 4096`. 2. **RVV-Monotonic Failover & Slow-Reconnect Dispatch (`RvvMonotonicVectorDispatcher`, `ContinuousVectorQueryService`, & `RvvClientGate`):** Tracks per-`(bucketId, memberId)` RVV high-watermarks, maintains a bounded replay tail buffer with checkpoint compaction and overflow resync signaling, gates live writes behind asynchronous tail replay during primary promotion, provides `replayUncheckpointedForReconnect` across both pre-crash `m_P` and post-promotion `m_S` streams under `synchronized (state)`, and enforces strictly monotonic, exactly-once listener delivery across primary node failure and slow client reconnects. --- ## Key Changes ### Adaptive Continuous Vector Routing & Subnormal-Safe Normalization - **`VectorSubscription`**: - Immutable subscription descriptor storing `subscriptionId`, `normalizedQueryVector`, `similarityThreshold`, and derived `chordalTolerance`. - `VectorSubscription.normalize(float[])` uses 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 subnormals (`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. - 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. - 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`) derived from Higham's IEEE-754 Theorem 3.1 so boundary vectors at `tau_i = 1.0` up to 4096 dimensions never suffer floating-point false negatives or square-root singularity. - 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 `RouterSnapshot`s, 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 (`observedSurvivalRate` EWMA) with configurable `maxVoronoiSurvivalRate` (default `0.85`): `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`. When tripped, retains `probeCells` on `RouterSnapshot` and runs a 16-sample (`DEFAULT_SURVIVAL_GUARD_PROBE_BURST_SIZE = 16`) `O(Kd)` re-probe burst every `survivalGuardReprobeInterval` routes (default `4096`, `0` disables) without altering `FLAT_SIMD` results, automatically restoring `CHORDAL_VORONOI` when `p_probe <= maxVoronoiSurvivalRate - survivalGuardRecoveryMargin` (default margin `0.10`, tracked via `survivalGuardRecoveryCount`). ### RVV-Monotonic Failover Dispatch, Slow-Reconnect Replay & Service Facade - **`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. - Emits lightweight per-`(bucketId, memberId)` RVV watermark heartbeats (`ContinuousVectorEvent.watermarkHeartbeat(...)`) periodically every `heartbeatIntervalEvents` primary mutations (default `64`, configurable, `0` disables) and at the end of primary-promotion and reconnect replays so healthy 0%-match subscribers advance `V_client` and unblock safe tail checkpoint compaction (`V_ckpt`) without overflowing the replay tail buffer. - Uses an async replay barrier during primary failover promotion that gates live writes until tail replay completes, eliminating reordering and duplicate windows. - Provides `replayUncheckpointedForReconnect(int bucketId, Map<String, Long> clientHighWaterByMember[, Runnable onReplayedUnderLock])` under `synchronized (state)` replaying `(max(V_ckpt[b, m], clientHighWaterByMember[m]), V_S[b, m]]` across all retained streams `m` (both pre-crash `m_P` and post-promotion `m_S`) plus trailing watermark heartbeats per `m` (tracked via `totalReconnectReplaysHandled`). - Coalesces all matched subscriptions for a mutation into a single `ContinuousVectorEventSink.onEventBatch(List<ContinuousVectorEvent>)` dispatch and supports an optional asynchronous dispatch executor (`setAsyncDispatchExecutor`) with a lock-free per-bucket serial FIFO drain queue so region mutation threads never block on network I/O while preserving strict per-`(bucketId, memberId)` RVV monotonicity across live mutations, promotion replays, and reconnect replays. - **`RvvClientGate`**: - Client-side per-`(subscriptionId, bucketId, memberId)` monotonic gate enforcing strictly increasing RVV delivery across out-of-order and multi-subscription streams (`tryAccept` and `tryAcceptBatch`), serializing concurrent callbacks on the same stream, advancing `highWaterVersion` monotonically across all registered active subscriptions on watermark heartbeats without invoking match listeners, enforcing strict Theorem 3 Invariant 4 safe checkpoint bounds across all active subscriptions, exposing `getSafeHighWaterByMember(int bucketId)` for slow-reconnect handoff, and releasing gate state cleanly on unsubscription. ### New Unit & Distributed Chaos Tests (27 Unit + 2 Failover DUnit) - `ChordalVoronoiRouterTest` (16 tests): zero-FNR verification across thousands of random and boundary vectors, unconditional max-abs float64 normalization across subnormal/extreme vectors (`Float.MIN_VALUE`, `1e-19f`, `1e-30f`, `Float.MAX_VALUE`) 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`, 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, onlin e 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` (11 tests): failover replay exactly-once monotonic delivery, slow client reconnect replaying both pre-crash `m_P` and post-promotion `m_S` retained streams with trailing heartbeats under concurrency, 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. - `ContinuousVectorRvvFailoverDistributedTest` (2 4-node failover chaos DUnit tests): kills the primary server mid-ingestion on a real Geode cluster with both matching subscriptions and a healthy 0%-match orthogonal subscriber (verifying zero missed events, zero duplicates, strict RVV monotonicity, and watermark-driven `V_ckpt > 0` advancement), plus slow reconnect after primary kill with concurrent post-promotion `m_S` writes guaranteeing zero loss via `replayUncheckpointedForReconnect`. --- ## Backward Compatibility & Serialization Notes - **Zero Public API Breakage & Purely Additive:** All changes are purely additive (`+7312 / -0` across 12 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`), `RvvStreamKey`, and `VectorSubscription` in `sanctioned-geode-lucene-serializables.txt`, verified via `AnalyzeLuceneSerializablesIntegrationTest` (6/6 PASS). --- ## Exact Gradle Verification Commands & Pass Counts ```bash ./gradlew --no-daemon --max-workers=2 \ :geode-lucene:spotlessCheck \ :geode-lucene:checkPom \ :geode-lucene:javadoc \ :geode-lucene:test --rerun ./gradlew --no-daemon --max-workers=2 \ :geode-lucene:distributedTest \ --tests "*ContinuousVectorRvvFailoverDistributedTest*" ./gradlew --no-daemon --max-workers=2 \ :geode-lucene:integrationTest --rerun \ --tests "*AnalyzeLuceneSerializablesIntegrationTest*" ``` | Verification Suite | Total | Passed | Failed | Skipped | Status | | :--- | ---: | ---: | ---: | ---: | :--- | | `:geode-lucene:test --rerun` (`50` suites) | 310 | 306 | 0 | 4 *(pre-existing)* | **PASS** | | PR 4 Continuous Vector Unit Suites (`ChordalVoronoiRouterTest` 16/16, `RvvMonotonicVectorDispatcherTest` 11/11) | 27 | 27 | 0 | 0 | **PASS** | | `ContinuousVectorRvvFailoverDistributedTest` (4-node failover + slow reconnect) | 2 | 2 | 0 | 0 | **PASS** | | `AnalyzeLuceneSerializablesIntegrationTest` | 6 | 6 | 0 | 0 | **PASS** | | `:geode-lucene:spotlessCheck`, `:checkPom`, `:javadoc` | — | — | 0 | — | **PASS** | -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
