Skip to content

fix(vector): reject VECF32 l1_norm/l2_norm that overflow the element domain - #29455

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
cpegeric:bug_29083
Sep 28, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
cpegeric:bug_29083

Conversation

@cpegeric

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:

issue #29083

What this PR does / why we need it:

VECF32 vector distances are computed in the float32 element domain (the design established in #29040 / #29050): a finite vector whose distance leaves that domain is rejected with an error, not returned as +Inf / NaN, so a scalar query and an index (HNSW / cuVS) agree. l1_norm / l2_norm were the one pair of functions that skipped this guard.

blas32.Asum / blas32.Nrm2 accumulate and return a float32, so a finite VECF32 whose norm exceeds the float32 range overflowed to +Inf and was returned silently:

select l1_norm(cast('[2e38,2e38]'   as vecf32(2)));  -- was +Inf, now errors
select l2_norm(cast('[2.5e38,2.5e38]' as vecf32(2)));  -- was +Inf, now errors

That silent +Inf also broke the identity l2_distance(v, 0) == l2_norm(v): the distance already errored on such a vector while the norm leaked +Inf.

Fix: route the float32 norm result through metric.CheckFiniteDist, so l1_norm/l2_norm error identically to the distance kernels ("l1 norm: vector magnitude is too large, the result overflows the element domain"). The identity is restored, on both the error case and the ordinary case.

Unchanged (by design):

Verification

  • Unit test TestF32NormRejectsOverflow in pkg/vectorize/moarray (f32 overflow → error; in-range f32 → finite value; f64 → unchanged).
  • BVT test/distributed/cases/vector/vector_finite_extreme.sql — asserts the SQL errors, the l2_distance(v,0)==l2_norm(v) / l1_distance(v,0)==l1_norm(v) identities on both error and ordinary magnitudes, and that VECF64 norms are unaffected (58/58 pass in run mode).

🤖 Generated with Claude Code

…domain

VECF32 distances are computed in the float32 element domain (matrixorigin#29040/matrixorigin#29050): a
finite vector whose distance leaves that domain is rejected, not returned as
+Inf. l1_norm/l2_norm skipped that guard -- blas32.Asum/Nrm2 return a float32,
so l1_norm([2e38,2e38]) and l2_norm([2.5e38,2.5e38]) silently returned +Inf.
That also broke the identity l2_distance(v,0) == l2_norm(v): the distance
errored while the norm leaked +Inf.

Route the float32 norm result through metric.CheckFiniteDist so it errors
identically to the distance kernels. VECF64 norms (computed in the float64
domain) and in-range VECF32 norms are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@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.

Deep review of 451af532edd5273c66aec67da3ecf737c9bc89e2, merge-base d99187d7b3bfda8744088b3ae8cf16739b690aa0. REQUEST_CHANGES: one functional/design issue remains.

The implementation is small and correctly propagates its newly chosen errors through the SQL scalar wrapper, but it does not satisfy the norm contract recorded in the linked issue. See the inline finding.

The distinction matters here: #29050's index-distance decision does not establish the range of the standalone norm functions. I traced the norm callers to L1NormArray/L2NormArray; their SQL result is DOUBLE, and these helpers are not the HNSW/cuVS score channel. Both the author's norm-specific explanation and the subsequent QA acceptance report explicitly require finite DOUBLE results for the two examples this PR changes to errors. The new tests encode a different acceptance criterion without resolving that issue discussion.

Independent local validation (Darwin/arm64, Go 1.26.4, verified native inputs):

  • Ran the moarray package tests, including the PR's new test. All existing/PR tests passed; the package command exited 1 because the independent DOUBLE-range probe failed for both overflow examples. Its nearest in-range L1/L2 controls passed.
  • For the actual stored float32 inputs, independent widened oracles are approximately 3.999999872114277e38 and 3.535534008024101e38; the head returns errors instead.
  • Challenged the claimed norm/distance identity with float32{1e20, 0}: L2 norm is finite (1.0000000200408773e20), while distance to zero errors because its squared intermediate overflows. Thus adding the norm guard does not establish the stated general identity; the two operations already have distinct intermediate-domain behavior.

I also checked exact-head CI run 36418686324: green, and the BVT artifact confirms vector_finite_extreme.sql executed 58/58 successfully. That verifies the PR's error expectations, not the issue's finite-result expectation.

No additional blocker found in error propagation, null/selection handling, resource ownership, or performance: the proposed guard is constant work per norm result, adds no scan/allocation on the successful path, and introduces no concurrency or retained state. The test additions reuse the existing small fixtures. The ordinary bug-fix scope does not require a new architecture document.

There are no previous inline/human PR reviews to resolve. The linked issue's norm-specific comments are the unresolved item. Suggested fix: widen the F32 norm reduction itself before overflow, preferably without a per-row temporary F64 vector; preserve the existing F64 behavior and test finite DOUBLE results plus nearby controls. If a deliberate product change to a float32-limited norm is desired instead, explicitly reconcile and supersede the norm-specific issue contract; the index-score rationale alone does not justify it.

Comment thread pkg/vectorize/moarray/external.go Resolved
…ring (matrixorigin#29083 review)

l1_norm/l2_norm are DOUBLE functions (both the vecf32 and vecf64 overloads return
T_float64), not index scores, so the HNSW float32-domain contract does not apply
to them. The prior commit rejected a finite VECF32 whose norm exceeds the float32
range, but the issue -- and the author's norm-specific analysis and the QA
acceptance criteria -- require the representable finite double.

Root cause was the premature float32 reduction: blas32.Asum/Nrm2 accumulate in
float32 and overflow a finite vector's norm to +Inf. Accumulate in float64
instead: a sum of finite float32 elements (or their squares) cannot overflow
float64, so the f32 norm is always finite and needs no error path. This also
drops blas32.Nrm2's scaling branch, making the path faster (up to ~2.4x on
l2_norm at small dims, faster at every width measured) and more accurate.

The claimed l2_distance(v,0)==l2_norm(v) identity does not hold and is removed:
l2_norm([1e20,0]) is finite while l2_distance([1e20,0],0) rejects its float32-
squared intermediate -- norm and distance have different contracts by design.

VECF64 norms are unchanged: blas64.Nrm2's scaling is load-bearing there (no wider
accumulator exists, and it returns a finite result for a representable norm like
[1e300,1e300] where a naive float64 sum-of-squares would overflow).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ation

The DOUBLE-widening of VECF32 l1_norm/l2_norm (matrixorigin#29083) makes those functions
return the accurate float64 result instead of the older, less accurate
float32-reduced value. Update the hardcoded expectations to match:

- UT TestL2NormArray / moarray TestL2Norm: exactly-representable VECF32 inputs
  (1..6) now yield the same value as the VECF64 case (e.g. sqrt(14) =
  3.741657386773941, not the float32 3.741657257080078).
- BVT array.sql (t7) and vector_func.sql (vtab32): the l2_norm/l1_norm result
  values on non-exact VECF32 vectors shift to their representable double form.
  Only the l1_norm/l2_norm value lines are updated; SUMMATION/inner_product and
  all metadata are untouched (they are unaffected by the change), and
  array_alter_dimension is unchanged (its value is l2_distance, not a norm).

Values verified against the running server; both BVTs re-pass at 100% under the
CI comparison mode (-g -n).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

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

Deep re-review · d18127e1850b

APPROVE. The previous norm-contract blocker is resolved in the implementation. Reviewed all eight changed files against base/merge-base d99187d7b3bfda8744088b3ae8cf16739b690aa0, the prior review/thread, and #29083's norm-specific author/QA comments. No subagents.

The final design is appropriate: widen each stored float32 element before reduction and return the representable DOUBLE norm. The finite float32 domain is small enough that neither its squared elements nor their sum over an addressable slice approaches float64 overflow; even the smallest nonzero float32 square is representable in float64. Thus the direct L2 loop does not need BLAS's scaling machinery for this input domain. It keeps one pass, constant extra space, and no temporary float64 vector. The unchanged float64 L2 path retains its scaled BLAS algorithm. This is a focused ordinary bug fix, not a new architecture requiring a separate design document.

I traced the SQL overloads and unary wrapper, including NULL/selection handling, and checked the distance/index counterpart. The norm's DOUBLE contract is now correctly distinct from the float32 distance-score contract. This changes some ordinary norm results' low bits as well as fixing premature overflow; the norm-related result updates reflect that intended precision improvement. No additional blocker found in error propagation, resource ownership, or concurrency: the changed loops introduce no new allocations, retained state, waits, or failure cleanup paths.

Independent validation at this head (Darwin/arm64, Go 1.26.4):

  • Complete pkg/vectorize/moarray tests passed, including a private independent math.Hypot oracle for max/min-subnormal, mixed magnitude, signed zero, empty, ordinary and distance-intermediate inputs. Package: 2.045 s.
  • A private real SQL/MySQL-protocol probe passed: the issue's two inputs return 3.999999872114277e38 and 3.535534008024101e38; ordinary literal L2 and NULL behavior also pass. The unchanged inner-product control returns its original float32-rounded score. Test 11.43 s; package 13.395 s.
  • Compared old BLAS and new loops in one benchmark binary, with a consumed result and allocations reported. At dimensions 2/128/1024, L1 old→new was 5.20→3.10 / 78.2→72.7 / 793→665 ns; L2 was 7.07→2.48 / 179→79.5 / 1190→894 ns. All cases allocate zero. These are local samples, not a cross-platform or query-throughput claim.
  • Reused current-head CI run 36446668039, including UT/SCA and the actual compose BVT artifact: array.sql 201/201, vector_finite_extreme.sql 59/59, vector_func.sql 229/229, no ignored statements. These are executed cases, not merely a green rollup. Local native inputs matched a provenance-verified CPU artifact; the initial wrapper's missing-worktree-artifact rejection is not counted as a test pass.

Two non-blocking cleanup notes:

  1. Rewrite the PR title/body around the final implementation. They still say norms reject float32 overflow and restore norm/distance error equality; that describes the superseded implementation and conflicts with both current code and #29083's accepted contract.
  2. Keep the checked-in result values faithful to their operations. vector_func.result:139-141 changes the unrelated inner_product(v,[1,1,1]) values to widened sums, although this PR does not change inner product. The first actual result remains -1.9714267253875732, not -1.9714266657829285. Conversely line 401 retains the old l2_norm('[1,2,3]') value although actual SQL now returns 3.7416573867739413. Both differences are small enough for the current floating comparison to pass; they do not demonstrate a production failure, but the baseline should record the correct values.

The previous substantive review comment is resolved; the above cleanup notes are separate from that closed blocker. Approval is for this commit's code and tests, not for the stale PR description's claims.

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

mergify Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-28 17:35 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-28 17:36 UTC · at 0d1c04d65a67d34bdee6e32a538badfc65a55a0a

This pull request spent 1 minute 22 seconds in the queue, with no time running CI.

Reason

Pull request #29455 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.

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

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 a543410 into matrixorigin:main Sep 28, 2026
20 of 21 checks passed
@mergify mergify Bot added dequeued and removed queued labels Sep 28, 2026

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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants