Repository navigation
Description
Is there an existing issue for the same bug?
- I searched existing open and closed issues for
getMostSelectiveIndexForPointSelectand forFORCE INDEXwith primary-key predicates. No direct duplicate found. Closed [Bug]: MySQL index hints return wrong rows or ignore missing composite indexes #25356 concerns wrong results/missing-index validation, rather than this access-path rejection.
Branch Name
v4.2.5
Commit ID
1a44f3db3056e32975fde86ca0ab69a094996a3f (server GIT_VERSION() returns 1a44f3d).
Other Environment Information
SELECT VERSION(), GIT_VERSION(), BUILD_VERSION();
8.0.30-MatrixOne-v4.2.5 | 1a44f3d | 2026-09-28 08:11:29
Local disposable database, synthetic rows only. Executed using server-side SQL PREPARE/EXECUTE, inside explicit transactions. This report does not claim reproduction on a newer main revision or a binary-protocol prepared-statement client.
Actual Behavior
A selective equality lookup on all three columns of UNIQUE(user_id, session_id, execution_key) does not use that index when the table's primary key starts with user_id, even with an explicit FORCE INDEX(uq_execution_key).
The reproducible control changes only the primary-key definition; both tables have the same columns, generated expression, unique secondary index, 20,004 synthetic rows and queries:
| Primary key | Query | Actual access / input rows |
|---|---|---|
(user_id, run_id) |
Unlocked | Base-table scan: 10,004 → 1 |
(user_id, run_id) |
FOR UPDATE |
Base-table scan: 10,004 → 1 |
(run_id) |
Unlocked | Secondary-index scan: 1; base-table lookup: 1 |
(run_id) |
FOR UPDATE |
Secondary-index scan: 1; base-table lookup: 1 |
All four queries correctly return root; this is a performance/access-path issue, not an observed wrong-result report. The 10,004 input rows are measured for the loading pattern below, not a guarantee for every physical layout: separate large inserts can allow zonemaps to prune inactive blocks and reduce the base scan count while the secondary index remains unselected.
The affected query is:
SELECT run_id
FROM pk_owner FORCE INDEX(uq_execution_key)
WHERE user_id = ? AND session_id = ? AND execution_key = ?
FOR UPDATE;
-- parameters: 'owner', 'target', ''This matters for multi-tenant execution/admission lookups: a tenant predicate on the first primary-key column does not bound that tenant's accumulated history. A selective composite secondary index should remain usable.
Expected Behavior
An equality predicate on only the first component of a composite primary key must not categorically exclude a much more selective secondary-index lookup. For this supported, fully constrained unique-key lookup, FORCE INDEX should produce the requested index access as it does in the control table, with and without FOR UPDATE.
Steps to Reproduce
Save the following as repro.py and run with Python 3 and the mysql CLI installed. Configure the connection using MYSQL_HOST, MYSQL_PORT, MYSQL_USER, and MYSQL_PWD; no application or third-party Python packages are required. The script checks result correctness, prints the actual plans, and creates/drops only its own randomly named disposable database. The account needs database create/drop privileges.
import os
import subprocess
import uuid
# Requires the mysql CLI; use MYSQL_HOST/PORT/USER/PWD for connection settings.
mysql = ["mysql", "--protocol=TCP", "--batch", "--raw", "--skip-column-names",
"--host=" + os.environ.get("MYSQL_HOST", "127.0.0.1"),
"--port=" + os.environ.get("MYSQL_PORT", "3306"),
"--user=" + os.environ.get("MYSQL_USER", "root")]
db = "mo_repro_pk_prefix_" + uuid.uuid4().hex[:12]
def literal(value):
return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
def query(sql, use_db=True):
result = subprocess.run(mysql + ([db] if use_db else []), input=sql,
text=True, capture_output=True, check=True, timeout=90)
return result.stdout.strip()
print(query("SELECT VERSION(), GIT_VERSION(), BUILD_VERSION()", False))
assert not query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=" + literal(db), False)
query("CREATE DATABASE " + db, False)
try:
for table, pk in [("pk_owner", "user_id,run_id"), ("pk_run", "run_id")]:
query("CREATE TABLE " + table + """ (
user_id VARCHAR(128) NOT NULL,
session_id VARCHAR(128) NOT NULL,
run_id VARCHAR(64) NOT NULL,
parent_run_id VARCHAR(64) NULL,
status VARCHAR(20) NOT NULL,
execution_key VARCHAR(64) GENERATED ALWAYS AS (
CASE WHEN status IN ('running','waiting')
THEN CASE WHEN parent_run_id IS NULL THEN '' ELSE run_id END
ELSE NULL END
) VIRTUAL,
PRIMARY KEY (""" + pk + """),
UNIQUE KEY uq_execution_key(user_id,session_id,execution_key)
)""")
# Keep the original 500-row batches: zonemap pruning can change row
# counts when inactive/active rows are loaded as separate large blocks.
for start in range(0, 20000, 500):
rows = []
for i in range(start, start + 500):
if i < 10000:
values = ["owner", "target", "r-" + str(i), "completed"]
else:
values = ["other", "foreign-" + str(i), "r-" + str(i), "running"]
rows.append("(" + ",".join(map(literal, values)) + ")")
query("INSERT INTO " + table + "(user_id,session_id,run_id,status) VALUES " + ",".join(rows))
query("INSERT INTO " + table + """(user_id,session_id,run_id,parent_run_id,status) VALUES
('owner','target','root',NULL,'running'),
('owner','target','child-1','root','running'),
('owner','target','child-2','root','waiting'),
('owner','target','child-3','root','running')""")
for lock in ["", " FOR UPDATE"]:
sql = ("SELECT run_id FROM " + table + " FORCE INDEX(uq_execution_key) "
"WHERE user_id=? AND session_id=? AND execution_key=?" + lock)
def prepared(explain):
return query("START TRANSACTION; PREPARE s FROM " + literal(("EXPLAIN ANALYZE " if explain else "") + sql) +
"; SET @u='owner', @s='target', @k=''; EXECUTE s USING @u,@s,@k; "
"DEALLOCATE PREPARE s; ROLLBACK;")
assert prepared(False) == "root"
print("\n" + table + (" / FOR UPDATE" if lock else " / unlocked"))
print(prepared(True))
finally:
query("DROP DATABASE " + db, False)
print("Dropped this script's disposable database: " + db)Captured execution plans
PRIMARY KEY(user_id, run_id), with FOR UPDATE:
root
Project
Analyze: timeConsumed=0ms waitTime=0ms inputRows=1 outputRows=1 (min=1, max=1) InputSize=24 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=24 bytes (min=24 bytes, max=24 bytes)
-> Lock
Analyze: timeConsumed=0ms waitTime=0ms inputRows=1 outputRows=1 (min=1, max=1) InputSize=48 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=24 bytes (min=24 bytes, max=24 bytes)
-> Table Scan on repro_db.pk_owner
Analyze: timeConsumed=0ms waitTime=6ms inputBlocks=2 inputRows=10004 outputRows=1 (min=1, max=1) InputSize=1.14 MiB OutputSize=48 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=989.36 KiB (min=989.36 KiB, max=989.36 KiB)
Filter Cond: prefix_eq(pk_owner.__mo_cpkey_col), (pk_owner.session_id = cast('target' AS VARCHAR)), (pk_owner.execution_key = cast('' AS VARCHAR))
Block Filter Cond: prefix_eq(pk_owner.__mo_cpkey_col), (pk_owner.user_id = cast('owner' AS VARCHAR))
Control PRIMARY KEY(run_id), with FOR UPDATE:
root
Project
Analyze: timeConsumed=0ms waitTime=0ms inputRows=1 outputRows=1 (min=1, max=1) InputSize=24 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=24 bytes (min=24 bytes, max=24 bytes)
-> Lock
Analyze: timeConsumed=0ms waitTime=0ms inputRows=1 outputRows=1 (min=1, max=1) InputSize=24 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=24 bytes (min=24 bytes, max=24 bytes)
-> Join
Analyze: timeConsumed=0ms waitTime=0ms inputRows=2 outputRows=1 (min=1, max=1) InputSize=48 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=24 bytes (min=0 bytes, max=24 bytes)
Join Type: INDEX
Join Cond: (pk_run.run_id = __mo_index_pri_col)
Runtime Filter Build: #[-1,0]
-> Table Scan on repro_db.pk_run [ForceOneCN]
Analyze: timeConsumed=0ms waitTime=0ms inputBlocks=1 inputRows=1 outputRows=1 (min=1, max=1) InputSize=96 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=123 bytes (min=123 bytes, max=123 bytes)
Filter Cond: (pk_run.user_id = cast('owner' AS VARCHAR)), (pk_run.session_id = cast('target' AS VARCHAR)), (pk_run.execution_key = cast('' AS VARCHAR))
Runtime Filter Probe: pk_run.run_id
-> Index Table Scan on pk_run.uq_execution_key [ForceOneCN]
Analyze: timeConsumed=0ms waitTime=0ms inputBlocks=1 inputRows=1 outputRows=1 (min=1, max=1) InputSize=48 bytes OutputSize=24 bytes ReadSize=0 bytes|0 bytes|0 bytes MemorySize=73 bytes (min=73 bytes, max=73 bytes)
Filter Cond: (__mo_index_idx_col = serial(cast('owner' AS VARCHAR), cast('target' AS VARCHAR), cast('' AS VARCHAR)))```
### Source-level diagnosis
In [`getMostSelectiveIndexForPointSelect` at the reproduced commit](https://github.com/matrixorigin/matrixone/blob/1a44f3db3056e32975fde86ca0ab69a094996a3f/pkg/sql/plan/apply_indices.go#L2548), the following shortcut returns before evaluating secondary-index candidates:
```go
firstPkColIdx := node.TableDef.Name2ColIndex[node.TableDef.Pkey.Names[0]]
_, ok := col2filter[firstPkColIdx]
if ok { //point select filter on first column of primary key, no need to go index
return -1, nil
}
It treats equality on the first primary-key component as sufficient to reject secondary-index point access. It also does not consult the passed ignoreStats value / force-index decision at this early return. The primary-key-only control agrees with this diagnosis. Index-only rewrites run separately, so this is not a claim that every secondary-index query containing a primary-key-prefix predicate is affected.
A fix should distinguish a genuinely selective/full primary-key lookup from an arbitrary tenant prefix and preserve explicit hint semantics. Regression coverage should include a non-covering composite unique lookup with an equal first composite-PK component, forced and automatic planning, prepared execution, and both locking/unlocked forms. FOR UPDATE itself is demonstrably compatible with index access in the control.
Activity
fix(plan): preserve composite predicates through secondary index sele…
XuPeng-SH commentedon Oct 24, 2026
Validated the reported access-path case on latest main
dae02bbaaaa18aac7fa9b788e42f4483b3adf091(binary SHA-256b534b2c2d33683eab3572971284093f6d584b626f4f94691b6dc050690c2d21c), using an isolated local MatrixOne service and synthetic data.On two tables with 20,004 rows each, server-side PREPARE/EXECUTE exercised both primary-key layouts (composite
(user_id, run_id)and control(run_id)), automatic and forced secondary-index selection, and unlocked /FOR UPDATEqueries. All eight queries returnedroot; all eightEXPLAIN ANALYZEplans useduq_execution_key, with one row entering the index scan and one row returned. A separate two-session lock challenge confirmed an update to a different row completed while the root row was locked, while an update to the same row waited 18.169 seconds until rollback and then succeeded.This is a latest-main access-path and lock-behavior validation on one local CN with synthetic rows. It is not a paired v4.2.5/current-main benchmark or a latency comparison.
fix(plan): restore composite secondary access on 4.2-dev (#31049)
Ariznawlll commentedon Oct 26, 2026
测试版本
maincommit:5fe08a3307e246e1ab9951ab690b50557af0f509;修复 PR #31048 MERGED,merge commitc93136ff6f7c40a3342c13102e436a34c70c8587在祖先链。4.2-devcommit:86a45d39df3d1f23490fcdd7328b46c5520efada;回移 PR #31049 MERGED,merge commit8f3e2bdcce3a4a6ac46f37b0d772b756ad4aba8e在祖先链。GIT_VERSION()分别为5fe08a3307/86a45d39df;二进制 SHA-256 分别为05c967b5a580ffdeec37efd446237a03477477dd463bb2e3c4297f5381cb43e7/220e20fa6d8833e3da080eafa8b27cf11338e9cf06a30919a5e8e1e2723ba580。原问题验证
保持 issue 原规模和装载形态:每轮建立
PRIMARY KEY(user_id,run_id)与PRIMARY KEY(run_id)两张表,每张 20,004 行、500 行一批装载,均含相同生成列和UNIQUE(user_id,session_id,execution_key)。两种主键 × 自动/FORCE INDEX× 普通/FOR UPDATE,共 8 种服务器端PREPARE/EXECUTE查询。两个分支各建 3 轮全新数据库;48/48 次实际返回root,对应EXPLAIN ANALYZE均出现uq_execution_key的Index Table Scan,没有退回原先的基表扫描。每轮结束删除数据库。Happy Path 覆盖
root并选用复合二级索引;main 3/3、4.2-dev 3/3。root后,不同记录的更新实际影响 1 行且未被该锁阻塞;同一root的更新在持锁期间等待,回滚持锁事务后影响 1 行。两个分支各 3/3。Unhappy Path 覆盖
execution_key返回 0 行;不存在的FORCE INDEX(no_such_index)被拒绝,目标表仍为 20,004 行。两个分支各 3/3,无错误操作后的数据变化。白盒验证
不适用:原问题是优化器对公共 SQL 的实际访问路径选择;本轮以真实
EXPLAIN ANALYZE、结果行与锁行为验证。没有把修复 PR 的作者测试算作独立 Go/race 结果。回归测试
MOTR #278 新增
issue_31046_composite_pk_secondary.py及配对期望输出,保留 20,004 行/表阈值;./motr --branch main --repeat 3 14_issue_regression.issue_31046_composite_pk_secondary结果total=3 success=3 failed=0 skipped=0。MOTR 完整 suite 和线上 CI 未运行,不宣称其通过。测试证据
/private/tmp/mo-qa-new-20261026-ROza73/motr-278/var/log/run-1792985545780571000,涵盖 8 种计划、缺失键及错误提示的原子性。20004 rows/table, 8 prepared index plans and lock isolation PASS。测试结论
测试通过。