Repository navigation
fix: keep HNSW cosine boundary scores on exact path - #29136
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes for exact head 84868aa075abe05fa1fe8a8d0eac78866c686457.
[P2] NaN distances make LIMIT 1 return a fabricated successful result.
In pkg/vectorindex/brute_force/brute_force.go:381-401, an F64 cosine index containing [1e200], queried with [1e200] and Limit: 1, produces NaN through Inf/Inf. Because NaN < bestDistance is false, the new selection branch returns key -1, distance MaxFloat64, and no error despite a nonempty dataset. This converts an existing scalar overflow into an invalid row and invented score.
Define non-finite handling consistently for top-1 and heap selection: return an explicit error or preserve valid row identities under a defined ordering. Add all-NaN and mixed finite/NaN regressions. Other HNSW planner and CPU scorer paths looked consistent; GPU, partition/multi-CN, prepared and restart evidence remains incomplete.
84868aa to
a938d82
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
APPROVE — reviewed exact head a938d82. The prior NaN top-1 fabricated-result P2 is fixed: real row IDs are retained, NaNs are handled consistently in top-1/top-K, and regressions cover all-NaN/mixed cases. HNSW cosine fallback, boundary scoring, cancellation and bounded heap/resource behavior show no actionable P0–P2 findings. Exact-head race/UT/BVT evidence passed; partition/distributed/prepared/restart/GPU/scale evidence remains limited.
Merge Queue Status
This pull request spent 28 minutes 1 second in the queue, with no time running CI. Waiting for any of
All conditions
ReasonPull request #29136 has been dequeued Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.
HintYou should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it. Tick the box to put this pull request back in the merge queue (same as
|
…te query (matrixorigin#29082) matrixorigin#29136 fixed the usearch cosine zero/subnormal-boundary bug by disabling the HNSW index for ALL cosine queries (planner returned nil, every cosine search fell back to a full exact scan) -- nullifying ANN for the most common vector metric while still paying to build the cosine graph. Restore native usearch.Cosine ANN and scope the guard to the actual failure: a zero or subnormal query vector whose float32 squared norm underflows the domain usearch computes cosine in. HNSW cosine assumes caller-normalized vectors, so such a query is rejected fail-fast (it is NOT rewritten -- silently normalizing it would disagree with the stored index); a normalized query uses the index. - apply_indices_hnsw.go: drop the blanket cosine gate; cosine plans use the index. - metric.CosineVectorL2Norm(v) (norm, ok): ok=false on float32 squared-norm underflow; norm returned for the diagnostic. Computed once per search, not per row. - hnsw/search.go: error out on !ok for a cosine query; native ANN otherwise. BVT: vector_hnsw_cosine_boundary rewritten (normalized query -> hnsw_search with correct neighbours; zero/subnormal query -> error; scalar path keeps its zero-vector convention). vector_index_optype_matrix cosine block flipped to expect the index, with index score == brute force. Both regenerated and validated 100%. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ranch changed TestUsearchBruteForceCosineNaNOrdering was added by matrixorigin#29136 to pin cosine boundary/NaN top-k ordering on the exact/scalar cosine path. This branch keeps native usearch cosine, so the NaN/overflow (1e200) tie ordering the test asserts is platform-dependent: it passed locally on arm64 but fails on CI (amd64) with different heap ordering of NaN/tied rows. I restored this test in 42c3547 as merge collateral, but it is the same category as its sibling TestUsearchBruteForceCosineNaNOrdering-adjacent TestUsearchBruteForceCosineBoundaryUsesScalarContract, which was deliberately left deleted because it pins the scalar cosine contract this branch no longer implements. Remove it (and the now-unused math import); the native-cosine decision does not guarantee a portable NaN/tie ordering to assert here. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…29040 #29050) (#29100) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [x] Code Refactoring ## Which issue(s) this PR fixes: issue #29040 #29050 #29082 #29083 #29183 #29090 ## What this PR does / why we need it: This PR bundles four vector-index distance fixes. ### 1. Standardize vector distances on the float32 domain (#29040 #29050) Vector index distances are physically float32 -- usearch returns `usearch_distance_t` (typedef float) and cuvs is float32-only -- while MO's scalar `l2_distance` already delivers a float32-precision value for f32 and the narrow bf16/f16/int8/uint8 bases. The index runtime and the pushed range gate, however, kept float64, so an index-served distance disagreed with the same scalar expression by a float32 ULP: a projected value and a `<=`/`>` boundary predicate could observe different values in one row (#29050), and a pushed distance-range gate could flip membership at an exact boundary (#29040). Standardize every distance path on the float32 domain (DOUBLE return type unchanged): - `metric.DistanceTransform{Hnsw,Ivfflat}` round the transformed distance to float32 via `RoundDistanceToElemDomain` (inlined), covering ivfflat/hnsw/brute_force/cagra/ivfpq. - moarray's six scalar metrics round to float32 too, so mode=force / the plain scalar agree with the index for a float64 base (cosine_similarity's 1.0/-1.0 corner snap is subsumed by the round). k-means build is unaffected -- it uses `metric.L2Distance` directly. - `readutil.squareL2BoundOutward` widens the L2 bound to the next float32 before squaring, and `ivfflat.filterEntryDistanceRange` rounds its bounds, so the squared-domain gate and the exact post-filter agree with the float32 distance a row is gated on (#29040). ### 2. Preserve finite-extreme overflow safety without the #29143 perf regression (#29083) #29143 (merged) fixed the finite-extreme overflow (#29083) by adding `Stable*` distance functions -- a per-vector scale pass + scalar float64 loop + `big.Float` -- which drop the float32 SIMD kernels and the cuVS/GPU batch path. That is a broad performance regression and, under the float32-domain model above, redundant: precision beyond float32 is discarded on the exposed distance anyway. This PR **reverts #29143's `Stable*` machinery** and keeps #29083 safe with a focused change: `L2Distance` accumulates the squared sum in **float64** before the `sqrt` and the float32 cast, so a float32 vector whose *squared* distance overflows float32 but whose *distance* is representable returns a finite value. The fast element-typed `L2DistanceSq` (the hot search/pruning kernel) is untouched. A float64 base whose distance genuinely overflows float32 is still rejected fail-fast (fix 1). > Note: this reverts merged PR #29143. Its author should be looped in on the float32-vs-float64 direction, since a later main -> branch merge could otherwise reintroduce `Stable*`. ### 3. Consolidate NormalizeL2 (refactor) `NormalizeL2` was duplicated three times with identical, non-SIMD bodies (two build-tag variants in `pkg/vectorindex/metric` plus a copy in `pkg/vectorize/moarray`). Collapse them into one untagged `metric.NormalizeL2` and make `moarray.NormalizeL2` delegate to it. Behavior is unchanged for every caller (elkans/balanced k-means, the `l2_normalize` SQL builtin over f32/f64 and the narrow bases). ### 4. Restore native cosine ANN for HNSW; reject a degenerate query (#29082) #29136 (merged) fixed the usearch cosine zero/subnormal-boundary bug by disabling the HNSW index for **all** cosine queries -- the planner returned no index and every cosine search fell back to a full exact scan, nullifying ANN for the most common vector metric while still paying to build the cosine graph. This PR restores native `usearch.Cosine` ANN and scopes the guard to the actual failure. HNSW cosine assumes caller-normalized vectors; usearch computes cosine in float32, so only a zero or subnormal query vector -- whose float32 squared norm underflows -- cannot be scored to MO's `cosine_distance`. Such a query is rejected fail-fast (the vector is **not** rewritten -- silently normalizing it would disagree with the stored index); a normalized query uses the index. - `apply_indices_hnsw.go`: drop the blanket cosine gate. - `metric.CosineVectorL2Norm(v) (norm, ok)`: `ok=false` on float32 squared-norm underflow; computed once per search, not per row. - `hnsw/search.go`: error out on `!ok` for a cosine query; native ANN otherwise. ## Validation - **UT** (all green, CGo wrapper): `pkg/vectorindex/metric`, `pkg/vectorize/moarray`, `pkg/vectorindex/hnsw`, `pkg/sql/plan`, plus the whole `pkg/vectorindex/...` tree. Covers the float32-domain contract, the #29083 overflow case (`Test_L2Distance_Float32SquaredOverflow`), `CosineVectorL2Norm`, and the HNSW cosine planner/search paths. - **BVT** (regenerated + validated 100% on a live cluster): `vector_func`, `vector_ivf_prepare_dist_range`, `vector_ivf_quantization`, `vector_hnsw_f64`; `vector_hnsw_cosine_boundary` rewritten (normalized query -> `hnsw_search` with correct neighbours; zero/subnormal query -> error; scalar path keeps its zero-vector convention); `vector_index_optype_matrix` cosine block flipped to expect the index, with index score == brute force. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: fengttt <[email protected]>
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #29082
What this PR does / why we need it:
HNSW cosine search currently exposes usearch scores that do not match MatrixOne's
cosine_distancecontract at the zero/subnormal boundary: zero-vs-zero can bereported as
0, while tiny finite vectors can produce negative or-Infscores.Because HNSW ranks candidates before
DistanceTransformHnswruns, a post-searchclamp cannot restore candidates already discarded by the heap.
This PR:
potentially incorrect score;
including F32/F64, batched queries,
LIMIT 1,K > 1, negative components,and bounded cancellation checks;
finite distances rank before NaNs, and NaNs are appended after finite results;
distances, top-K result sets, derived filtering/aggregation, pagination,
joins, and the existing op-type planner matrix.
This is intentionally correctness-first. All HNSW cosine queries temporarily
lose ANN acceleration and use exact evaluation until the native backend can
provide SQL-compatible boundary semantics. Direct cosine HNSW callers on an
upgraded executor receive an explicit error; mixed-version rollouts must
account for this behavior. No index storage or reindex format changes are
included.
Validation
Validated after rebasing onto
origin/mainatf9a6eb363b463951686b07233245782591f547d0:pkg/sql/planCGo tests: PASSpkg/vectorindex/hnswCGo tests: PASSpkg/vectorindex/brute_forceCGo tests: PASS, including the non-finitecosine regression and index cleanup checks
pkg/vectorindex/metricCGo tests: PASSgofmtandgit diff --check: PASSa938d82a17: PASSThe final local validation did not include GPU hardware, partitioned/multi-CN,
prepared-statement, or restart combinations; no code path, persistence format,
RPC contract, or GPU implementation was changed for this follow-up.
The change is scoped to #29082 and does not address the separate #29050 L2
expression issue or #29083 extreme-magnitude scalar arithmetic issue.