Repository navigation
fix: vector_l1_ops and vector_l2sq_ops indexes were unusable and hnsw inner product score transform - #27044
Conversation
…atrixorigin#25966) IVF-FLAT accepted two op_types no query could ever use. vector_l1_ops built an index, but l1_distance did not exist as a SQL function. That broke more than the optimizer rewrite: IVF-FLAT generates its own entries/re-rank SQL from MetricTypeToDistFuncName, so an L1 index emitted l1_distance(entry, '[...]') and failed at execution. The metric layer already had L1 everywhere -- f32/f64 kernels, native bf16/f16/int8/ uint8 kernels, cuvs.L1 -- only the SQL builtin was missing. Add it (L1_DISTANCE = 569) with overloads for all six vector element types over those existing kernels, so the SQL value and the value the index ranks by come from the same code. The wrapper goes through moarray like its L2 siblings, so a dimension mismatch reports the invalid-input error naming both dimensions rather than the kernel's internal error. vector_l2sq_ops built an index the planner never selected: each distance function matched ONE canonical op_type by string equality, and the canonical op_type for both L2 forms is vector_l2_ops. Replace the equality test at all four algorithm sites with OpTypeServesDistFunc, backed by DistFuncOpTypeSet: vector_l2_ops, vector_l2sq_ops -> l2_distance, l2_distance_sq vector_l1_ops -> l1_distance vector_ip_ops -> inner_product vector_cosine_ops -> cosine_distance The L2 pair is interchangeable because both op_types build the same index (each maps to Metric_L2sqDistance) and whether the score is sqrt-ed is decided at search time from the query's function name, never from the index -- so either serves either form with a correctly scaled score. Tests: unit coverage for the serving sets (plus a drift guard against the default-op_type table), l1_distance values in both float widths, the narrow-type parity sweep, the batched const-query path, and the moarray dimension check. Two BVT cases: l1/l2sq end to end, and a matrix walking every op_type on IVF-FLAT and HNSW that asserts the served function reaches the index, a non-served one does not, and the returned score equals the brute-force distance. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An HNSW vector_ip_ops index reported every distance exactly 1 too high. usearch's inner-product metric is 1 - a.b, while MO's inner_product SQL function is -a.b (negated so that smaller means closer), and DistanceTransformHnsw only handled the squared-L2 -> L2 sqrt. Measured on a 4-row table, the index returned -199/-19/-11/-3 where brute force returned -200/-20/-12/-4. The offset is monotonic, so ordering stayed correct and every existing test -- all of which assert row order, never the value -- passed straight through it. usearch is the only backend that needs this: the Go CPU kernels already return -a.b, and cuVS output is negated inside cgo/cuvs before it reaches Go. Within usearch, IP is the only metric whose zero point differs -- Cosine is already 1 - cos_sim, which is exactly what cosine_distance returns, and L2sq is the same squared distance MO computes. The usearch brute force needed the same rebase, and could not take it from rt.OrigFuncName: that field is populated by the index search paths but not guaranteed for a directly constructed brute-force index, and its empty value looks up as Metric_L2Distance. The metric is already known at construction, so keep it -- MetricTypeToUsearchMetric is lossy, mapping both Metric_L2Distance and Metric_L2sqDistance onto usearch.L2sq, so without MoMetric the search cannot tell whether to take the root. Predates this branch; found while verifying index scores against brute force for matrixorigin#25966. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
… builds gpu_pairwise_distance_wait already flips the sign of the inner-product buffer inside cgo/cuvs (distance_c.cpp, matching the synchronous contract in distance.hpp), and PairwiseDistanceWait then negated the same buffer again, so a gpu-tagged build returned +a.b where MO's inner_product is -a.b. Only batches clearing GPUThresholdSQL take the GPU path, so a single query could report both signs for the same vectors: over a 20000-row x 128-dim table, `select distinct inner_product(v, '[1,...,1]')` returned BOTH 128 and -128, while the 10-row control on the CPU kernel returned -128. The squared-L2 root stays -- cgo does not apply that one -- and the CPU branch returns before this code, its kernels already producing MO's convention. Adds a gpu-tagged test that forces the GPU path with GPUThresholdOverlapped and asserts, for inner product, L2sq, L2 and cosine, both the expected value and agreement with the CPU launch/wait on the same inputs -- the invariant this bug violated. It fails on the old code with "Max difference between -14 and 14 ... difference was -28". Predates this branch; found while verifying index scores against brute force for matrixorigin#25966, and reproduced on an RTX 5070 build. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The case passed 110/110 on a CPU build and failed on a GPU one, because
two assertions were on outcomes that are not determined by the query.
Test E.3 ordered t_edge by distance from '[0,0,0]' while the table held
the three unit basis vectors -- all exactly 1 away -- so `limit 2` over a
three-way tie had no defined answer. CPU returned 2,1 and GPU 1,3, both
correct. Give the rows distinct distances (1, 2, 3) so the assertion is on
the search rather than on which two rows the probe happened to visit.
Test 5.4 asserted an exact row set from a deliberately partial scan:
probe_limit=1 over lists=5 scans one centroid list, and whether that list
holds 4 or 5 of the 20 near-collinear points depends on how k-means split
them. The recorded 4 rows also contradicted the case's own comment
("Should return at least 'limit' rows if available") with 20 matching rows
present. Probe every list for that one query and restore probe_limit=1
straight after, so 5.5 onwards keep the low-recall fallback they were
written for.
Measured before changing anything: the query is stable within an index
build (6/6) and across 8 independent index builds (8/8, all returning the
true nearest 5), and identical under prepared statements -- so the row
count is contingent on the single-list probe, not on the query path or a
k-means seed.
Verified on both builds, 2 full cases/vector runs each: GPU 1614 total /
0 failed, CPU 1614 total / 0 failed.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…expectations
Two review items.
1. mo-cgo-test dropped the GPU build tag whenever the caller passed any -tags of
their own. The old reasoning was sound as far as it went -- go test keeps only
the LAST -tags, so appending a second one would discard the caller's -- but
skipping it produced a false green:
MO_CL_CUDA=1 mo-cgo-test -tags typecheck ./pkg/vectorindex/metric/
ran with `-tags typecheck`, so every //go:build gpu file was excluded from a run
whose entire purpose was GPU validation, and it passed. Measured with go list on
that package: 0 gpu test files compiled before, 2 after.
The tag is now MERGED into the caller's set in whichever form they wrote it --
`-tags v`, `-tags=v`, `--tags=v` -- and is not duplicated when already present,
treating both comma and space as separators. The rest of the argv keeps its order.
mo-cgo-test-tags-test covers all of it with a stubbed go, so it needs no GPU,
no CUDA toolkit and no built libmo. The MO_CL_CUDA-unset case self-skips when
the checked-out libmo is CUDA-built, since the wrapper then refuses that run by
design and it is a different behaviour under test.
2. vector_hnsw_f64.result carried two stale distances. They are exactly
float32(exact): 364.6423034667969 vs the true 364.6422904710862, and
127.42056274414062 vs 127.4205634895718 -- the old behaviour where an f64
column's distance was computed in float32 and widened. This branch keeps
float64 on the scalar path precisely to stop that, so the expectations, not the
code, were wrong. Verified against exact arithmetic before touching them.
ROUND(score, 4) was considered and rejected: both the old and new values round
to 364.6423, so it would blind the case to an f32/f64 regression -- exactly the
bug just fixed. The values are also machine-independent here despite
L2DistanceSqFloat64 branching on hasAVX512 with FMA, because every element is a
small integer, so only the final sqrt rounds and IEEE sqrt is correctly rounded;
scalar-unrolled and pairwise summation agree bit for bit.
Edited in place rather than regenerated: mo-tester rewrites the whole file in a
different separator format, which would have buried two changed numbers in a
374-line diff.
pessimistic_transaction/vector 570/639, 0 failed (the other 50 failures in the
first run were mine -- the suite was started before ISCP came up).
Co-Authored-By: Claude Opus 5 <[email protected]>
Two conflicts, both in the vector_ivf_retry case, and both because the same two fixes this branch makes reached main independently (ff9b919, matrixorigin#27057). Resolved by taking main's copy of both files wholesale. The SQL is identical on either side -- same `set probe_limit = 5;` around test 5.4, same distinct-distance t_edge fixture -- so the .sql conflict was purely the explanatory comment wording, and main's is the published text. The .result conflict looked larger but is the same fix in main's newer metadata result format (`➤ id[4,32,0] 𝄀` rather than plain column names); the expected rows are identical, test 5.4 still asserts the same five rows and 5.5 the same 999|1. Keeping this branch's copy would have reverted that format regeneration for one file while the other 26 in the suite kept it. Both files are now byte-identical to main, so they drop out of this branch's diff. Both fixes remain present in the merged tree. Verified: for all seven auto-merged Go files -- the four apply_indices_* files plus func_binary.go, func_binary_test.go and list_builtIn.go -- the merged-vs-main diff equals this branch's own pre-merge diff, so neither side lost anything. go build and go vet clean; pkg/sql/plan, pkg/vectorindex (incl. -tags gpu), pkg/vectorize/moarray and pkg/sql/plan/function all pass under MO_CL_CUDA=1. Co-Authored-By: Claude Opus 5 <[email protected]>
|
fixed merge conflict. |
aptend
left a comment
There was a problem hiding this comment.
Deep re-review completed on exact head 8ce48b099a67bea233e45653d29a4c63d42e8cab. The prior blockers are resolved: the column×constant distance path preserves float64/scalar semantics, selection masks, and dimension errors, and the CGo wrapper now merges the gpu tag with all supported caller tag forms. I also checked the final op-type serving matrix, HNSW/brute-force inner-product rebasing, GPU pairwise sign and ragged-row handling, and L1 overload/index integration. Focused metric, brute-force, moarray, function, and planner tests plus the wrapper tag regression pass.
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed exact head 8ce48b0. The prior semantic blockers are closed: column-by-constant evaluation preserves float64 precision, FunctionSelectList masking, null handling, and canonical dimension errors; usearch and cuVS score transforms now match the SQL distance contract; and the GPU wrapper retains the gpu tag across caller tag forms. I also applied the index-plugin review gate over merge-base 414fb8e: no new per-algorithm SQL/catalog dispatch, plugin-to-SQL import, indexplugin pollution, removed interface assertion, or untracked index change was found. Exact-head CI is complete and green.
XuPeng-SH
left a comment
There was a problem hiding this comment.
[P2] Make the new wrapper regression test independent of a prebuilt Linux libmo as documented
I ran sh .agents/skills/mo-dev/scripts/mo-cgo-test-tags-test from an isolated worktree at 8ce48b099a67 on macOS with no Linux artifact. All seven GPU-tag cases fail with <no -tags at all>. The test stubs go env GOOS to linux, so the wrapper requires $repo_root/cgo/libmo.so before it reaches the stubbed go test; the test creates only $work/{include,lib} and suppresses the wrapper stderr. This contradicts the documented contract that it runs without a built libmo and makes the regression test environment-dependent: it only passes when a Linux libmo happens to be present.
Please make the prerequisite probe injectable/stubbed or create a safe fake prerequisite in the isolated test setup, and assert the wrapper exits successfully before parsing its argv. That will also keep prerequisite failures from being misreported merely as missing -tags.
…as advertised The test claimed it needed no built libmo and did not. Stubbing `go` is not enough: mo-cgo-test resolves its repository from its own location and rejects the run unless cgo/libmo.so and thirdparties/install/include exist there, before it would invoke the stub. Pointed at the real checkout, the test therefore passed only on a machine that happened to have built libmo, and in a clean worktree failed all seven cases with "<no -tags at all>" -- reporting a wrapper that never ran as a wrapper that dropped the gpu tag. Reproduced at this branch's head in a detached worktree before changing anything. The test now builds a throwaway git repository, copies the REAL wrapper into it, and creates empty stand-ins for the two prerequisites, so only the surroundings are fake and the file under test stays the shipped one. Every invocation is checked for a zero exit before its stdout is parsed, so a setup fault reports as "harness broken" rather than as seven tag failures -- the misdiagnosis that hid this. The MO_CL_CUDA-unset case used to skip itself on a CUDA-built checkout; the fake libmo is not a CUDA binary, so it now asserts here too. mo-cgo-test itself is unchanged and byte-identical to the copy on decision_log, where the same fix landed as 443347b: the tag-merging implementation was never the problem, only the harness that was supposed to protect it. Verified: passes in this tree and in a clean detached worktree at 8ce48b0 with neither prerequisite present. Non-vacuous -- restoring the old skip-when-caller-set-tags behaviour in a sabotaged copy produces 5 failures and exit 1. Co-Authored-By: Claude Opus 5 <[email protected]>
|
fixed |
…-independent CI failed on vector_index_optype_matrix.sql at the HNSW cosine query: [EXPECT] 1 | 0.0 [ACTUAL] 1 | 5.9604644775390625E-8 That value is exactly 2^-24. Row a=1 IS the query vector [1,0,0,0], so its cosine distance is the degenerate zero, and 1 - cos comes back as 0.0 or as 2^-24 depending on whether the host's SIMD kernel accumulates the dot product to 1.0 or to 0.99999994. The recorded .result was generated on a machine that produced an exact zero; CI's CPU takes the other path. The comparator treats 0-vs-nonzero as a hard mismatch, so the case fails on whichever machine did not generate the file. Regenerating the .result to 5.96e-8 would only move the failure onto the machines that pass today, so instead the projection is rounded, which is how this repo already solves it -- vector_ivf_mode.sql:296 documents the identical case, and line 174 of this same file already rounds for the same reason. round() wraps the projection ONLY; each ORDER BY stays on the raw distance so the index is still used. All four exposed queries are rounded, not just the one that failed. The ivfflat query at 146 differs from the failing HNSW one only in which SIMD path it happens to hit, so fixing one and leaving three coin-flips would defer the next red build rather than prevent it. The two INDEXED projections change type metadata from d[8,9,0] to d[8,53,31]: with the index applied the projection is the score column, and wrapping it in round() yields round()'s own result type. The two brute-force rows already carried [8,53,31] and are unchanged. The other seven d[8,9,0] headers in the file belong to queries that are not rounded and are untouched. Verified by running the case against a freshly built mo-service on a clean instance, without -n so result metadata is compared as CI compares it: 85/85, 0 failed. That run confirms the format; what makes the case host-independent is arithmetic -- round(5.96e-8,4) and round(0.0,4) are both 0.0, so the two SIMD paths now converge on the same recorded value. Co-Authored-By: Claude Opus 5 <[email protected]>
|
fixed bvt failed test. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of exact head d26d7a64bb39ab7bb92750e478197bdf45cea20f against merge-base 414fb8e0f854a4ab31519394542f93535e2c492f.
The prior blocker is closed: mo-cgo-test-tags-test now runs the shipped wrapper inside a throwaway git repository, creates only safe prerequisite stand-ins, asserts the wrapper exits successfully before inspecting argv, and passes from an isolated worktree with no built libmo. All tag spellings and the non-GPU control pass; both shell scripts also pass sh -n.
I rechecked the full vector change and the latest host-independent cosine fixture update. The index-plugin gate found no new per-algorithm SQL/catalog dispatch, plugin-to-SQL import, registry pollution, or removed interface assertion. The latest rounding affects only the projected display value; raw cosine distance still drives ORDER BY and index selection. Full CPU tests pass for metric, brute-force, moarray, plan/function, and plan; the new metric/precision/selection/dimension tests also pass under -race. No blocking findings.
One conflict, in .claude/skills/mo-dev/SKILL.md: this branch still had the old one-line "prefer the deterministic wrapper" sentence while main had evolved it into the "controlled wrapper" paragraph naming the caller-owned inputs. Took main's. The auto-merge of the .agents twin needed correcting by hand. Both trees on main say "For local CPU CGo tests"; the merge silently kept this branch's older "For local CGo tests" in .agents, dropping main's CPU qualifier because only the .claude copy conflicted loudly enough to stop it. Restored main's wording there too. Checking for more of the same turned up a second divergence the merge left behind: the two trees ended up with different wordings of the MO_CL_CUDA paragraph, .agents keeping this branch's fuller version (which explains that the wrapper reports a CUDA-built libmo rather than letting the linker emit a page of "undefined reference to cuInit", and carries a runnable example) and .claude a condensed variant without the example. Synced .claude to the .agents text. Both wrapper scripts now match main byte for byte -- the tags-test fix from this branch reached main independently, so the merge converged rather than needing a resolution. Verified after resolving: no conflict markers; the four SKILL.md bodies are identical across .agents and .claude outside the intended Claude metadata blocks; all non-SKILL files identical; every relative markdown link resolves; mo-cgo-test-tags-test passes; go build ./pkg/... clean; pkg/sql/plan/... green, and pkg/vectorindex/metric plus pkg/vectorize/moarray green through the wrapper (bare go test cannot link them -- cannot find -lusearch_c). Co-Authored-By: Claude Opus 5 <[email protected]>
LeftHandCold
left a comment
There was a problem hiding this comment.
Reviewed exact head 4225192189583190801fdd930a0f8388a9328137 against main@ccb37f591b07e9901da2e0e7b5cb1733485e8771 (same merge-base). No blocking findings. The prior scalar-contract blockers are closed: the column×constant path preserves float64 precision, honors FunctionSelectList, and returns canonical dimension errors. I also verified the centralized op-type serving matrix across IVF-FLAT/HNSW/CAGRA/IVF-PQ, L1 builtin registration and overloads, usearch inner-product rebasing, and the cuVS pairwise sign/ragged-row boundary. The index-plugin guard is clean, and Q1-Q3 found no new leak, hung wait chain, or unbounded accumulation. Exact-head local validation passed: controlled CPU CGo build; build/vet; focused and full tests for metric, brute_force, moarray, plan/function, and plan; plus dependent ivfflat/... and hnsw/... suites. Exact-head CI is green. GPU hardware was unavailable locally, so GPU-tag behavior was verified from the Go/C++ boundary and its dedicated tests.
Merge Queue Status
This pull request spent 1 hour 59 minutes 44 seconds in the queue, including 51 minutes 41 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #25965 #25966
What this PR does / why we need it:
Two commits. The first is #25966; the second is a pre-existing defect found while
verifying the first, kept separate so it can be reviewed or reverted on its own.
1.
vector_l1_opsandvector_l2sq_opsindexes were unusable (#25966)IVF-FLAT accepted two op_types no query could ever use.
vector_l1_opsbuilt an index, butl1_distancedid not exist as a SQL function.That broke more than the optimizer rewrite: IVF-FLAT generates its own entries/re-rank
SQL from
MetricTypeToDistFuncName(pkg/vectorindex/ivfflat/search.go), so an L1 indexemitted
l1_distance(entry, '[…]')and failed at execution. The metric layer already hadL1 everywhere — f32/f64 kernels, native bf16/f16/int8/uint8 kernels,
cuvs.L1— only theSQL builtin was missing.
Added
L1_DISTANCE = 569with overloads for all six vector element types, computed bythose same kernels, so the SQL value and the value the index ranks by cannot drift. The
f32/f64 wrapper goes through
moarraylike its L2 siblings, so a dimension mismatchreports the invalid-input error naming both dimensions instead of the kernel's internal
error (whose text also differs between the SIMD and scalar builds).
This is IVF-FLAT-only: HNSW/CAGRA/IVF-PQ validate against
OpTypeToUsearchMetric, whichhas no L1 entry, so they already rejected it at DDL.
vector_l2sq_opsbuilt an index the planner never selected: each distance functionmatched ONE canonical op_type by string equality, and the canonical op_type for both L2
forms is
vector_l2_ops. The equality test at all four algorithm sites is replaced withOpTypeServesDistFunc, backed byDistFuncOpTypeSet:vector_l2_opsl2_distance,l2_distance_sqvector_l2sq_opsl2_distance,l2_distance_sqvector_l1_opsl1_distancevector_ip_opsinner_productvector_cosine_opscosine_distanceThe L2 pair is interchangeable because both op_types build the same index (each maps to
Metric_L2sqDistance) and whether the score is sqrt-ed is decided at search time from thequery's function name, never from the index — so either serves either form with a
correctly scaled score.
2. usearch inner-product distances were 1 too high
An HNSW
vector_ip_opsindex reported every distance exactly 1 above brute force(
-199/-19/-11/-3vs-200/-20/-12/-4on a 4-row table). usearch's IP metric is1 - a·bwhile MO'sinner_productis-a·b, andDistanceTransformHnswonly handledthe squared-L2 → L2 sqrt. The offset is monotonic, so ordering stayed correct and every
existing test — all of which assert row order, never the value — passed straight through
it.
usearch is the only backend affected: the Go CPU kernels already return
-a·b, and cuVSoutput is negated inside
cgo/cuvsbefore reaching Go. Within usearch, IP is the onlymetric whose zero point differs —
Cosineis already1 - cos_sim, andL2sqis thesame squared distance MO computes.
The usearch brute force needed the same rebase and could not take it from
rt.OrigFuncName: that field is populated by the index search paths but not guaranteedfor a directly constructed brute-force index, and its empty value looks up as
Metric_L2Distance. The metric is already known at construction, so it is now kept —MetricTypeToUsearchMetricis lossy, mapping bothMetric_L2DistanceandMetric_L2sqDistanceontousearch.L2sq, so withoutMoMetricthe search cannot tellwhether to take the root.
Tests
Unit — serving-set resolution plus a drift guard against the default-op_type table;
l1_distancevalues in both float widths, negatives and zero; the narrow-type paritysweep (bf16/f16/int8/uint8 agree with vecf32); the batched const-query path that every
real
ORDER BY l1_distance(v,'[…]')takes; themoarraydimension check assertingbyte-identical error text to
l2_distance;function_idregistration; and the usearchrebase (
-199 → -200,Metric_L2Distance → 5,Metric_L2sqDistance → 25, all with anempty
RuntimeConfigto show it no longer depends on one).BVT — two new cases under
test/distributed/cases/vector/:vector_ivf_l1_l2sq—l1_distanceover every vector element type, then L1 and L2sqIVF-FLAT indexes end to end.
vector_index_optype_matrix— every op_type on IVF-FLAT and HNSW, asserting the servedfunction reaches the index (
ivf_search/hnsw_searchin the plan), a non-served onedoes not, and the returned score equals the brute-force distance against an
unindexed twin table. That last check is what catches a wrong metric or a mis-scaled
score; an ordering-only assertion would not have caught the inner-product bug.
Results (clean data dir, single CN, binary rebuilt from this source):
cases/vectorcases/functioncases/ddlcases/optimizer27,409 statements, 0 failures, 0 abnormals. Package tests green for
pkg/vectorindex/{metric,brute_force,ivfflat,hnsw},pkg/vectorize/moarray,pkg/sql/plan,pkg/sql/plan/function,pkg/sql/colexec/productl2. Both commits wereverified independently, not only as a combined tree.