Skip to content

[Bug]: IVFFLAT cache keeps the first L2 function and misfilters later l2/l2sq ranges #29038

Closed

Description

@Ariznawlll

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Branch Name

main

Commit ID

01d60e1

Other Environment Information

  • Local multi-CN launch (etc/launch-multi-cn/launch.toml), SQL ports 16001 and 16002
  • Synchronous IVFFLAT, lists=1, vector_l2_ops
  • 120 rows in three exact distance shells; no approximate-list recall variable

Actual Behavior

An IVFFLAT L2 index remembers whichever equivalent SQL distance function uses the cached index first. A later query using the other function evaluates pushed distance ranges in the first function's unit and can return an empty result.

Both directions reproduce:

  1. l2_distance runs first and correctly returns ten rows at distance 200; the next l2_distance_sq query for 22500 < distance_sq < 62500 returns zero rows instead of the same ten rows at squared distance 40000.
  2. l2_distance_sq runs first and correctly returns ten rows at squared distance 40000; the next l2_distance query for 150 < distance < 250 returns zero rows instead of the same ten rows at distance 200.

The alternate-function query returns zero in mode=post, mode=include, and mode=pre. mode=force returns the expected ten rows, so the source data and SQL predicates are valid.

This was repeated with a previously unused table/index cache key for every attempt: two CN endpoints × both first-function directions × three independent indexes × three IVF modes = 36/36 incorrect alternate-function results. Every first-function execution and every exact control was correct.

Expected Behavior

l2_distance and l2_distance_sq are both supported by vector_l2_ops and vector_l2sq_ops. Each query must use its own function's unit when applying DistRange, regardless of which function first loaded or explained the cached IVFFLAT index.

Steps to Reproduce

set experimental_ivf_index = 1;
drop database if exists ivf_l2_func_cache_repro;
create database ivf_l2_func_cache_repro;
use ivf_l2_func_cache_repro;

create table t(id int primary key, grp int, v vecf32(2));
insert into t
select result,
       floor((result - 1) / 40),
       cast(concat('[', floor((result - 1) / 40) * 200, ',0]') as vecf32(2))
from generate_series(1, 120) g;

create index idx using ivfflat on t(v)
lists = 1 op_type 'vector_l2_ops';

-- First use of this index: correct, ten rows at distance 200.
select id, grp, l2_distance(v, '[0,0]') d
from t
where l2_distance(v, '[0,0]') > 150
  and l2_distance(v, '[0,0]') < 250
order by l2_distance(v, '[0,0]')
limit 10 by rank with option 'mode=post';

-- Same vectors and equivalent squared interval: incorrectly returns zero.
select id, grp, l2_distance_sq(v, '[0,0]') d
from t
where l2_distance_sq(v, '[0,0]') > 22500
  and l2_distance_sq(v, '[0,0]') < 62500
order by l2_distance_sq(v, '[0,0]')
limit 10 by rank with option 'mode=post';

-- Exact control: correctly returns ten rows at squared distance 40000.
select id, grp, l2_distance_sq(v, '[0,0]') d
from t
where l2_distance_sq(v, '[0,0]') > 22500
  and l2_distance_sq(v, '[0,0]') < 62500
order by l2_distance_sq(v, '[0,0]')
limit 10 by rank with option 'mode=force';

To reproduce the reverse direction, recreate the table/index with a new name and execute the squared-distance query first.

Additional information

The plan reader constructs a per-query IndexTableConfig with OrigFuncName = r.spec.DistanceFunction, but the IVFFLAT cache key is the centroid hidden table plus index version. The cached search object retains the first Tblcfg. In the relation-search path, range filtering calls filterEntryDistanceRange(..., tblcfg.OrigFuncName, ...), while returned scores use the current request's RuntimeConfig.OrigFuncName. This split explains why ordinary scores remain correctly labeled but the pushed range is evaluated using stale L2 versus squared-L2 conversion.

This is the corrected independent defect found while expanding #28943. The earlier #29037 was closed after fresh-name controls disproved its original static-range diagnosis.

Activity

  1. added this to the MO-202609 milestone on Sep 17, 2026
  2. added
    kind/bug
    on Sep 17, 2026
  3. added theissue type on Sep 17, 2026
  4. Ariznawlll commented on Sep 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    Additional scope confirmed on the same commit:

    • The state is server-side, not connection-local. Priming an index with l2_distance on one connection and opening a new connection for l2_distance_sq still returns zero. Priming through SQL port 16001 and querying the alternate function through port 16002 has the same result.
    • Server SQL PREPARE/EXECUTE reproduces it. p_l2(150,250) returns ten rows at distance 200; a separately prepared p_sq(22500,62500) then returns zero on two consecutive executions. The exact squared-distance control returns ten rows at 40000.
    • The defect is not tied to the canonical op-type name: vector_l2sq_ops shows the same first-function behavior.
    • Quantized IVFFLAT indexes also reproduce. With fresh indexes for each type, float16, bf16, int8, and uint8 all return ten rows for the first L2 query, zero for the following squared-L2 range, and ten for the exact squared-L2 control, on both CN endpoints.
    • HNSW does not show the analogous score-cache problem in the no-range control: alternating l2_distance and l2_distance_sq returns 100 and 10000 respectively on repeated switches. Its lower-bound Top-K filtering is already covered by [Feature Request]: support filtered vector search for HNSW, IVFPQ, and CAGRA #28988 and is a separate issue.

    The expanded IVFFLAT result remains deterministic; no new issue is needed for these variants because they share the cached IndexTableConfig.OrigFuncName mechanism described here.

  5. Ariznawlll commented on Sep 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    Two more lifecycle/concurrency boundaries confirm the cache-key diagnosis:

    1. ALTER TABLE ... ALTER REINDEX changes the index version and therefore starts a fresh cache generation, but does not remove the design flaw. Before reindex, first l2_distance returns ten and later l2_distance_sq returns zero. After reindex, running squared-L2 first returns ten, and the following L2 query returns zero. The failing direction simply flips with the first execution on the new version.
    2. Concurrent first use is nondeterministic. Ten independent fresh indexes were each queried simultaneously from separate connections, one with L2 and one with squared-L2. Every attempt produced exactly one correct ten-row result and one empty result. L2 won 2/10 races and squared-L2 won 8/10; there was no attempt where both equivalent queries were correct.

    This makes the impact workload-order dependent: after startup or reindex, whichever function wins cache initialization determines which equivalent range form is wrong until the cache generation changes.

  6. Ariznawlll commented on Sep 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    The first query does not need a distance predicate to poison later range filtering. On two more fresh indexes:

    • an ordinary ORDER BY l2_distance(...) LIMIT 10 returned the correct nearest rows, then the first squared-L2 bounded query returned zero;
    • an ordinary ORDER BY l2_distance_sq(...) LIMIT 10 returned the correct nearest rows, then the first L2 bounded query returned zero.

    So a common unfiltered ANN request can establish the stale function unit before a later filtered request arrives. Upper-only ranges remained correct in the 80-row control; the wrong-result boundary is the lower-bound/local filter-before-Top-K path that calls filterEntryDistanceRange with the cached table config.

  7. Ariznawlll commented on Sep 17, 2026

    @Ariznawlll
    CollaboratorAuthor

    The issue also occurs entirely inside the first execution of one SQL statement. A query with two CTEs over the same fresh IVFFLAT index—one bounded by l2_distance, the other by the equivalent l2_distance_sq interval—produces two Vector Index Scan nodes but only one correct branch:

    CTEs declared l2, sq  -> l2 count 0;  sq count 10 at 40000
    CTEs declared sq, l2  -> sq count 0;  l2 count 10 at 200
    

    Changing declaration order flips which function wins cache initialization. Therefore prior workload history is not required: a single CTE/UNION query that legitimately uses both supported function forms can return an internally inconsistent result on its first execution.

  8. Ariznawlll commented on Sep 18, 2026

    @Ariznawlll
    CollaboratorAuthor

    补充确认:该缓存函数单位问题也会破坏单边距离范围,并不只发生在同时存在上下界时。此前“小 LIMIT 下 upper-only 正常”的现象,是因为最近的 K 行本来都满足上界,错误候选被 LIMIT 截断后没有暴露;当 LIMIT 足以容纳范围外候选时,上界错误可以直接观察到。

    固定环境:

    • commit:01d60e1c4ded1b0f3fc1a4ecd75ce54e95e23b90
    • 1 TN / 1 LogService / 2 CN,端口 16201、16202
    • 每张表 7 个非 NULL 向量,LISTS=1,建索引后 FORCE_SYNC REINDEX
    • 覆盖 VECF32、VECF64,以及 vector_l2_ops、vector_l2sq_ops

    每个新索引先执行 l2_distance,再执行等价的平方距离范围:

    SELECT id
    FROM t
    WHERE v IS NOT NULL
      AND l2_distance_sq(v, CAST('[0,0]' AS VECF32(2))) <= 56.25
    ORDER BY l2_distance_sq(v, CAST('[0,0]' AS VECF32(2)))
    LIMIT 20 BY RANK WITH OPTION 'mode=pre';

    源数据的平方距离依次为 0, 25, 100, 225, 400, 625, 900,因此 <= 56.25 应只返回 (1,2)。索引路径返回 (1,2,3,4,5,6,7);反向的 >= 56.25 应返回 (3,4,5,6,7),索引路径返回空集。

    覆盖结果:

    • VECF32/VECF64 × vector_l2_ops/vector_l2sq_ops × pre/post/auto × 2 CN
    • 单独上界 <=:24/24 返回范围外行
    • 单独下界 >=:24/24 漏掉全部范围内行
    • 三轮独立重建:每轮 48/48 稳定复现
    • 同一矩阵的 l2_distance 对照保持正确
    • 执行计划均选择 Vector Index Scan on ix [l2_distance_sq]

    这仍然属于本 issue 描述的同一机制:缓存对象保留先使用的 l2_distance 单位,后续 l2_distance_sq 的单边阈值也按错误单位进入 storage gate / 本地距离过滤。修复和回归用例需要覆盖单独上界与单独下界,并让 LIMIT 大于命中数,避免错误候选被 Top-K 截断掩盖。

  9. added a commit that references this issue on Oct 1, 2026
    112f7f3
  10. Ariznawlll commented on Oct 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    测试版本

    • 分支:main
    • Commit:d50a2d475a406829f67127fef7b2ad4abc1c1d3d
    • 部署方式:本地全新单 CN mo-service,独立数据目录;MySQL 文本协议与 server-side PREPARE
    • 测试日期:2026-10-02

    原问题验证

    按 issue 原始语义在上述 commit 重新执行并重复 3 次。同一缓存索引上 l2_distance 与 l2_distance_sq 均返回 10 行且集合一致。

    Happy Path 覆盖

    覆盖两种 metric、重复查询和 cache reuse。

    Unhappy Path 覆盖

    覆盖零向量、NULL、维度错误;错误受控且缓存未污染。

    白盒验证

    关联修复 #29535 已进入当前 main。同时将本 issue 的可公开观察契约固化为独立回归,避免只依赖实现细节或共享测试间接判断。

    回归测试

    测试证据

    • 精确测试版本:d50a2d475a406829f67127fef7b2ad4abc1c1d3d
    • 当前结果:同一缓存索引上 l2_distance 与 l2_distance_sq 均返回 10 行且集合一致。
    • 回归代码与 golden result 已提交到 MOTR #209;本地全量 14_issue_regression 中观察到的旧 GOROOT/历史 golden/并发锁冲突属于既有无关失败,以上新增用例单独重跑均稳定通过。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions