Skip to content

[Performance]: hybrid MATCH plus vector ORDER BY retains an unused full-result relevance sort #30164

Closed

Description

@XuPeng-SH

Is there an existing issue for performance?

  • I have checked the existing issues.

Searched fulltext/redundant-sort/hybrid reports. #25967 concerns outer ordering disabling vector index rewrite, not this extra relevance ordering beneath an already explicit distance order. #27453 is the broader shared index-scan architecture request.

Environment

  • Version or commit-id: main, 8586fa08715c868cab997d11d2687a76b8cc360f (actual tested binary; not a claim about today's main).
  • Hardware parameters: CPU-only local test; GOMAXPROCS=4, GOMEMLIMIT=6GiB. Physical CPU model was not recorded.
  • OS type: Linux amd64; Go1.27.1, GOAMD64=v3, GOEXPERIMENT=simd.
  • Others: 1 LogService / 1 TN / 1 CN; mysql-connector-python, use_pure=True, autocommit=True. Independent synthetic fixtures, no production source edits.

Details of Performance

A MATCH filter combined with explicit vector-distance ORDER BY retains an inner fulltext relevance-score Sort, even though the outer distance order discards that order. Actual EXPLAIN ANALYZE shows both operators consuming rows; this is more than a final-plan shape observation.

Executed HNSW+classic-fulltext fixture: 1026 rows, 16 rare-word hits. The hybrid gate correctly skips ANN and exactly sorts fulltext hits. The unnecessary score Sort nevertheless consumes/emits all 16 hits before the distance Top consumes 16 and emits 7:

Sort: l2_distance(v,q), LIMIT 7          inputRows=16 outputRows=7
  Sort: fulltext_alias.score DESC       inputRows=16 outputRows=16
    Join(base table, Fulltext Index Scan)

Results are correct (IDs 1010..1016); the complaint is extra sorting/state, not ANN recall or index absence. No production latency multiplier is inferred from the small local fixture.

Fixture / reproduction

The SQL below expresses the same rows as the executed Python insertion loop; it has not been separately rerun today.

CREATE DATABASE hybrid_repro;
USE hybrid_repro;
SET experimental_fulltext_index=1;
SET experimental_ivf_index=1;
SET experimental_hnsw_index=1;

CREATE TABLE docs(
  id BIGINT PRIMARY KEY,body TEXT,tag INT,v VECF32(2) NOT NULL
);
INSERT INTO docs
SELECT result,
       CASE WHEN result=1026 THEN NULL
            WHEN result>1009 THEN 'needle omega'
            WHEN result%3=0 THEN 'alpha beta'
            ELSE 'alpha plain' END,
       CASE WHEN result=1026 OR result%17=0 THEN NULL ELSE result%7 END,
       CONCAT('[',result,',0]')
FROM generate_series(1,1026,1) g;
CREATE FULLTEXT INDEX ix_ft ON docs(body);
CREATE INDEX ix_v USING hnsw ON docs(v) OP_TYPE 'vector_l2_ops';
SELECT mo_ctl('dn','flush','hybrid_repro.docs');

EXPLAIN ANALYZE
SELECT id FROM docs
WHERE MATCH(body) AGAINST('needle')
ORDER BY l2_distance(v,'[0,0]')
LIMIT 7;

No score is projected and no relevance pagination is requested. A relevance sort should be retained only when a consumer or pagination contract observes it. Explicit ordering by another expression should not incur an unused full-result relevance sort.

Additional information

Source localization: applyIndicesForProjectionUsingFullTextIndex adds a score Sort when its local sortNode is nil. An ancestor explicit distance ordering can make this locally inferred ordering unnecessary. The observed plan is consistent with missing ancestor order/demand information; no patched intervention or complete root-cause trace is claimed.

Fix constraints: distinguish relevance ORDER BY, relevance top-k/threshold consumers, projected MATCH scores, grouping/windows and explicit other-key order. Preserve LIMIT/OFFSET placement and all eligible matches; do not delete all fulltext ordering globally. Include classical FULLTEXT and FULLTEXT2, vector-free other-expression sorting, no/one/multiple outer order keys, score ties and large common-term hit sets. Assert actual sort inputs/state, not only an EXPLAIN label.

Retained receipt: hybrid-results.jsonl, hybrid/ft_hnsw/needle/all/default/analyze. HNSW fallback to exact sorting is intended; absence of a Vector Index Scan is not the defect. GPU and multi-CN paths were not run.

Repeated FULLTEXT execution in IVF PRE is a separate optimization concern and is tracked separately rather than assuming one fix covers both.

Activity

  1. cpegeric commented on Oct 15, 2026

    @cpegeric
    Contributor

    main is broken: pkg/sql/plan tests don't compile, and the covered FULLTEXT2 score LIMIT no longer reaches the search

    Affected: upstream/main 461bc8e. Two PRs that merged close together conflict with each other:

    1. Build break (all pkg/sql/plan unit tests)
      pkg/sql/plan/apply_indices_fulltext_snapshot_test.go:182:67: not enough arguments in call to
      builder.tryApplyCoveredFulltext2
      have (..., *plan.Expr, nil)
      want (..., *plan.Expr, *plan.Expr, bool)
      fix(plan): omit overwritten implicit fulltext ordering #30189 added the trailing orderOverwritten bool parameter. perf(plan): bound covered FULLTEXT2 score searches #30193 added a new call in
      TestCoveredFulltext2ScoreLimitOnBoundSQL without it. Each PR was green on its own, but main fails once both are
      merged.

    2. Behaviour regression (shows once the call compiles)
      --- FAIL: TestCoveredFulltext2ScoreLimitOnBoundSQL
      --- FAIL: .../score_alias apply_indices_fulltext_snapshot_test.go:239: Expected value not to be nil.
      --- FAIL: .../score_alias_offset
      Query shape: a covered FULLTEXT2 index with INCLUDE columns, and a query ordering by score with a limit:
      SELECT id, MATCH(title, body) AGAINST('hello' IN BOOLEAN MODE) AS sc
      FROM ft WHERE MATCH(title, body) AGAINST('hello' IN BOOLEAN MODE) AND base_id IS NULL
      ORDER BY sc DESC LIMIT 2;

    • Expected: the search scan gets CandidateLimit = 2, or 3 with OFFSET 1.
    • Actual: no candidate limit is set, so the search reads every match and sorts all of them.

    The results are still correct; the cost is performance, which is what #30193 was meant to fix.

    Cause:

    Fix: branch fix_ft2_score_limit, commit ddfc546, based on main.

    • Makes the inner score sort optional in pushCoveredFulltext2ScoreLimitFromSort. It only repeats the outer score-DESC
      order. When the sort is present, its key is still checked.
    • Adds the missing false argument to the test call.
    • The full pkg/sql/plan package passes with the fix.
  2. VioletQwQ-0 commented on Oct 15, 2026

    @VioletQwQ-0
    Collaborator

    转测交接:hybrid MATCH + vector ORDER BY 省略未消费的全量相关性排序(PR #30189 已合并)

    @Ariznawlll 你好,#30164 的修复已通过 PR #30189 合入 main,现按流程转测试验收。

    合入信息

    修复范围(对应原 issue 症状)

    • MATCH 过滤后跟随显式 vector 距离或其他键排序时,祖先序证明可穿透纯投影与过滤传递;在未被观察消费者使用前省略隐式相关性 Sort。classical FULLTEXT、普通 FULLTEXT2 与 covered INCLUDE FULLTEXT2 共享该决策
    • 保护项不变:默认相关性排序、显式 score 排序、投影 MATCH score、score 阈值、嵌套 LIMIT/OFFSET、有状态/volatile 消费者;全部合格命中仍在分页前到达显式外层排序

    验证证据

    • 开发自测(PR body 记录,绑定声明 base/head):planner 归属包 vet 与 focused 测试通过(.agents/skills/mo-dev/scripts/mo-cgo-test -p1 -vet=all ./pkg/sql/plan),仓库固定 golangci-lint 2.14.0 通过;mo-tester 正常模式四轮比较 PASS 53/53,直接 SQL 每版本 PASS 43/43(行列与列名一致),21 组成对 EXPLAIN ANALYZE 探针通过
    • 前后对照:base 侧冗余 score Sort 实际消费/发射全部 6 或 8,193 条命中(MemorySize 544.07 KiB 普通 / 224.03 KiB covered);head 侧该节点不存在,外层排序消费全部命中并返回 3/10 行,结果/默认相关性/嵌套分页/nextval barrier 一致
    • 最终 head 540e3fe9b60 当前检查状态(fresh 查询):9 success / 20 skipped / 1 cancelled / 2 neutral / 4 FAILURE。失败项:MO Checkin Regression On TKE / BUILD MO DOCKER IMAGE(镜像构建基建)、Matrixone CI execution / SCA Test on Linux/arm64、Matrixone Coverage execution / Coverage、Matrixone UT Coverage execution / UT Coverage on Ubuntu/x86——三项产品类检查在 final head 上的失败与本 PR 的关联未定性,已记录为待跟进项,不声称 required 全绿;PR 由 maintainer 手工合并
    • 本地自测:无新增独立本地执行;运行时证据绑定 PR body 声明的 base/head,最新 main 集成运行时证据未宣称

    请验收的场景(PASS/FAIL 预期)

    1. 复现原症状现已 FAIL(即修复生效):issue 中 1026 行 HNSW+经典全文 fixture 的 EXPLAIN ANALYZE ... ORDER BY l2_distance ... LIMIT 7,inner fulltext_alias.score DESC Sort 节点应不存在;结果 IDs 1010..1016 与顺序不变
    2. 保护项 PASS:无显式 ORDER BY 时默认相关性排序保持;显式 ORDER BY score DESC 仍保留 score Sort;投影 MATCH score 的查询结果含 score;score 阈值与嵌套 LIMIT/OFFSET 结果不变
    3. 大公共词集合:高命中量的混合查询外层排序正确分页,无结果被相关性状态截断
    4. classical FULLTEXT / FULLTEXT2 / covered INCLUDE FULLTEXT2 三类引擎路径行为一致;covered 路径无 base-table Join
    5. 环境建议:包含 461bc8e349 的 main 构建或 nightly;SET experimental_fulltext_index=1(及所需向量开关);CPU-only 即可,GPU/多 CN 未在开发侧覆盖,可在测试环境补充观测

    转测依据:issue 标签 kind/performance,无 compatibility 类标签,按维护约定分配 default tester @Ariznawlll。

    验证通过后请在本 issue 回复 PASS(注明版本/环境与终态结果),我将据此清理标签并关闭;如 FAIL 请附复现语句与版本,我会加 test-verification-failed 并继续修复。

  3. Ariznawlll commented on Oct 15, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:MatrixOne 官方 main
    • commit:cc024d091832cae5b9bcc0d3ec4137a05237e3e3(执行时官方 main)
    • 修复:#30289 已 MERGED,merge commit e8b3ed7f21c2b1966d74814adaa2bcd96d8c129f 已进入上述 main;该 PR 恢复 [Performance]: hybrid MATCH plus vector ORDER BY retains an unused full-result relevance sort #30164 的排序优化并兼容 covered FULLTEXT2 的候选上限
    • 部署方式:独立本地 macOS/arm64、1 CN / 1 TN / 1 LogService,独立数据目录、SQL 端口 16001;CPU-only,experimental_fulltext_index=1、experimental_fulltext2_index=1、max_dop=1
    • 测试日期:2026-10-16(北京时间)

    原问题验证

    按 issue 的 1026 行数据形状构造表(16 条 needle 命中),建立经典 FULLTEXT 和 HNSW 索引,执行 MATCH(body) AGAINST('needle') 过滤、ORDER BY l2_distance(v,'[0,0]') LIMIT 7。3/3 次均返回精确 ID 1010,1011,1012,1013,1014,1015,1016。EXPLAIN ANALYZE 只有距离排序,Sort Key: l2_distance 的 inputRows=16 outputRows=7;原先内层 score DESC 全量相关性 Sort 不再出现。这里验收的是多余排序/状态被去除及结果保持正确,不宣称生产吞吐或延迟增益。

    Happy Path 覆盖

    1. 经典 FULLTEXT、普通 FULLTEXT2、带 INCLUDE(tag) 的 covered FULLTEXT2:各 3/3 次返回同样的 7 个精确 ID,距离排序存在,未消费的 score Sort 不存在。
    2. 8193 行均命中公共词的独立数据集:3/3 次返回距离最近的 ID 1..7;外层 Sort 实际 inputRows=8193 outputRows=7,无内层全结果相关性 Sort,确认高命中量没有被提前截断。
    3. 不指定显式 ORDER BY 的对照:三种全文路径均保留默认 score 排序;covered FULLTEXT2 显式按 score 取 Top 2 时,计划保留 Candidate Limit: 2 的全文索引扫描且无 base-table Join。

    Unhappy Path 覆盖

    1. 1026 行 fixture 含 body=NULL 和 tag=NULL;这些行不会误进入 needle 命中集,精确结果与排序断言仍通过。
    2. 有状态/嵌套分页保护:检查嵌套 LIMIT/OFFSET 计划仍有相关性排序屏障;没有将所有隐式排序一概删除。未独立运行 Python UDF 服务或分布式多 CN、GPU 路径,这些不作为本次单机结构性缺陷的通过证据。

    白盒验证

    未在本次 QA 中重新运行 Go UT/race;修复 PR 的 planner 测试不能代替这里的最新官方 main 运行时验收。源 PR 的 exact-head Docker image CI 检查失败,原因尚未归因;不将其记为通过。

    回归测试

    • 已将针对原缺陷、三类全文路径、默认排序保护、covered Top-K 候选上限及 8193 命中的场景加入当天唯一的 MOTR 汇总 PR #237,文件:issue_30164_fulltext_overwritten_sort.py。定向执行 3/3 次,13 项断言每次全部通过;本地 06_fulltext_index suite 52/52 用例通过。
    • MOTR PR 当前仍 Open,4 项离线检查成功;完整集成 CI 与合入尚未完成,后续继续跟踪,不把 PR 创建等同于已合入覆盖。

    测试证据

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions