Skip to content

fix(sql): return mathematical dot product from INNER_PRODUCT - #29711

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
ck89119:issue-29703-main
Oct 9, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
ck89119:issue-29703-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 8, 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:

Closes #29703

What this PR does / why we need it:

Make SQL INNER_PRODUCT(a, b) return the mathematical dot product Σaᵢbᵢ: the issue example now returns 32, and its self-product returns 14.

  • Convert scores at the scalar, float32 batch, narrow-vector, and shared index-output boundaries while retaining internal negative-dot distance kernels and IVF centroid routing.
  • Allow maximum-inner-product nearest-neighbor rewrites for DESC, not ASC. Keep ASC on the exact path; preserve L1/L2/cosine behavior.
  • Align IVF internal SQL, storage ordering, exact reranking, INCLUDE values, and public-score range filtering with that contract.
  • Cover all six vector types, expression layouts, signs, NULL/error behavior, ordering eligibility, and IVF/HNSW indexed-versus-unindexed score parity.
  • Regenerate affected BVT result blocks with mo-tester while preserving unrelated historical output.

Compatibility

Applications relying on historical negative scores must use -INNER_PRODUCT; applications using ASC for maximum similarity must switch to DESC. Review score thresholds and derived scores as well. Index storage formats are unchanged and existing indexes do not require rebuilding. Do not mix old/new SQL semantics during rolling upgrades. See docs/CLAUDE_inner_product_semantics.md for migration and rollback guidance.

External MOI documentation and the separate HNSW offset issue #25965 are outside this change.

Validation

  • Go 1.27.1, matching gofmt, repository mo-cgo-test, rebuilt native prerequisites, and successful make build.
  • Full affected-package suites passed: moarray, metric, brute_force, ivfflat, plan, and function (function's final full run was executed independently); focused INNER_PRODUCT regression suites passed.
  • Changed executable-line coverage: 47/50 = 94.0% (required ≥75%).
  • go vet passed; repository-pinned golangci-lint v2.14.0 reported 0 issues; git diff --check passed.
  • A clean-base regression run failed with expected 32, actual -32.
  • Real local frontend verification and two-round mo-tester value comparisons with -n for 13 affected BVT files, including final regenerated IVF/HNSW cases; scalar/index-matrix database teardown verified. These runs did not validate column metadata.
  • One repeated full-suite run hit an Eventually timeout in the unchanged TestReleaseUserLevelLocksOnSessionCloseRetainsSaturatedHandoffAndRecovers. An exact-main source-overlay comparison and the subsequent final function package run passed. That test was not modified or skipped; its stability is not established by the passing runs.

Follow-up review / CI fixes

  • Migrate TestIssue28378IVFFlatRemoteLifecycle to IP DESC without removing its two-CN remote-execution, cancellation, connection, or cleanup assertions.
  • Replace the four failing large-float32 SQL golden queries and the related MIN control with independent float64 elementwise-product/SUMMATION references and a dimension-appropriate 1e-6 relative-error oracle. Preserve row IDs, NULLs, sign, aggregation, and derived-table/CTE coverage; no ignore/skip tags were added.
  • Migrate CAGRA/IVF-PQ maximum-IP fixtures to (1,1292) with DESC, add ASC minimum-IP (6,15) controls, and migrate both pairwise modes to DESC / (9999,258169).
  • Merge current main (83d82b8ee0) and regenerate only the affected result blocks with mo-tester.

Follow-up evidence:

  • Final full pkg/tests/issues: PASS, 303.731s; focused lifecycle normal and coverprofile modes: PASS. The issues package itself contains no production statements; the prior changed-production-line coverage evidence remains 94%, with the production math/rewrite closure unchanged by this test-only follow-up.
  • Fresh latest-main-merged binary: build, incremental vet, pinned lint (0 issues), formatting and diff checks passed.
  • Final scalar BVT and the same-data CPU public-oracle projection of the three GPU fixtures passed two value-comparison rounds with -n, with teardown verified. GPU result values were additionally checked against independent dot products; GPU index metadata and unrelated metrics were preserved. Column metadata was not compared in those runs; the pairwise omission is corrected below.
  • An earlier full issues run failed join-spill admission while free disk was approximately 2GiB: automaticSpillDiskCap intentionally reduces the cap to one byte below its 16GiB headroom threshold. With sufficient space, an exact-main source-overlay full suite and the final candidate full suite passed. No spill code, test, budget, or assertion was changed to hide that environment failure.

Pairwise column-metadata correction (P2)

  • The result-merge helper incorrectly preserved pairwise's historical ip[8,54,0] header. Pairwise has no index-specific result schema; regenerate its two IP headers from the actual SQL output: ip[8,53,31]. No query, value, production code, skip, or comparison rule changed.
  • The original vector_pairwise_mode.sql without -n reproduced exactly two metadata failures (exit 1). After genrs, both strict comparison rounds passed 18/18 statements, exit 0, and database teardown was zero.
  • Merged current main (dca6ffc2bf). For this artifact-only protocol fix, reused the existing 83d82b8ee0-based binary after checking that the INNER_PRODUCT typing/implementation, container types, and MySQL frontend metadata producers are unchanged. This evidence establishes the corrected SQL/metadata oracle, not a fresh build/full-suite validation of all newer main changes.
  • Strict pairwise checks ran on the CPU build with both gpu_mode settings; CUDA execution remains unverified. Other earlier -n runs are value-only evidence, not strict metadata passes.

Environment limits: BVT used a local single-CN macOS service; the lifecycle UT exercised an embedded two-CN cluster and remote pipelines. Actual CUDA/GPU execution and standalone/compose multi-CN BVT were not run locally. GPU fixture score oracles were generated/compared on the CPU exact path; this does not establish CUDA index or offload runtime parity, which still needs CUDA-capable validation.

@ck89119
ck89119 requested a review from fengttt as a code owner October 9, 2026 06:49
@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 →

@aunjgr aunjgr 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 at b2f41d7 against declared base b6fa8cc. No blocking correctness finding confirmed.

Reviewed scalar/constant/batch/narrow-vector sign conversion, common index-output transforms, internal brute-force centroid routing, IVF SQL/relation-reader ordering, exact reranking/INCLUDE alignment, public-score range filtering and ASC/DESC rewrite admission. Public scores change to dot while candidate kernels retain negative-dot; DESC serves maximum-IP neighbors and ASC stays on the exact path. The storage reader still resolves the internal metric, while scalar-generated candidate scores are negated back before internal ranking. IP range predicates deliberately disable incompatible negative-domain storage range pushdown and are applied before Top-K. Existing algorithm registration and storage formats are unchanged; no new per-algorithm dispatch or ownership state machine is introduced.

An independent exact-head Linux probe ran the actual metric.InnerProduct, moarray.InnerProduct and DistanceTransformIvfflat functions. Positive/negative/zero examples give internal -32/32/-0 and public/index 32/-32/0, with agreement in all three controls. Reviewed the layout/type/null/error unit matrix, index/full-scan ordering and score controls, tolerance-based large-f32 oracles and migrated two-CN lifecycle test. The strict pairwise metadata correction matches the actual scalar FLOAT metadata contract.

Evidence reused: current-head required CI, UT/SCA/coverage, proxy and pessimistic BVT are green; author package, real SQL and strict pairwise evidence retains its recorded revisions/modes. Diff whitespace check passed. I did not rerun full packages or a live SQL cluster locally. GPU adapter consumers were traced through the common output boundary, but native CUDA/CAGRA/IVF-PQ runtime parity was not independently executed; CPU execution with gpu_mode enabled is not treated as CUDA proof. The documented old/new SQL-semantic incompatibility and application sign/order migration remain rollout constraints, not an index rebuild requirement.

@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 at b2f41d7, merge-base b6fa8cc. No blocking finding established after reviewing all 47 changed files and the affected producer/consumer chains.

This is a bounded correction to the existing INNER_PRODUCT contract, not a new execution framework. The authoritative metric kernels and stored indexes keep negative-dot distance; scalar/float32 batch/narrow-vector SQL and shared index-output boundaries expose dot. IVF-generated SQL and scalar entry scans convert back to internal distance before candidate ranking; storage readers resolve the internal metric directly. HNSW/IVF/CAGRA/IVF-PQ use the common DESC admission rule for maximum IP, while ASC retains exact evaluation. Exact reranking keeps INCLUDE data/nulls aligned. Public-score ranges are filtered before Top-K, with incompatible storage-range pushdown disabled. Existing registry, persistence, ownership and cleanup mechanisms remain in use; no new duplicated dispatch/state/storage was found.

Reviewed NULL, dimension/non-finite failures, negative/zero scores, all six vector types and expression layouts, empty/multicn follow-up behavior, exact/index score and order controls, and the changed tolerance oracles. The tests use independent mathematical references rather than only comparing implementations to themselves. The migrated lifecycle case retains its cancellation/remote execution assertions. Long-vector fixture payloads are unchanged. Increment assessed separately: production +73/-56, tests/fixtures +660/-235, docs +35/-0. No outstanding earlier inline questions exist on this PR.

Verified current-head CI run 37895586354 and downloaded its UT/BVT evidence: required CI passed; INNER_PRODUCT semantics 18/18, vector_func 229/229, index-optype matrix 93/93 and multicn search 36/36 passed, all with zero ignored/abnormal cases. Author evidence for the strict pairwise metadata correction was reviewed with its stated revision/mode limits. I did not rerun those complete suites locally. GPU adapters were source-traced through native negative-dot output and the shared conversion; native CUDA execution was not independently validated, and CPU gpu_mode runs are not GPU parity evidence.

Performance/compatibility: scalar conversion adds only sign handling and no new allocation/state. IP range queries lose the storage Top-K fast path and evaluate/filter candidates before bounded Top-K; their CPU cost may increase and was not benchmarked here. Existing ASC maximum-similarity clients must migrate to DESC or they both change meaning and lose ANN acceleration. This is documented along with threshold/sign migration, rollback and avoiding mixed SQL semantics during rollout; no index rebuild is required.

@mergify mergify Bot added the queued label Oct 9, 2026
@mergify

mergify Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-09 08:45 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-09 08:48 UTC · at d524c86ff886ea6365a457c854e735f09e559539

This pull request spent 2 minutes 8 seconds in the queue, with no time running CI.

Reason

Pull request #29711 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 9081663 into matrixorigin:main Oct 9, 2026
@mergify mergify Bot added dequeued and removed queued labels Oct 9, 2026
@ck89119
ck89119 deleted the issue-29703-main branch October 9, 2026 08:50
XuPeng-SH added a commit that referenced this pull request Oct 9, 2026
…#29711) (#29790)

## What type of PR is this?

- [x] API-change
- [x] BUG
- [ ] Improvement
- [x] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #29703. This reverts the fix rather than resolving or closing
the issue.

## What this PR does / why we need it:

Revert #29711 at the user's request.

This reverts commit `908166384d32e378a72cc3b5ef9e7075603c4e81` in full.
All 47 reverted paths match the original commit's parent; subsequent
unrelated main changes are preserved.

- Restore historical `INNER_PRODUCT(a, b) = -Σaᵢbᵢ` semantics across
scalar, batch, narrow-vector, and index score boundaries.
- Restore ASC maximum-inner-product nearest-neighbor rewrites and the
corresponding IVF ordering, reranking, and range handling.
- Restore the previous UT/BVT fixtures and results, and remove the
reverted PR's mathematical-dot-product migration document and new
semantics cases.

### Compatibility

Applications migrated for #29711 must undo their score-sign, ordering,
and threshold changes when deploying this revert. Index storage formats
remain unchanged. Avoid mixing nodes with opposite SQL INNER_PRODUCT
semantics.

### Validation

On macOS arm64, using Go **1.27.1** from go.mod and freshly rebuilt
native prerequisites:

- Focused tests and full owning-package suites passed for moarray,
metric, brute_force, ivfflat, plan, and function.
- `TestIssue28378IVFFlatRemoteLifecycle` passed, including the embedded
two-CN IP query and remote lifecycle assertions.
- Changed executable-line coverage: **27/29 = 93.1%**.
- `make build`, matching gofmt, incremental go vet, repository-pinned
golangci-lint **2.14.0** (**0 issues**), and diff checks passed.
- Two local single-CN mo-tester value-comparison rounds (`-g -n`) passed
for 12 affected CPU BVT files: array, array_vecnarrow,
array_vecnarrow_ops, array_vecuint8, vector_finite_extreme, vector_func,
vector_index, vector_index_optype_matrix, vector_ivf_mode_advanced,
vector_ivf_multicn_search, vector_hnsw, and vector_hnsw_f64.
- HNSW files retain 21 historical #22794 ignored statements each; the
changed IP statements are outside those blocks. No skips or comparison
rules were added.

**Limits:** BVT comparisons did not validate column metadata. The pure
revert restores historical golden floating-point tails and metadata,
including pairwise headers; strict metadata parity is not claimed.
Actual CUDA/GPU execution, standalone/compose multi-CN BVT, and the full
issues package suite were not run. The embedded lifecycle UT is two-CN
evidence; the local BVT remains single-CN evidence.

Co-authored-by: XuPeng-SH <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — d524c86f Deployed Oct 9, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/api-change kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: INNER_PRODUCT returns negated dot product (sign wrong)

4 participants