Skip to content

fix: keep HNSW cosine boundary scores on exact path - #29136

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
Lundomn:fix/issue-29082-hnsw-cosine-boundary
Sep 20, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
Lundomn:fix/issue-29082-hnsw-cosine-boundary

Conversation

@Lundomn

@Lundomn Lundomn commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

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_distance contract at the zero/subnormal boundary: zero-vs-zero can be
reported as 0, while tiny finite vectors can produce negative or -Inf scores.
Because HNSW ranks candidates before DistanceTransformHnsw runs, a post-search
clamp cannot restore candidates already discarded by the heap.

This PR:

  • keeps HNSW cosine planner rewrites on the exact SQL path;
  • rejects direct/old cosine HNSW searches explicitly instead of returning a
    potentially incorrect score;
  • adds an exact scalar-contract cosine scorer to the usearch brute-force path,
    including F32/F64, batched queries, LIMIT 1, K > 1, negative components,
    and bounded cancellation checks;
  • handles non-finite cosine results consistently: real row IDs are retained,
    finite distances rank before NaNs, and NaNs are appended after finite results;
  • adds focused unit and SQL regressions for zero/tiny vectors, non-finite
    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/main at
f9a6eb363b463951686b07233245782591f547d0:

  • pkg/sql/plan CGo tests: PASS
  • pkg/vectorindex/hnsw CGo tests: PASS
  • pkg/vectorindex/brute_force CGo tests: PASS, including the non-finite
    cosine regression and index cleanup checks
  • pkg/vectorindex/metric CGo tests: PASS
  • HNSW cosine boundary BVT: 22/22, 100%
  • Existing vector op-type matrix BVT: 85/85, 100%
  • gofmt and git diff --check: PASS
  • Independent final review of head a938d82a17: PASS

The 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.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@mergify mergify Bot added the queued label Sep 20, 2026
@mergify

mergify Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-20 09:31 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-20 09:59 UTC · at 87acd4db11fc25594c0b39dcb5cda27acb839632

This pull request spent 28 minutes 1 second in the queue, with no time running CI.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Reason

Pull 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.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You 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.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@XuPeng-SH
XuPeng-SH merged commit a1220de into matrixorigin:main Sep 20, 2026
20 of 21 checks passed
@mergify mergify Bot added dequeued and removed queued labels Sep 20, 2026
cpegeric added a commit to cpegeric/matrixone that referenced this pull request Sep 21, 2026
…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]>
cpegeric added a commit to cpegeric/matrixone that referenced this pull request Sep 21, 2026
…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]>
fengttt added a commit that referenced this pull request Sep 23, 2026
…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]>

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: HNSW cosine search returns wrong or -Inf scores for zero and tiny vectors

3 participants