Skip to content

Reject i8 vectors whose squared magnitude overflows to infinity - #111085

Merged
rschu1ze merged 7 commits into
ClickHouse:masterfrom
groeneai:fix/usearch-i8-overflow-magnitude-8146-795a
Jul 28, 2026
Merged

rschu1ze merged 7 commits into
ClickHouse:masterfrom
groeneai:fix/usearch-i8-overflow-magnitude-8146-795a

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

Resolves #111621

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Reject vectors whose squared magnitude overflows to infinity when using a vector_similarity index with i8 quantization (previously such vectors triggered undefined behavior in usearch and produced silent garbage).

Description

Follow-up to #104079, which added checkVectorIsSane to reject non-finite elements and, for i8 quantization, zero-magnitude vectors. That guard missed one more class of undefined behavior.

usearch's cast_to_i8_gt (index_plugins.hpp:1216) quantizes a vector by scaling each element by 127 / sqrt(magnitude_squared). A vector with finite elements but a very large one (e.g. an element around 1e300) has a squared magnitude that overflows to +inf, so element * 127 / inf becomes nan, and the subsequent static_cast<std::int8_t>(nan) is undefined behavior:

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

Such a vector has finite elements and a non-zero magnitude, so it passed checkVectorIsSane and reached the i8 cast both as a reference vector (MergeTreeIndexConditionVectorSimilarity::calculateApproximateNearestNeighbors -> index->search) and as an indexed vector (updateImpl). In non-sanitizer builds this silently indexes/searches with implementation-defined int8 values.

Fix: reject non-finite magnitude_squared for i8 in checkVectorIsSane, next to the existing zero-magnitude check. This covers both the search and insert paths in one place. Non-i8 quantizations are unaffected (they do not divide by the magnitude).

Found by the AST fuzzer, STID 8146-795a, Stress test (arm_asan_ubsan):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109261&sha=e532419f9209dd0e350462cfcc698dcbe4c1f31d&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

Test: extended 02354_vector_search_undefined_behavior.sql with overflow-magnitude cases for both the reference vector and the indexed vector (the latter needs an Array(Float64) column, since Float32/BFloat16 elements are too small to overflow the Float64 sum of squares). The queries fail on master (succeed silently) and pass with the fix.

Version info

  • Merged into: 26.8.1.291 (included in 26.8 and later)

checkVectorIsSane already rejects non-finite vector elements and, for i8
quantization, zero-magnitude vectors. It did not reject vectors whose squared
magnitude overflows to infinity. Such a vector (e.g. an element around 1e300)
has finite elements and a non-zero magnitude, so it passed the guard, but
usearch's cast_to_i8_gt scales each element by 127 / sqrt(magnitude_squared);
with an infinite magnitude the scaled value becomes nan and the subsequent
static_cast<int8_t>(nan) is undefined behavior (UBSan: nan is outside the range
of representable values of type 'signed char', index_plugins.hpp:1216).

Reject non-finite magnitude_squared for i8 in the same place, covering both the
reference vector (search) and the indexed vector (insert) paths.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. SELECT id FROM t ORDER BY L2Distance(vec, [1e300, 1.0, 1.0]) LIMIT 1 on an i8-quantized index triggers it every time. A standalone repro of the usearch cast under -fsanitize=float-cast-overflow emits the exact CI diagnostic.
b Root cause explained? YES. For i8, usearch scales each element by 127/sqrt(magnitude_squared). A finite but huge element (~1e300) overflows magnitude_squared to +inf, so element*127/inf = nan and static_cast<int8_t>(nan) is UB. checkVectorIsSane rejected non-finite elements and zero magnitude, but not an overflowed (infinite) magnitude.
c Fix matches root cause? YES. Adds if (i8 && !std::isfinite(magnitude_squared)) throw in checkVectorIsSane, exactly the missing condition. Not a band-aid.
d Test intent preserved / new tests added? YES. No existing assertion weakened. Added 3 new serverError cases to 02354_vector_search_undefined_behavior.sql (overflow reference vector on i8 Float32 and Float64 indexes; overflow indexed vector on i8 Float64 index).
e Demonstrated in both directions? YES. Without the fix, the overflow SELECT returns a row and the overflow INSERT succeeds with no error (silent UB; EXPLAIN indexes=1 confirms the index is used). With the fix they throw INCORRECT_QUERY / INCORRECT_DATA; control queries and non-i8 indexes are unaffected.
f Fix is general, not a narrow patch? YES. The change is in the single shared checkVectorIsSane, so it covers both call sites (reference vector and indexed vector) at once. The only other i8 cast is inside vendored usearch; rejecting at the ClickHouse boundary is the layer #104079 established.
g Fix generalizes across inputs? YES. The reference vector is always Float64, so the guard fires for any index column type. Indexed vectors only overflow with Array(Float64) (Float32/BFloat16 elements are too small); the test covers both. Completeness: if magnitude_squared is finite and non-zero then `
h Backward compatible? YES. No setting/format/metadata change. A previously silently-corrupt (UB) input now raises a clear error; such vectors never produced meaningful results.
i Invariants and contracts preserved? YES. checkVectorIsSane is a stateless validation helper; one more throw path preserves its contract. Reuses the already-computed magnitude_squared. No lock/ownership/block-structure invariants touched.

Session id: cron:clickhouse-author-slot-1:20260720-141400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Independent second-model (codex) review of the diff before opening this PR.

Result: 0 findings on the final fix diff (2 files, +31/-2).

❌ Blockers: none.

⚠️ Majors: none on the fix. (An initial review pass ran against a transient working-tree state that carried unrelated submodule pointer drift from switching the worktree base onto master; that drift was never part of the commit. It was restored to base and the review re-run against the actual 2-file diff came back clean.)

💡 Nits: none.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze — follow-up to #104079: checkVectorIsSane still let through i8 vectors whose squared magnitude overflows to +inf (e.g. an element ~1e300), so element*127/inf = nan reached the i8 cast and hit the same UBSan report (STID 8146-795a). This rejects non-finite magnitude_squared for i8 alongside the existing zero-magnitude check.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fbab68b]

Summary: ✅


AI Review

Summary

This PR closes the obvious forward i8 UB by rejecting vectors whose accumulated magnitude_squared becomes non-finite before they reach usearch. The logic change itself is small and targeted, but the current head still has a backward-compatibility gap for already-written Array(Float64) i8 index data, and the new regression test still does not prove the indexed-vector INSERT path the PR description claims to cover.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp:260-278, 314-347, 351-387] [dismissed by author -- https://github.com/Reject i8 vectors whose squared magnitude overflows to infinity #111085#discussion_r3616766767] The issue is still present in the current code: deserializeBinary still accepts FILE_FORMAT_VERSION = 1, while the shared checkVectorIsSane path in updateImpl now throws on the same legacy Array(Float64) rows during merge/mutation/index rebuilds. That means an upgrade can keep loading already-corrupted i8 index blobs until the next rebuild, then start failing background work on pre-existing data. Suggested fix: either invalidate legacy index files with an explicit rebuild path, or gate the stricter rebuild-time validation so upgrades do not start rejecting existing parts silently accepted by older releases.
Tests
  • ⚠️ [tests/queries/0_stateless/02354_vector_search_undefined_behavior.sql:49-60] The new INSERT case is weaker than the contract. This table is Array(Float32), so the 1e300 literal narrows to +inf before checkVectorIsSane runs and is rejected by the pre-existing per-element non-finite check; the new !std::isfinite(magnitude_squared) branch in updateImpl is still unproven. Add a separate Array(Float64) + i8 table for the indexed-vector INSERT case so a finite value survives input conversion and overflows only during magnitude_squared accumulation.
Final Verdict

Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0f66431

CI finished on this head. None of the reds relate to this PR's change (the usearch i8 magnitude-overflow guard in MergeTreeIndexVectorSimilarity.cpp). Each has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error 'Not-ready Set is passed as the second argument' (STID 0250-41a5) logical-error (chronic trunk, 10 master + 40+ unrelated PRs/30d; NOT PR-caused, unrelated to vector index) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04507_mvt_encode_state_serialize flaky (Code 70 Tuple->Geometry in MVTEncodeMerge state serialize; 9 master + 15+ unrelated PRs/30d) #110886 + #111041 (external, open)
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) crash (chronic coverage-job server abort; job-level, no distinct test row) #109747 (ours, open) + #110048 (external, open)
Mergeable Check / PR aggregators reflecting the reds above no separate failure

Session id: cron:our-pr-ci-monitor:20260721-013000

@Manerone Manerone self-assigned this Jul 22, 2026
-- There are other zero-magnitude vectors, but we can't test the other ones reliably because of rounding errors
-- There are other zero-magnitude squared vectors, but we can't test the other ones reliably because of rounding errors
INSERT INTO tab VALUES (12, [0.0, 0.0, 0.0]); -- { serverError INCORRECT_DATA }
INSERT INTO tab VALUES (12, [1e300, 1.0, 1.0]); -- { serverError INCORRECT_DATA }

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.

This insert does not actually exercise the new overflowed-magnitude_squared path on the indexed-vector side. updateImpl validates the materialized column value, and this table is Array(Float32), so by the time checkVectorIsSane runs the 1e300 literal has already narrowed to a non-finite Float32 and is rejected by the pre-existing per-element !std::isfinite(casted) check. The bug fixed here on inserts only exists for Array(Float64), where a finite value can survive input conversion and overflow only when magnitude_squared is accumulated. Can we move the insert-side case to a separate Array(Float64) table so the new branch is actually covered?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b06e7cc

All four reds are unrelated trunk/infra failures with owners; none is caused by this PR (its diff touches only MergeTreeIndexVectorSimilarity.cpp and the vector-search test). Safe to merge from the CI side.

Check / test Reason Owner
Upgrade check (amd_release) / New+Changed settings not in history (join_runtime_filter_min_probe_rows) trunk regression: the introducing PR #104860 placed the history entry in the 26.7 section, so the upgrade check flags it on every PR fixing PR #111671 (ours, open)
Stateless (amd_llvm_coverage, ParallelReplicas, s3) / unknown stream (STID 5217-5b3d) + Server died trunk logical error in the parallel-replicas reading coordinator (66 PRs + 3 master / 30d) a fix task is investigating at full effort (fixing-PR link to follow here)
Fast test (arm_darwin) / Server died chronic macOS native-runner flake, issue #103235 (23 PRs / 3d) a fix task is tracking it
Stress test (arm_msan) / Cannot start clickhouse-server chronic host-memory-pressure server-startup flake (85 PRs + 10 master / 30d) a fix task is tracking it

Session id: cron:our-pr-ci-monitor:20260723-213000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c51fc91

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / Server died + 03634_autopr_input_bytes_estimation_compact macOS native-runner instability (57 hits / 52 unrelated PRs / 0 master in 30d) a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Upgrade check (amd_release) / Error message in clickhouse-server.log (SystemLog (system.metric_log): Failed to mark the rotated system log table as readonly, Code 229) trunk error-log leak #111703 (external, merged 2026-07-24T17:24:53Z) - NOT on this branch (git merge-base --is-ancestor eb577ff401a3 c51fc912aba30b1b7335dc2efb57f098f43e93ef is false), so this build predates the fix; merging master will pick it up

The Fast-test red is the arm_darwin runner losing the server, not this PR's diff: Fast test on amd is green on the same head, and the same PR-only signature fires across 52 unrelated PRs with zero master hits.

Session id: cron:our-pr-ci-monitor:20260726-163000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Owner update for the Fast test (arm_darwin) / Server died line on this pull request's CI finish
ledger.

That failure is a hang on the macOS native runner, not a fault in this pull request's diff. It was
introduced by #109825; the crash half was fixed by #111656, and a ~2.7% residual hang half remains
with no open tracking issue. I posted the full forensics (global instant freeze, 17 of 21 system
logs stuck mid-flush, the named failing test always a _cleanup_database victim, plus the job-level
rate step from 0.04% to 4.3% at the #109825 merge hour) here:

#111579 (comment)

No fixing pull request exists yet, and I am deliberately not opening a speculative one: the stuck
lock cannot be named without a thread dump, the lldb dump is currently discarded by the test
harness (covered by the open #107173), and I have no native macOS-arm64 host to reproduce or
validate a fix on. I have asked the component owner who carries the hang half. When a fixing pull
request opens, I will post the link here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5ada62e

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

This head is a plain master merge on top of the previously ledgered c51fc912aba3, so the
diff under review is unchanged. None of the three reds touches this PR's files
(src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp,
tests/queries/0_stateless/02354_vector_search_undefined_behavior.sql).

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Inconsistent KeyCondition behavior (STID 5182-2f27) debug-only monotonicity canary on a widened-type key comparison (issue #90461), fuzzed 04612_reverse_key_index_analysis query #109023 (ours, open)
Stress test (arm_debug) / Inconsistent KeyCondition behavior (STID 5182-2f27) same canary, arm build (arch-split STID of one defect) #109023 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log — Failed to read version metadata for part ...: Code: 27 ... expected '\n' before: 'version: 1\nstoring_version: 0 ...' trunk-wide upgrade-check leak, onset 2026-07-23, 0 master; the previous-release test files are frozen so no master-side test change clears it #111772 (ours, open)
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260727-043000

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code

Full report · Diff report

@rschu1ze
rschu1ze enabled auto-merge July 28, 2026 14:53
@rschu1ze
rschu1ze added this pull request to the merge queue Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fbab68b

CI has fully finished on this head with no failures: 174 check-runs, all completed,
0 failures (Finish Workflow green), and CIDB records no FAIL or ERROR row for this
pull request in the window. There is nothing to own.

Head fbab68b2258f is @ rschu1ze's own master merge, so I validated and ledgered only:
no push, no rebase, no master merge from me.

Session id: cron:our-pr-ci-monitor:20260728-163000

Merged via the queue into ClickHouse:master with commit 1a506aa Jul 28, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
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-bugfix Pull request with bugfix, not backported by default 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.

UBSan: NaN cast to signed char in usearch i8 quantization when reference vector magnitude overflows to Inf (STID: 8146-795a)

5 participants