Skip to content

[Bug]: ODKU with UNIQUE keys performs full hidden-index validation scan after selective target lookup #29197

Closed

Description

@Ariznawlll

Independent QA update — 2026-10-06

Confirmed outcome

The original minimal KEY-partition + UNIQUE-key ODKU witness does not reproduce a panic or wrong-row update at tested commit 6655ceef2b587275db1075cdd46bf2a4c60cf1db. Independent live SQL validation through a two-CN embedded cluster passes:

  • PK-only partitioned ODKU control.
  • The original KEY-partition + UNIQUE-key witness: result (1,10,999), (2,20,200).
  • RANGE partition + UNIQUE key, where incoming id=99 conflicts with stored id=1: the stored row is updated in its original partition; physical p0 contains the expected rows and p1 remains empty.
  • Composite UNIQUE key (uk,v) with ODKU updating an independent ordinary payload column w.

The initial composite probe attempted to update a UNIQUE-key member and was correctly rejected with unsupported DML: update unique key on duplicate; it was corrected to update w. SELECT ... PARTITION(p0) is unsupported syntax, so the physical routing checks queried the actual quoted partition relation names instead. Neither probe correction is evidence of the reported partition correctness defect.

Storage-layer disttae relation construction expands partitioned base tables and hidden indexes through combinedTxnTable. Absence of explicit partition fields in the binder alone therefore does not establish a partition-blind scan. The historical correctness hypotheses below remain unproven; FULLTEXT/irregular maintenance and concurrent cases have not been validated in this update.

Confirmed performance defect: full UNIQUE-index scan after target resolution

A one-row UNIQUE conflict ODKU updating only ordinary column v performs a selective conflict-target lookup, then a downstream DEDUP (FAIL) UNIQUE-key validation scans the entire hidden UNIQUE index. This occurs for nonpartitioned, KEY-partitioned and RANGE-partitioned tables, so it is a shared ODKU performance problem, not demonstrated partition-specific corruption. Related to #29196.

Measured SQL shape:

CREATE TABLE p(id INT PRIMARY KEY, uk INT UNIQUE, v INT);
-- Populate N distinct rows: (i, i * 10, 0), i=1..N.
-- Partitioned variants use eight KEY(id) or RANGE(id) partitions.
INSERT INTO p VALUES (N + 99, 10, 999)
ON DUPLICATE KEY UPDATE v = v + 1;

Runtime logical and physical EXPLAIN ANALYZE evidence at N=100,000:

  • Conflict-target UNIQUE-index probe: 1 row; resolved old-row lookup: 1 row; incoming PK probe: 0 rows.
  • Later UNIQUE-index validation scan: InRows=100000, OutRows=100000, ScanBytes=400000, feeding a dedup join that emits 1 row.
  • KEY and RANGE variants show the same 100,000-row validation scan across eight partitions.
  • PK-only ODKU controls read 1 row, with no full UNIQUE-index scan.
  • The measured validation scan has zero disk/network I/O; this already reproduces with hot local data.

Controlled local timing

Two complete rounds ran successfully. Round 2 reversed data-size and table-shape order and added PK-only controls. Each shape/mode used 3 warmups and 20 measured operations. Both direct SQL and binary-protocol prepared executions were measured; the table below reports round-2 prepared median latency:

Shape 10,000 rows 100,000 rows
Nonpartitioned + UNIQUE 6.208 ms 14.571 ms
KEY partition + UNIQUE 6.483 ms 15.205 ms
RANGE partition + UNIQUE 7.080 ms 14.438 ms
Nonpartitioned PK-only control 5.151 ms 5.134 ms
KEY partition PK-only control 5.616 ms 5.415 ms

Round 1 also reproduces the size-dependent UNIQUE path (100,000-row prepared medians: nonpartitioned 14.210 ms, KEY 15.295 ms, RANGE 14.300 ms). The scan counters, rather than timing alone, identify the unnecessary size-dependent work. No material partition-specific amplification is established by these local results.

All measured operations preserve row count and increment only the expected (id=1, uk=10) row. Fixtures clean their tables/database, and no production source changes were made; probes were temporary Go overlays.

Scope and required next closure

  • Tested head: 6655ceef2b587275db1075cdd46bf2a4c60cf1db; local Go 1.26.4, two-CN fixture, GOMAXPROCS=2, single SQL client.
  • This is a reproducible full-index validation cost, not a demonstrated version-to-version performance regression or concurrent-QPS result. It is not an exact latest-main execution claim.
  • Investigate the existing UNIQUE-dedup admission/runtime-filter owner after target resolution. Preserve ordered multi-row ODKU semantics, mixed INSERT/UPDATE actions, NULL handling, locking and concurrent uniqueness checks; do not globally remove uniqueness validation or prune by the incoming partition key.
  • Continue separate correctness challenges for irregular/FULLTEXT maintenance and concurrent partition cases before claiming those historical hypotheses closed.

Original investigation (historical hypotheses; retained for traceability)

[Bug]: ODKU with unique keys on partitioned tables uses partition-unaware target_pk resolution + DEDUP scans (untested path, fragile partition col handling in dedupjoin)

Summary

INSERT ... ON DUPLICATE KEY UPDATE on a partitioned table that also has one or more UNIQUE KEYs triggers buildOnDupTargetPkResolution (extra full TABLE_SCAN + LEFT JOINs over PK probe + every UK hidden index table to compute target_pk = COALESCE(...)) followed by the main DEDUP update join.

This path:

  • Creates raw TABLE_SCAN nodes for the base table and all UK hidden index tables with no partition context, no Partition info, and no filter derived from partition key.
  • Never references tableDef.Partition inside bind_insert.go (0 occurrences).
  • Relies on a fragile @FIXME hack in colexec/dedupjoin/join.go (probe/UPDATE result projection) that detects T_Rowid to pull "right child's partition column" from the old batch.

Basic partitioned ODKU (PK only, no UKs) has BVT coverage. UK + partition ODKU, and especially when irregular indexes are also present, have none.

Current behavior

  • DDL succeeds for partitioned table + PK + UK(s).
  • ODKU without UKs on partitioned tables appears to work (engine-level routing from row values).
  • ODKU with UKs exercises the target-pk code and the dedupjoin FIXME path with no partition-aware scans or lock targets in the binder for the UK hidden tables.
  • Related fulltext case on partitioned tables already panics on plain INSERT (see [Bug]: INSERT into a partitioned table with a FULLTEXT index panics in disttae Write #28311).

Expected

Either:

  1. The target_pk resolution, DEDUP build scans, UK hidden index scans, and irregular maint sources in the ODKU binder must carry / respect partition definitions (or delegate via the same partitionExpr / LockTarget mechanisms used in normal DML paths), or
  2. Explicitly reject ODKU (or at least ODKU on tables with UKs) for partitioned tables until the paths are audited and fixed, similar to how other unsupported DML combos error early.

Correct conflict resolution + partition routing must be preserved; no cross-partition wrong-row updates or "cannot write to partition primary table" panics.

Reproduction (add EXPLAIN + result when possible)

drop database if exists odku_part_uk;
create database odku_part_uk; use odku_part_uk;

create table p(
  id int primary key,
  uk int unique,
  v  int
) partition by key(id) partitions 2;

insert into p values (1,10,100), (2,20,200);

-- UK conflict on partitioned table (triggers target_pk resolution + dedup UPDATE)
insert into p values (99,10,999) on duplicate key update v = values(v);

select * from p order by id;

Also test with composite UK, RANGE partition, and add a FULLTEXT index (will also exercise irregular ODKU maint).

Capture:

  • EXPLAIN (verbose) of the INSERT ... ON DUPLICATE ...
  • Whether it succeeds or panics / returns wrong rows
  • system.statement_info row for the statement (plan, bytes_scan, etc.)

Code pointers (current main)

  • Planning: pkg/sql/plan/bind_insert.go
    • useTargetPk + buildOnDupTargetPkResolution (~1508, ~869): always full scans + LEFT JOINs for PK + every UK; produces target_pk; no partition handling.
    • appendDedupAndMultiUpdateNodesForBindInsert (~1227): creates the PK/UK dedup TABLE_SCANs, LOCK_OPs, DEDUP node.
    • appendOnDupIrregularMaintSource (~384), buildIrregularFulltextDeleteByPk (~666), buildIrregularIndexDeleteMaintenance: custom delete/pre-insert from ODKU sink; partition-blind.
  • colexec: pkg/sql/colexec/dedupjoin/join.go:720 (the rowid / "partition column" FIXME in UPDATE result projection).
  • Contrast normal DML partition handling: pkg/sql/plan/build_dml_util.go (partitionExpr threaded to appendPrimary..., makeOneDelete..., locks), query_builder.go.

Related

Suggested next

  1. Add the missing cross tests (partition + UK + ODKU, partition + fulltext + ODKU) once the panic in [Bug]: INSERT into a partitioned table with a FULLTEXT index panics in disttae Write #28311 is resolved.
  2. Thread partition context through the ODKU binder for target resolution scans, dedup scans, lock targets, and irregular maint (or centralize the dedup logic so partition logic is not duplicated/bypassed).
  3. Replace the rowid hack in dedupjoin with a proper mechanism for partition columns under ODKU UPDATE.

Environment: main as of investigation (2026-09-21), standalone/distributed.

Activity

  1. added
    kind/bug
    severity/s2
    area/partition
    and removed
    severity/s2
    on Sep 21, 2026
  2. added theissue type on Sep 21, 2026
  3. added this to the MO-202609 milestone on Sep 21, 2026
  4. self-assigned this
    on Sep 21, 2026
  5. changed the title [-][Bug]: ODKU with unique keys on partitioned tables uses partition-unaware target_pk resolution + DEDUP scans (untested path + dedupjoin FIXME)[/-] [+][Bug]: ODKU with UNIQUE keys performs full hidden-index validation scan after selective target lookup[/+] on Oct 6, 2026
  6. added a commit that references this issue on Oct 6, 2026
    d9eb0e0
  7. Ariznawlll commented on Oct 9, 2026

    @Ariznawlll
    CollaboratorAuthor

    测试版本

    • 分支:官方 main
    • commit:dca6ffc2bf21036627b221b67f05943fbe458cf0
    • 部署方式:独立本地单 CN;另用同一 commit 的双 CN 配置分别从 CN1、CN2 入口复测
    • 测试日期:2026-10-09

    原问题验证

    构造非分区、8 分区 KEY(id)、8 分区 RANGE(id) 三种 id PRIMARY KEY, uk UNIQUE, v 表,每表 100,000 行。执行只更新普通列 v 的 UNIQUE 键冲突 ODKU,并用 EXPLAIN ANALYZE 检查实际 Table Scan/Index Table Scan 的 inputRows,不只看最终结果。三种形态的扫描均未出现原先 100,000 行隐藏 UNIQUE 索引验证全扫,所检查的每个扫描算子均不超过 8,192 行;冲突均命中原有 (id=1,uk=10),表仍为 100,000 行。单 CN 定向回归重复 3/3;双 CN 配置从 CN1、CN2 各运行一轮,全部通过。

    Happy Path 覆盖

    1. 非分区、KEY、RANGE 的 UNIQUE 冲突更新都得到正确目标行和行数;PK-only 对照同样保持选择性扫描。
    2. KEY 分区表上 20 个并发客户端对同一 UNIQUE 冲突行执行自增,最终 v=21(含先前一次验证更新),无丢失更新或误插入,行数仍为 100,000。

    Unhappy Path 覆盖

    1. 尝试在 ODKU 中修改 UNIQUE 键成员被明确拒绝;失败后原行仍为 (1,10,21),表行数不变,证明拒绝路径没有留下半更新。
    2. 三种表形态的扫描量断言会在恢复到 100,000 行全扫时失败,避免仅凭正确结果掩盖性能回退。

    白盒验证

    此项验收的是实际计划工作量,采用 EXPLAIN ANALYZE 的扫描算子计数;没有把不稳定的耗时/QPS 当作唯一证据。未声称完成修复前后严格 A/B 吞吐对比。

    回归测试

    测试证据

    测试结论

    测试通过。

  8. LeftHandCold commented on Oct 12, 2026

    @LeftHandCold
    Collaborator

    Follow-up: nightly concurrency assertion failures, with exact-image isolated validation

    Two consecutive Main MOTR runs fail key_concurrent_conflicts in the existing issue_29197_odku_unique_scan case:

    The original selective-scan checks pass. The concurrency check expects (id=1,uk=10,v=21) and a total of 100,000 rows after the earlier one-row EXPLAIN ANALYZE update plus 20 successful concurrent ODKUs. The helper uses autocommit and waits for every future; this is not an uncommitted-client fixture by inspection.

    The subsequent key_rejection_atomic failure depends on the same expected v=21. It does not independently prove that the rejected UNIQUE-key update partially executed.

    What the nightly artifacts do not establish

    The case prints PASS/FAIL, but does not preserve the actual returned tuple or row count. Therefore the current artifact cannot distinguish a lost increment, an extra row, an indexed read/visibility problem or another failed invariant component. The inspected service-log slice does not supply those missing result rows either.

    Completed validation on an isolated Linux host

    I started a fresh, dedicated single-CN quickstart container from the exact incident image, with image digest:

    sha256:fedd9e610b9fc0f0a780f27e24d11ef81cdc6f2d260247165b03f16be39d5485

    The original pinned script ran five complete times. A diagnostic wrapper only recorded existing read results and successful increment completions; it did not retry writes, weaken assertions or change MO production code.

    Check Result
    Successful concurrent increments per repetition 20 / 20, for all five repetitions
    Final UNIQUE lookup and PK lookup (1, 10, 21) in every repetition
    Final row count 100,000 in every repetition
    Unsupported UNIQUE-key update Rejected; checked values/count unchanged
    Existing scan/result assertions Passed in all five repetitions

    This is not a reproduction of the shared, multi-CN nightly environment and does not clear the Daily correctness candidate. It also does not justify reopening this issue as a recurrence of the already-fixed hidden-index full scan.

    Recommended next evidence

    On the existing case's next failure, preserve the actual UNIQUE lookup tuple, PK lookup tuple, total row count, successful-operation count, individual completion status, and connection/CN identity. Capture immediate and follow-up reads without retrying any successful write. Keep the rejected-update before/after comparison separate from an already-failed increment invariant.

    Decision: record the failed closure-acceptance observation here, leave the original scan-performance issue closed for now, and do not claim a confirmed lost-update bug or an introducing PR. Reopen or split into a correctness issue once the actual failing result and mechanism are available.

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

Metadata

Metadata

Assignees

Labels

area/partitionkind/bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions