Skip to content

[Bug]: HNSW rewrite returns inconsistent or non-finite distance expression values #29050

Closed

Description

@Ariznawlll

问题

HNSW rewrite 只把直接投影和排序中的 l2_distance 替换成索引返回的 score;同一个函数嵌套在 ROUND()、比较表达式或 WHERE 中时仍按标量函数计算。两个计算路径的精度不同,因此同一行、同一 SQL 表达式会在一条结果中同时得到互相矛盾的值。

这不是 ANN 召回差异:HNSW 与精确路径选择了相同的行,错误发生在返回值和表达式一致性上。

环境

  • MatrixOne main
  • commit: 01d60e1c4ded1b0f3fc1a4ecd75ce54e95e23b90
  • 本地 2 CN / 1 TN / 1 LogService
  • 同步 HNSW,vector_l2_ops

最小复现

set experimental_hnsw_index=1;

create table t(id bigint primary key,v vecf32(4));
insert into t values
  (29,'[2.189,-1.676,2.08,-1.578]'),
  (99,'[10,10,10,10]');

create index hx using hnsw on t(v)
  op_type 'vector_l2_ops'
  m=16 ef_construction=128 ef_search=128 max_index_capacity=75;
alter table t alter reindex hx hnsw force_sync;

select id,
       l2_distance(v,'[1.125,-0.625,0.375,1.75]') direct_d,
       round(l2_distance(v,'[1.125,-0.625,0.375,1.75]'),14) wrapped_d,
       l2_distance(v,'[1.125,-0.625,0.375,1.75]') = 4.02731990814209 eq,
       l2_distance(v,'[1.125,-0.625,0.375,1.75]') <= 4.02731990814209 le
from t
where l2_distance(v,'[1.125,-0.625,0.375,1.75]') <= 4.02731990814209
order by l2_distance(v,'[1.125,-0.625,0.375,1.75]')
limit 10;

实际结果

id  direct_d           wrapped_d        eq  le
29  4.027320069947357  4.02731990814209 1   1

direct_d 大于比较边界,但同一个 l2_distance 的 = 和 <= 同时为真。给查询加 BY RANK WITH OPTION 'mode=force' 后,直接投影也返回标量值 4.02731990814209。

预期结果

同一行中语义相同的函数调用必须得到同一个 SQL 值。向量索引可以近似选择候选行,但访问路径不应让直接投影、函数嵌套和谓词分别观察到不同的 l2_distance 值。

稳定性与控制

  • 3 个独立数据库和 HNSW 索引;
  • 两个 CN;
  • 每个索引、每个 CN 连续执行 3 次;
  • 18/18 次均返回上述矛盾结果;
  • mode=force 18/18 次返回一致的标量值;
  • HNSW 与精确路径的行集都只有 id=29,排除了召回率或 Top-K tie;
  • EXPLAIN 确认错误查询使用 hnsw_search,WHERE 在回表 scan 上按标量函数执行。

定位

pkg/sql/plan/apply_indices_hnsw.go 用 HNSW table function 的 score 列替换 Top-K 的排序表达式,并通过 vectorRemapForChildProject 重映射直接投影;原表上的 residual filter 保留标量 l2_distance。vecf32 标量实现返回 float32 舍入后的距离,而 HNSW score 路径返回另一精度的值,于是相同函数根据表达式位置产生不同结果。

这与 #29040 不同:#29040 是 IVFFLAT 推送距离范围后改变行成员关系;本问题是 HNSW 选中相同行后,直接投影与同查询内的标量表达式值不一致,修复路径也位于 HNSW rewrite/remap。

Activity

  1. Ariznawlll commented on Sep 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    补充指标与向量类型矩阵后,#29050 不是单一 VECF32 + l2_distance 舍入点。

    在相同两行数据、相同查询向量、两个 CN 上,对直接投影值和 ROUND(distance, 14) 内的标量值进行比较:

    类型 距离函数 直接 HNSW score 与标量值
    VECF32 l2_distance 不同
    VECF32 l2_distance_sq 当前数据相同
    VECF32 cosine_distance 不同
    VECF32 inner_product 当前数据相同
    VECF64 l2_distance 不同
    VECF64 l2_distance_sq 不同
    VECF64 cosine_distance 不同
    VECF64 inner_product 不同

    所有查询的 Top-K ID 和精确路径一致,两个 CN 结果一致;差异只取决于表达式是否被 planner 直接重映射到 hnsw_search.score。例如同一个 VECF64 L2 行:直接投影为 4.027320069947357,标量函数为 4.02731995252426;VECF64 L2SQ 为 16.21930694580078 对 16.219306000000003。

    因此建议修复时不要只统一 F32 L2 的最终 sqrt 舍入,而要保证直接投影、嵌套函数和 residual predicate 对所有 HNSW 指标观察到同一个 SQL 表达式值。

  2. Ariznawlll commented on Sep 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    继续验证后,本问题会改变结果集,不仅是直接投影末位小数不同。

    把 HNSW Top-K 作为派生表/CTE,并在外层使用其距离别名:

    select id,d
    from (
      select id,
             l2_distance(v,'[1.125,-0.625,0.375,1.75]') d
      from t
      order by l2_distance(v,'[1.125,-0.625,0.375,1.75]')
      limit 2
    ) k
    where d <= 4.02731990814209;

    HNSW 路径返回空集;给内层 LIMIT 加 BY RANK WITH OPTION 'mode=force' 后正确返回:

    29  4.02731990814209
    

    等值谓词 d = 4.02731990814209 也同样丢行;聚合消费者:

    select count(*) from (<same HNSW Top-K>) k
    where d <= 4.02731990814209;

    返回 0,精确路径返回 1。

    该扩展已加入相同的 3 个独立索引 × 2 CN × 每端 3 次矩阵:派生表、CTE、等值和聚合结果共 18/18 稳定错误。原因是外层消费者合法地使用内层公开的距离列,而该列已经被替换成精度不同的 HNSW score,不能再由回表 residual predicate 纠正。

  3. changed the title [-][Bug]: HNSW rewrite returns different values for the same l2_distance expression[/-] [+][Bug]: HNSW rewrite returns inconsistent or non-finite distance expression values[/+] on Sep 18, 2026
  4. Ariznawlll commented on Sep 18, 2026

    @Ariznawlll
    CollaboratorAuthor

    补充确认该问题不限于 vecf32 + l2_distance 的末位精度差异,而是覆盖多 metric,并且 vecf64 有限输入会被 HNSW score 路径变成 Inf。

    固定环境:main commit 01d60e1c4ded1b0f3fc1a4ecd75ce54e95e23b90,2 CN / 1 TN / 1 LogService。

    多 metric 值一致性

    对 HNSW 的 vecf32/vecf64 × L2/L2SQ/COSINE/INNER_PRODUCT 共 8 组索引,在两个 CN 上比较直接投影(HNSW remap score)与同函数加 +0 后的标量值:

    • 16 个类型/metric/CN 组合中有 12 个出现不一致;
    • vecf32 L2:100/100 行不一致;
    • vecf32 COSINE:67/100 行不一致;
    • 四种 vecf64 metric 均为 100/100 行不一致;
    • vecf32 L2SQ、vecf32 INNER_PRODUCT 是一致的控制组;
    • 两个 CN 结果相同。

    在 indexed/exact 选择相同 40 个 ID 的控制下,受影响组合的关系运算结果也不同:

    • L2 和四种 vecf64 metric:UNION=80、INTERSECT=0、indexed EXCEPT exact 为 40 行、按 (id,distance) 等值连接为 0 行;
    • vecf32 COSINE:40 行中 34 行 score 不同,UNION=74、INTERSECT=6、等值连接仅 6 行。

    vecf64 有限值变成 Inf

    使用 vecf64(2),数据向量为 [s,s],s ∈ {1,1e10,1e19,1e20,1e50,1e100,1e150}:

    select id, l2_distance(v,'[0,0]') d
    from t
    order by l2_distance(v,'[0,0]')
    limit 7;

    两个 CN 上均得到:

    • HNSW l2_distance:从 s=1e20 起为 +Inf;精确路径仍是有限的 1.4142135623730951e20 到 1.414213562373095e150;
    • HNSW l2_distance_sq:从 s=1e20 起为 +Inf;精确路径仍是有限的 2e40 到约 2e300;
    • HNSW inner_product:s=1e50/1e100/1e150 为 -Inf;精确路径分别为有限的 -2e50/-2e100/-2e150;
    • 相同数据的 IVFFLAT 三种函数全部与精确路径一致。

    pkg/vectorindex/hnsw/model.go::Search 从 usearch 接收 []float32 distance,之后 pkg/vectorindex/hnsw/search.go 将其转换为 float64 并作为 SQL score 返回。对 vecf64 而言,转换发生在精度丢失或溢出之后,无法恢复原始函数值。

    所以这里不仅是 ANN 召回差异:候选 ID 完全相同的情况下,访问路径改变了 SQL 函数值,有限输入还会产生非有限输出,并继续影响集合运算、等值连接、分组和过滤。

  5. Ariznawlll commented on Sep 18, 2026

    @Ariznawlll
    CollaboratorAuthor

    补充 #29050 的 vecf64 + vector_ip_ops 场景:HNSW score 溢出不仅改变投影值,也会改变 Top-K 的候选 ID。

    固定环境为 main commit 01d60e1c4ded1b0f3fc1a4ecd75ce54e95e23b90,本地 2 CN / 1 TN / 1 LogService。构造 30 行 vecf64(2):id % 3 = 0/1/2 分别写入 [3e200,0]、[1e200,0]、[2e200,0];HNSW 使用 vector_ip_ops、m=8、ef_construction=64、ef_search=64。查询向量为 [1,0],LIMIT 10。

    精确路径 BY RANK WITH OPTION 'mode=force' 稳定返回 3,6,9,12,15,18,21,24,27,30,距离均为有限的 -3e200。mode=post 的计划确认使用 hnsw_search,10 个返回 score 均为 -Inf,并混入 [1e200,0]、[2e200,0] 的行,例如一次返回 3,4,5,6,7,8,28,29,30,2。

    该矩阵使用 3 个独立数据库、2 个 CN、每端连续查询 3 次;18/18 组中候选集合都与精确 Top-K 不同,同时精确控制组始终正确。ef_search=64 大于表行数 30,因此这里不是 ANN 检索深度或 tie 的可接受差异:有限的 F64 内积分数在 HNSW []float32 距离路径中收窄为 -Inf,所有候选失去排序信息,继而改变结果成员。

    代码上,pkg/vectorindex/hnsw/model.go 的 HnswModel.Search 从 usearch 接收 []float32 distances;pkg/vectorindex/hnsw/search.go 随后将这些已经溢出的值转为 float64 并用于合并和返回 SQL score。这个现象属于本 issue 已记录的 HNSW score/rewrite 精度问题的结果集扩展。

    复现证据:evidence/hnsw_f64_ip_candidate_overflow_matrix.py,输出中 candidate_corruption_reproductions=18。

  6. cpegeric commented on Sep 18, 2026

    @cpegeric
    Contributor

    Confirmed and reproduced. This is working as intended, not a bug we'll fix.

    Root cause: When the HNSW index is used, the projected l2_distance is rewritten to the score column returned by usearch, and
    usearch computes distances in float32. The same function nested inside ROUND() / a comparison / the WHERE clause instead goes
    through MO's scalar l2_distance, which accumulates in float64. The two paths differ at ~1e-7 (float32 precision), so within one
    row the projected value and the <= bound can look contradictory.

    Why we won't fix it:

    1. Two different score-computation paths (usearch f32 vs MO f64) legitimately produce a round-off difference; forcing them to
      agree bit-for-bit is neither realistic nor a goal.
    2. The purpose of a vector index is a fair relative comparison / ranking between vectors — every candidate is scored the same
      f32 way, so the comparison is fair. It does not promise the exact absolute distance of any single vector. Row selection and
      ordering here match the exact path (both return only id=29), which shows the between-vector comparison is correct.

    Recommendation: don't request more precision than float32 carries (~7 significant digits). Use ROUND(l2_distance(...), 4)
    (anything up to ~6 decimals is safe) rather than ROUND(..., 14) — then the index (f32) and the scalar (f64) paths agree, e.g.
    both give 4.0273. ROUND(..., 14) only exposes sub-float32 noise.

    If you need the exact value: use ... BY RANK WITH OPTION 'mode=force' (or the full-scan path with no index); there the
    projection, nested calls, and predicates all consistently return MO's f64 scalar value (4.02731990814209 in this case).

    Closing as won't-fix.

  7. Ariznawlll commented on Sep 18, 2026

    @Ariznawlll
    CollaboratorAuthor

    Thanks for confirming the narrow vecf32 + l2_distance rounding case. I agree that a small float32-vs-float64 difference in the displayed distance alone is not necessarily a correctness bug, and that mode=force is the appropriate path when an exact scalar value is required.

    However, the issue now includes cases beyond display precision, and the "fair relative ranking" rationale does not cover them:

    1. For finite vecf64 inputs, the HNSW score path can narrow values to +Inf / -Inf. This is not a sub-float32 rounding difference.
    2. In the vecf64 + vector_ip_ops case, score overflow removes ordering information and changes the Top-K candidate IDs even with ef_search larger than the table cardinality. The indexed result is therefore no longer a fair ranking of the same candidates.
    3. When the rewritten distance is exposed by a derived table or CTE and filtered by an outer query, the float32 score can remove rows while the exact path retains them. This affects result-set correctness, not only the displayed value.

    Could you please review these three cases separately from the original vecf32 rounding example? The limited float32 display-precision contract can be documented, but finite-to-infinite conversion, changed Top-K membership, and derived-table predicate differences need an explicit product decision or a fix before this issue is closed.

    @cpegeric

  8. cpegeric commented on Sep 18, 2026

    @cpegeric
    Contributor

    Thanks — I investigated these three separately from the vecf32 rounding case, reproduced all of them, and traced the root cause
    into the usearch C sources.

    Root cause (verified in the C headers). usearch's distance type is hardwired 32-bit — usearch.h: typedef float
    usearch_distance_t;, and the metric pointer itself returns it (typedef usearch_distance_t (*usearch_metric_t)(...)). usearch
    does not blindly downcast the vectors — index_plugins.hpp special-cases std::is_same<scalar_at, f64_t>(), so f64 vectors are
    stored and accumulated in f64; the truncation is only at the result boundary, where the f64 distance is returned as float32.
    cuvs (GPU) is the same. So the distance channel is float32 for every base type. Confirmed empirically: finite vecf64 [1e30,0]…
    → HNSW returns +Infinity (order scrambled); ip Top-K collapses; and a derived-table … WHERE d < 4e30 over the index returns
    zero rows vs all rows exact.

    Decision. Because the index distance is physically float32 for all base types, we're standardizing the distance domain on
    float32 across both the scalar functions and the index, rather than letting the scalar (f64) and index (f32) disagree:

    1. Uniform float32 distance domain — l2_distance / l2_distance_sq / inner_product / cosine_distance compute in the float32
      domain for every vector base type (they already do for vecf32 and the narrow types). This makes the scalar path and the index
      path always agree, so the three cases above stop being divergences: both paths observe the same value, ordering, and predicate
      result. mode=force and the index become identical.
    2. Reject overflow fail-fast — a vector whose distance would exceed the float32 range is rejected at build/query time instead
      of silently producing ±Inf, closing the silent derived-table row-loss (case 3) and the ordering collapse (cases 1–2).
    3. Document the contract — vector-distance functions are a float32 domain; f64 vector columns retain f64 storage/precision, but
      their computed distances are float32 (an inherent usearch/cuvs limitation).

    We considered MO-side exact-f64 re-ranking to preserve f64 through the index, but deferred it: the index can't carry f64
    distance regardless, the overflow region is far outside normalized embeddings, and a uniform float32 contract is simpler and
    removes the divergence entirely rather than patching one path. It can be revisited if a concrete f64-exact ranking need
    appears.

    @Ariznawlll

  9. Ariznawlll commented on Sep 20, 2026

    @Ariznawlll
    CollaboratorAuthor

    在最新 main 上复测 #29050,commit 为 d8ddce92b1c5c172111b50aefe6b6b200b2589cb;本地 2 CN / 1 TN / 1 LogService。

    本次将 HNSW 的三种 score 路径和所有运行模式放入同一矩阵:

    • vector_l2_ops + l2_distance、vector_l2_ops + l2_distance_sq:向量值为 [1e30,0]、[2e30,0]、[3e30,0];该范围使 HNSW 的 float32 score 溢出,但标量 F64 结果仍有限。
    • vector_ip_ops + inner_product:向量值为 [1e200,0]、[2e200,0]、[3e200,0],查询向量 [1,0]。
    • 每组为 30 行、LIMIT 10,HNSW 参数 m=8, ef_construction=64, ef_search=64;每 metric 使用 3 个独立数据库,两个 CN 各执行 auto、pre、post 三种模式。

    mode=force 在 18 个 metric/数据库/CN 控制组中均返回有限距离及精确 Top-K(L2/L2SQ 为 id=1,4,...,28;内积为 id=3,6,...,30)。三个 HNSW 模式的 EXPLAIN 均使用 hnsw_search;54/54 组均把返回 score 收窄为 +Inf 或 -Inf,并返回不同的 Top-K 成员,混入本不属于精确前十的向量。

    这里 ef_search=64 大于表的 30 行,因此不是 ANN 检索深度不足或 Top-K tie:有限的 F64 输入在 score 的 float32 路径失去数值次序,随后直接改变了结果成员。此前本单记录的投影/谓词表达式不一致,在最新 main 上仍进一步表现为三种常用运行模式中的结果集错误。

    复现脚本与输出:evidence/hnsw_f64_score_overflow_modes_matrix.py,candidate_corruption_reproductions=54。

  10. added this to the MO-202609 milestone on Sep 23, 2026
  11. added theissue type on Sep 23, 2026
  12. Ariznawlll commented on Sep 24, 2026

    @Ariznawlll
    CollaboratorAuthor

    测试版本

    • 分支:main
    • commit:d7d940e93bd037e9aacdc0f1256b91e32df84642
    • 部署方式:本地分布式,1 LogService / 1 TN / 1 CN;全新数据目录
    • 测试日期:2026-09-24

    原问题验证

    按 issue 原始 VECF32(4) + vector_l2_ops HNSW 复现建表、同步重建索引并重复 3 次。EXPLAIN 确认使用 hnsw_search。

    当前同一行的直接投影、ROUND(...,14) 包装表达式以及 =、<= 谓词均观察到同一个值:

    id=29, direct_d=4.02731990814209, wrapped_d=4.02731990814209, eq=1, le=1
    

    派生表外层使用距离别名过滤时也正确保留 id=29,不再出现索引投影与标量谓词互相矛盾或外层过滤丢行。

    Happy Path 覆盖

    1. 原始 HNSW L2 查询、直接投影、包装表达式和 residual predicate 结果一致,连续 3/3 通过。
    2. 派生表消费距离别名的场景连续 3/3 返回相同行和值。

    Unhappy Path 覆盖

    1. 按研发确认的 fail-fast 方案,使用 VECF64(2) 的 1e30/2e30/3e30 触发 HNSW score 超出索引计算域;mode=post 返回明确的 vector index search: vector magnitude is too large 错误,不再产生 +Inf 或错误 Top-K。
    2. 拒绝后源表仍保持 3 行,索引查询失败未改写源数据。
    3. 补充 F64 L2/IP 矩阵中,auto/pre/post 均稳定受控拒绝;未观察到 panic、hang 或非有限 score 泄漏。

    白盒验证

    不适用。原始表达式一致性和溢出 fail-fast 均可通过公开 SQL 与查询计划验证。

    回归测试

    已加入 matrixorigin/motr#204:

    • suites/14_issue_regression/t/issue_29050_hnsw_score_consistency.test
    • suites/14_issue_regression/r/issue_29050_hnsw_score_consistency.result

    新增用例本地重复 3 次全部通过。完整 14_issue_regression 套件中本用例通过;套件的其他既有协议/基线失败与本用例无关。

    测试证据

    • 回归 PR:matrixorigin/motr#204
    • 回归提交:99089c8b
    • 本地测试汇总:目标三项合计重复 9/9 通过,177/177 statements 成功。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

area/optimizerkind/bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions