Skip to content

[Performance]: Single-row IN subquery under OR causes ~61k wide-row backfills before FOR UPDATE #32552

Closed

Description

@LeftHandCold

Is there an existing issue for performance?

Environment

  • MatrixOne v4.2.8, exact running SHA 10d204b8763f19b2b37ba2147d1d4c1a7828d6d4.
  • IDC QA, two TP CNs, each 16 CPU / 55 GiB; Linux containers in Kubernetes.
  • Observed 2026-11-11 04:18 / 04:34 UTC (12:18 / 12:34 Asia/Shanghai).
  • Historical successful statements and their complete exported plans were inspected read-only. No live workload replay, forced GC, statistics refresh, index change or cluster mutation was performed.
  • Business identifiers, endpoint details and credentials are omitted. This is a performance optimization report, not a proven newly introduced regression, wrong-result bug, leak or deadlock.

Details of Performance

SQL shape (parameters redacted)

SELECT *
FROM workflow_execution
WHERE workspace_id = ?
  AND (
    id IN (
      SELECT workflow_execution_id
      FROM mowl_workflow_cases
      WHERE workspace_id = ? AND id = ?
        AND workflow_execution_id <> ''
    )
    OR mowl_case_id = ?
  )
FOR UPDATE;

The intended application operation locates one execution. In both actual samples the subquery returned one row and the final result contained one row, but the chosen plan fetched approximately 61k wide execution rows before the final disjunction filter.

Actual executed plan, not only estimates

workspace-leading secondary-index scan (~61k candidate PKs)
  -> IndexBuild + execution base-row scan / IndexJoin (~61k wide rows)
  -> MARK join (physical HashJoin) with the 1-row case subquery
  -> OR Filter (~61k -> 1 row)
  -> Merge -> LockOp (1 row) -> Output (1 row)

Both complete exported plans were approximately 54k characters and included physical producer instances. No LoopJoin was observed in these two samples. The execution projection contained 21 columns, including JSON/TEXT payloads.

Actual measurement CN sample A CN sample B
Request start, UTC 04:18:30.484623 04:34:31.618172
Statement wall time 19.804945 s 6.570093 s
execution base rows read 61,127 61,142
secondary-index output rows 61,127 61,142
case subquery output 1 1
OR Filter output / LockOp input 1 / 1 1 / 1
statement rows_read 61,128 61,143
statement bytes_scan 106,840,359 bytes 106,867,755 bytes
Lock Operator dedicated Wait Lock Time 12.745 ms 0.173 ms
PrepareRun dedicated WaitLock 51.195 ms 0.149 ms
BuildReaderDuration 10.265 s 4.665 s

Interpretation limits:

  • This is real broad read/materialization amplification for one-row results. It is not evidence that 19.8 seconds were spent waiting for a row lock.
  • Generic logical Lock Operator.Wait Time includes upstream Merge waits; it must not be treated as row-lock wait.
  • Phase durations can overlap. Cumulative producer time is neither independent wall time nor OS CPU time; do not add those values together.
  • bytes_scan is a logical statement statistic, not object-store traffic. Both resource summaries reported S3ReadBytes=0; this does not prove all reader setup was CPU time.
  • A bounded historical sample showed at least 17 overlapping in-flight statements of this shape on one CN at 04:34:35.335270 UTC. This is not a complete workload census, lock-holder count, or QPS benchmark.
  • There is no claim that these two statements explain every slow request that day.

Why engine-side investigation is warranted

The application can avoid this shape when it already knows the execution ID, and that work is tracked separately. Nevertheless this is a valid SQL shape: a tiny subquery result plus a selective alternative lookup should be evaluated for selective candidate generation, narrow filtering and late wide-row materialization, rather than accepting workspace-sized wide-row processing as unavoidable.

In the running source, IN-subquery flattening uses insertMarkJoin. That is consistent with the observed MARK plan but is not, by itself, proof of a defective transformation. Planner rule eligibility, real index metadata, estimates, cost selection and reader/backfill overhead still need isolation.

Do not blindly push the IN filter below OR: doing so could discard rows matching only the other branch. Any candidate union must preserve overlap deduplication, NULL semantics, workspace predicates and locking/snapshot correctness.

Reproduction / validation status

Observed: two real successful statements with actual physical metrics above. Not yet completed: a standalone synthetic reproduction, same-data alternative-plan A/B, or verification on current main. No claim that a particular PR fixes or introduced this case.

Suggested isolated fixture below captures the relevant types and index layout from the application schema definition. It is not a fresh live SHOW CREATE TABLE, and the fixture itself has not been executed in this investigation:

CREATE TABLE workflow_execution (
  id VARCHAR(64) NOT NULL PRIMARY KEY,
  workspace_id VARCHAR(64) NOT NULL,
  workflow_id VARCHAR(64) NOT NULL,
  status INT NOT NULL,
  mowl_case_id VARCHAR(64) NOT NULL DEFAULT '',
  input_payload_json LONGTEXT,
  vars_payload_json LONGTEXT,
  error_message TEXT,
  INDEX idx_workspace_workflow (workspace_id, workflow_id),
  INDEX idx_workspace_status (workspace_id, status),
  INDEX idx_case (mowl_case_id)
);
CREATE TABLE mowl_workflow_cases (
  id VARCHAR(36) NOT NULL PRIMARY KEY,
  workspace_id VARCHAR(64) NOT NULL DEFAULT '',
  workflow_execution_id VARCHAR(64) NOT NULL DEFAULT ''
);

In a disposable instance, populate ~60k execution rows in the target workspace (plus other workspaces), representative wide payloads, and one case/execution match. Then:

  1. Compare the original query and executed plan on the reported SHA and current main. Capture the actual deployed DDL/indexes and relevant statistics when available; source-defined indexes are not proof of the deployed physical schema.
  2. Compare direct primary-key lookup, each branch separately and semantics-preserving candidate-union/narrow-projection alternatives. Do not assume a rewrite is equivalent or faster without checking it.
  3. Compare with/without FOR UPDATE only as a diagnostic; the application requires locking semantics. Do not recommend removing locks as the fix.
  4. Verify actual index/base input rows, bytes processed, reader setup, allocations and latency at one request and bounded concurrency. Separate warm-cache work from storage IO and CPU scheduling delay.
  5. Cover missing case, empty execution ID, branch-only matches, both branches matching the same row, two different matching rows, nullable test variants, tenant/workspace residual predicates, deletion after lock wait, rollback, and prepared-statement parameter reuse. Do not add LIMIT merely to hide the scan.
  6. Keep a broad-selectivity fallback; a full scan can be correct when cheaper. The goal is bounded useful work for selective inputs, not forcing index access universally.

Additional information

Activity

  1. self-assigned this
    on Nov 12, 2026
  2. XuPeng-SH commented on Nov 13, 2026

    @XuPeng-SH
    Contributor

    QA handoff: main optimization merged, not performance acceptance

    #32607 is merged into main as 99605b39146848b56accc85bf933badf50a1fefc. Its bounded scan-local guard targets the reported wide-materialization cost for eligible local MARK joins under OR. The original MARK/OR filter, tenant residual and FOR UPDATE remain authoritative; unsupported shapes or oversized/incomplete optional filters fall back. This is not a claim that every production delay or all access paths are fixed.

    The issue has no current-main verified counterexample or unfinished development follow-up in its discussion. The PR's design-review follow-up is resolved by later approvals. The separate restore-probe deadline change references already-closed #28742; it does not establish the cause or resolution of the loaded-CI 180-second restore timeout.

    Remote evidence: the PR reports affected-package race tests, selective SQL/locking/prepared-reuse cases, SCA, coverage and BVT, with historical warm same-plan selective improvements and nonzero broad-match cost. The latest recorded review reuses qualified author reports and does not independently rerun runtime tests. These reports belong to their stated feature/review revisions, not a fresh merged-main benchmark performed in this handoff. No local SQL, race, benchmark or production replay was run here.

    Important retained boundary: the 4.2 QA comparison found a repeatable +22.1% broad-match regression with different INDEX plans. Its cause remains unresolved; same-plan measurements do not disprove it, and it is not evidence of a verified regression on this main merge. This handoff neither accepts 4.2 nor requests a backport.

    QA should use the exact merged SDK-independent server revision and actual deployed DDL/statistics to replay the original shape, compare selective and broad alternatives with captured physical plans, and measure wide rows/bytes, reader time, allocations and latency under warm/cold and bounded-concurrency conditions. Preserve B-only/IN-only/overlap, NULL/empty/oversized keys, tenant residuals, prepared reuse and FOR UPDATE/rollback/deletion-after-wait checks; do not remove locks or add LIMIT to mask work. Record guard eligibility/fallback and plan differences before attributing performance. Production workload replay and live mixed-version validation remain unverified. The application-side known-ID redesign has separate acceptance criteria.

    Assigning to QA while keeping this issue open; no acceptance or universal latency claim.

  3. Ariznawlll commented on Nov 14, 2026

    @Ariznawlll
    Collaborator

    结论

    测试不通过。4.2-dev 的构造场景中,原问题对应的选择性查询和功能回归已验证,但原生产环境及历史大范围匹配性能场景尚未完整复测,因此不能认定所有性能验收条件已通过。按照测试安排先关闭,保留以下限制和后续跟进信息。

    关键证据

    • 版本:官方 4.2-dev@d7931234da4274010bfd2b900c6e349da2fdf2fa;隔离环境为双 CN、单 TN、单 LogService,核对两 CN 的 git_version()。
    • 按问题中的 IN 子查询、OR 和 FOR UPDATE 构造 6.1 万行宽表:原修复前选择性查询扫描输出约 6.1 万宽行,当前执行计划仍扫描候选行但过滤后输出 1 行;修复前后交替运行 12 轮,端到端中位耗时分别为 69.9 ms 和 6.0 ms。该测试使用构造数据,并非客户环境的完整重放。
    • 覆盖单分支、两分支重叠、NULL、空值、租户残余条件、预编译参数复用、并发查询和锁等待后删除;新增用例重复 3/3 通过,其所在 4.2-dev issue-regression suite 24/24 通过、无跳过。功能与 suite 运行记录。
    • 宽匹配对照在本次构造数据上,12 轮完整结果返回中位耗时分别为 886.6 ms 和 898.0 ms;EXPLAIN ANALYZE 请求中位耗时分别为 181.8 ms 和 182.5 ms。配对基准记录。
    • 回归已提交 MOTR #339,目标分支为 4.2-dev;每日定时执行配置见 nightly #1943。两个 PR 尚未合并,需先合入 MOTR 再合入 nightly,定时回归才会生效。

    待解决点

    • 历史 4.2 QA 曾观察到不同 INDEX 计划下大范围匹配约 +22.1% 的耗时差异;本次构造数据的前后计划相同,不能排除或解释那个历史场景。原生产 DDL、统计信息、冷热缓存和真实负载下的重放也尚未完成;若需对这些场景作性能验收,仍需另行补测。
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