Skip to content

Reject NaN/Inf and zero-magnitude vectors in vector similarity index - #104079

Merged
rschu1ze merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-8146-usearch-i8-nan-zero
May 9, 2026
Merged

rschu1ze merged 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-8146-usearch-i8-nan-zero

Conversation

@groeneai

@groeneai groeneai commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator
Fixes UndefinedBehaviorSanitizer report **STID 8146-795a** reproduced under `Stress test (experimental, serverfuzz, arm_ubsan)`:

runtime error: nan is outside the range of representable values of type 'signed char'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior
contrib/usearch/include/usearch/index_plugins.hpp:1216:42

The AST fuzzer drove a `SELECT` through `MergeTreeIndexConditionVectorSimilarity::calculateApproximateNearestNeighbors` → `index->search` → `unum::usearch::cast_to_i8_gt<double>::try_`, where the cast `static_cast<std::int8_t>(NaN)` is UB.

### Root cause

`unum::usearch::cast_to_i8_gt::try_` (called by USearch internally to convert query and indexed vectors to `i8`) is undefined behavior for two classes of input:

1. **Any non-finite element** (NaN or ±Inf): the cast `static_cast<std::int8_t>(NaN)` is UB.
2. **A zero-magnitude vector with `i8` quantization**: USearch normalizes by the magnitude before quantizing, so the per-element ratio is `NaN`, then casts to `int8` (UB).

Both cases also produce silent garbage in non-sanitizer builds (USearch ends up indexing / searching with implementation-defined `int8` values). They are nonsensical at the user-facing level.

### Fix

Reject these inputs at the ClickHouse → USearch boundary, where the codebase already validates user input (e.g. dimension mismatch).

A new helper `validateVectorElementsForUSearchOrThrow` is called from:
- `MergeTreeIndexConditionVectorSimilarity::calculateApproximateNearestNeighbors` — rejects bad reference vectors with `INCORRECT_QUERY`;
- the per-row `add_vector_to_index` lambda inside `updateImpl` — rejects bad indexed vectors with `INCORRECT_DATA`.

NaN/Inf is rejected for every quantization (`f32`, `f64`, `bf16`, `f16`, `i8`, `b1`); zero-magnitude is rejected only for `i8`, since other quantizations don't divide by the magnitude.

### Test

`tests/queries/0_stateless/04202_vector_search_i8_quantization_validation.sql` covers NaN, +Inf, −Inf, and zero-magnitude inputs on both `i8` and the default (`bf16`) quantization, exercising both the SELECT and INSERT paths. The test fails on master (queries succeed silently with garbage) and passes with the fix.

CI report: <https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4aa433a573ba3177b4a879a0e24d689601728c60&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_ubsan%29>

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reject non-finite vectors (nan, +-inf) during vector search, e.g. as searched vectors or as reference vectors. These cause undefined behavior in usearch.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.474

Fixes UndefinedBehaviorSanitizer report (STID 8146-795a) reproduced under
`Stress test (experimental, serverfuzz, arm_ubsan)`:

    runtime error: nan is outside the range of representable values of type 'signed char'
    SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior
    contrib/usearch/include/usearch/index_plugins.hpp:1216:42

`unum::usearch::cast_to_i8_gt::try_` is undefined behavior for two classes
of input:
  - any non-finite element (NaN or +/-Inf): the cast
    `static_cast<std::int8_t>(NaN)` is UB.
  - a zero-magnitude vector with `i8` quantization: USearch normalizes by
    the magnitude before quantizing, so the per-element ratio is NaN, then
    casts to int8 (UB).

Both cases also produce silent garbage in non-sanitizer builds (USearch
indexes / searches with implementation-defined int8 values). They are
nonsensical at the user-facing level, so we reject them at the boundary.

The new helper `validateVectorElementsForUSearchOrThrow` is called both
from `MergeTreeIndexConditionVectorSimilarity::calculateApproximateNearestNeighbors`
(rejects bad reference vectors with `INCORRECT_QUERY`) and from the
per-row `add_vector_to_index` lambda inside `updateImpl` (rejects bad
indexed vectors with `INCORRECT_DATA`). NaN/Inf is rejected for every
quantization; zero-magnitude is rejected only for `i8`, since other
quantizations don't divide by the magnitude.

Adds regression test `04202_vector_search_i8_quantization_validation`
covering NaN, +Inf, -Inf, and zero-magnitude inputs on both `i8` and the
default (`bf16`) quantization, exercising both the SELECT and INSERT paths.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4aa433a573ba3177b4a879a0e24d689601728c60&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20arm_ubsan%29
@groeneai

This comment was marked as resolved.

@groeneai

This comment was marked as resolved.

@rschu1ze rschu1ze self-assigned this May 5, 2026
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c4db417]

Summary: ✅


AI Review

Summary

The PR adds input validation for vector similarity indexes to reject non-finite elements (NaN/Inf) and reject zero-magnitude vectors for i8 quantization before calling USearch, then updates stateless coverage for these cases. I did not find additional correctness, safety, performance, or compatibility issues beyond the already-posted bot typo notes.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.20% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.70% 76.70% +0.00%

Changed lines: 94.44% (34/36) · Uncovered code

Full report · Diff report

@rschu1ze
rschu1ze added this pull request to the merge queue May 9, 2026
Merged via the queue into ClickHouse:master with commit 088b85d May 9, 2026
165 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: MergeTreeIndexVectorSimilarity::updateImpl and calculateApproximateNearestNeighbors — core code present in all supported branches.

Why this might apply: The vector_similarity index and the affected code paths (updateImpl, calculateApproximateNearestNeighbors) exist in 25.8 branch. The UB being fixed can cause silent data corruption in non-sanitizer builds when users insert NaN/Inf values or zero-magnitude vectors with i8 quantization.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

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

Labels

can be tested Allows running workflows for external contributors pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants