Skip to content

[Performance]: correlated EXISTS with expression correlate runs as nested-loop MARK join #31869

Closed

Description

@Ariznawlll

Description

A correlated EXISTS whose correlation is an expression (i.id = o.id - 1, not a plain column:column equality) falls off the hash-rewrite path and executes as a nested-loop MARK join — 30.7 seconds on 20k rows, while both semantically-identical rewrites run in under 10 milliseconds. At the 200k-row scale the same query exceeds a 25-second client read-timeout in my session (connection lost), with the CN worker pegged — i.e., effectively una runnable at trivial sizes.

Measured (main c6683bd2f5, 2026-10-30, table small 20k rows, warm):

form time count (parity)
WHERE EXISTS (SELECT 1 FROM small i WHERE i.id = o.id - 1) 30.70 s 19999 ✓
WHERE id IN (SELECT id + 1 FROM small) 0.00 s 19999 ✓
FROM small o, small i WHERE i.id = o.id - 1 0.00 s 19999 ✓

EXPLAIN shows the mechanism: the correlated form plans a Join Type: MARK with Join Cond: ((i.id = o.id - 1) IS TRUE) and no hashOnPK/hash marker — the plain i.id = o.id correlate (same tables, plain column equality) rewrites to hash semi-join and runs in milliseconds (verified earlier in the session). So the rewrite rule keys on column-equality correlates specifically; the expression-on-either-side correlate bypasses it entirely and lands in a naive nested-loop MARK. Even the inner probe's i.id = expr could hash on i.id (index/PK build side), which is exactly what the IN-rewrite's plan demonstrates is possible.

Missing-security note for triage: while pegged in the 30s query the CN accepted and serviced other sessions fine (regular 450ms scans returned in 0.0s), so it's a per-statement pathology — but each such statement monopolizes one worker; a handful of concurrent offenders starves the CN. Timeout/timeout-recommendation (query-level cancel, memory guard on MARK join cardinality) may matter more than the rewrite itself for deploy safety.

Impact

  • Any "find rows whose predecessor/successor exists" (id ± N, date ± interval deltas, computed foreign keys) shape — common in gap-detection, event-chaining, dedup-next-row analytics — is unusable beyond toy sizes, with no error surfaced: the client just hangs until its own timeout.
  • The join rewrites prove the fix is a planner rule extension (allow expression correlates into the hash build by normalizing i.id = o.id - 1 to i.id = k AND k = o.id - 1), not any executor work: hash-joining i.id against the computed key is exactly what the IN form already does.
  • A single such query by an unsuspecting BI user pegs a CN worker for minutes; my own session saw load average 44 on the dev box from this batch.

Expected behavior

Expression correlates normalize into the existing semi-join hash rewrite (build on the plain inner column, probe with the computed outer expression). Even without the rewrite, a guard could reject-with-cancel when the estimated MARK-join cost crosses O(n²).

Reproduction

CREATE TABLE small(id INT PRIMARY KEY, ...);  -- 20k rows
SELECT COUNT(*) FROM small o WHERE EXISTS (SELECT 1 FROM small i WHERE i.id = o.id - 1);  -- 30.7s
SELECT COUNT(*) FROM small WHERE id IN (SELECT id + 1 FROM small);                        -- <10ms, same count

main @ c6683bd; three-way parity verified; plan excerpt included above; 25s-timeout reproduction at 200k also performed (connection lost, worker pegged).

Activity

  1. added
    kind/bug
    on Oct 30, 2026
  2. added theissue type on Oct 30, 2026
  3. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    Family blast-radius extension (same session, same 20k-row fixture, all parity-checked):

    correlated shape time vs equivalent rewrite
    EXISTS (i.id = o.id - 1) (report body) 30.7 s IN-rewrite <10ms
    NOT EXISTS (i.id = o.id - 1) 20.0 s NOT IN (id+1) ~5ms
    EXISTS (i.id = o.id - 1 OR i.id = o.id + 1) 29.7 s none run (IN-union <50ms est.)
    EXISTS (i.tenant*10 + i.cat = o.tenant*10 + o.cat) (compound expr correlate) 5.5 s natural-key join <10ms
    EXISTS (i.id >= o.id AND i.tenant = o.tenant AND i.cat = 9) (mixed eq + range) 86 ms fine — the plain-column equality part enables a hash path
    scalar-agg correlate on plain column (MAX(amt)... WHERE tenant = o.tenant) 17 ms fine
    NOT IN (SELECT id - 1 ...) (expression in the projection) 5 ms fine — projection-side expressions DO hash-rewrite

    The pattern isolates cleanly: the semi/anti-join hash rewrite triggers only when correlates are plain column:column equalities; an expression on either correlate side — even a trivially normalizable arithmetic one, even a two-way OR between equalities — drops the plan into nested-loop MARK with seconds-to-minutes consequences. The mixed eq+range row shows the presence of any plain equality keeps the fast path, and the NOT IN projection row shows expression handling exists in the sibling rule. All inputs for a rule-extension fix; OR-of-equalities and expr-normalization are the two shapes to cover alongside the body's case.

    mistake-proofing note for whoever tests the fix: my first NOT IN with NULL-projection source appeared to return 18,000 (non-empty) but the source had zero NULL rows in that tenant partition (fixture artifact); re-verified with a genuinely NULL source (NULLIF(x,x), literal SELECT NULL, real NULL column) — all returned the required empty set. NOT IN NULL semantics are correct on MO; don't let a bad fixture send anyone down that path.

  4. added
    severity/s0
    and removed on Nov 3, 2026
  5. added a commit that references this issue on Nov 3, 2026
    dbf3efd
  6. assigned and unassigned on Nov 4, 2026
  7. slyunnn commented on Nov 5, 2026

    @slyunnn

    Regression and extended verification for #31869 (2026-11-05)

    Verification Environment

    • Frozen origin/main at test start, 80224b0314c6008ecb4de82d1e37b019d5e355df, fix(parser): support SERIAL columns and bare table grants (#32196). The clean verification worktree matched this commit. A fresh native service build, build log, binary version and runtime git_version() all identified 80224b0314.
    • macOS arm64, Go 1.27.1, GOMAXPROCS=4. Fresh isolated topology of 2 CN / 1 TN / 1 Log service / Proxy, using the repository's launch-with-proxy configuration and local disk file service.
    • Proxy 127.0.0.1:6001, CN1 127.0.0.1:16001 and CN2 127.0.0.1:16002 were connected and version-checked. Original scale queries, direct boundary checks, the complete selected SQL BVT and binary prepared checks were executed through each endpoint.
    • Clients used PyMySQL text protocol, mo-tester JDBC, and Go database/sql with go-sql-driver/mysql and interpolateParams=false, exercising real COM_STMT_PREPARE / COM_STMT_EXECUTE.

    What Was Covered

    • OK — Original i.id = o.id - 1 correlation at 20,000 and 200,000 rows returned exactly 19,999 and 199,999. Independent IN and equality-join rewrites returned the same counts at all three endpoints.
    • OK — NOT EXISTS, two-arm OR EXISTS, NOT EXISTS over those arms, compound arithmetic on both sides, and the plain-column equality control returned their independent expected counts at both scales.
    • OK — EXPLAIN ANALYZE and executed EXPLAIN PHYPLAN ANALYZE confirmed physical hash join instead of loop join for the tested eligible shapes. At 200,000 rows the runtime plan used mcpu=2, processed multiple blocks and globally merged the results. The disjunctive logical MARK joins are backed by physical hash joins.
    • OK — Direct Python-oracle checks covered duplicate inner witnesses, repeated outer values, NULL keys, positive/negative projected existence markers, empty inner input and mixed equality/range fallback at all three endpoints. An empty inner input preserved the guarded minimum-BIGINT arithmetic behavior. A genuinely NULL inner key preserved NOT IN semantics.
    • OK — Real binary prepared statements were reused with ordinary, absent-match and NULL bindings. A deliberate missing-column prepare error was followed by successful reuse of both already-prepared statements on the same connection at all three endpoints.
    • OK — The complete pkg/sql/plan and pkg/sql/compile package suites passed on the frozen commit. Relevant named tests verified safe arithmetic keys, disjunction eligibility, fallback, cancellation, physical hash-join selection, branch budgets, index costs and global distinct-set consumers.
    • Not covered — Live MySQL differential execution, production-hardware latency/QPS, TKE and a single query executing across both CNs were outside this run. Runtime physical evidence established workers on the selected coordinator. Both CNs were independently used as coordinators.

    Findings

    • The associated fix is dbf3efd4b5864216d32cfe95bc5a09690e9b4f72, fix(plan): hash safe arithmetic and OR EXISTS predicates (#32087), included in the tested main commit. It proves arithmetic safety before exposing hash keys and splits eligible disjunctions into bounded independently rebound existence branches. Fix PR
    • Local warm observations, medians of 3 executions after a warm-up at each endpoint, were about 1.04–1.21 ms / 5.75–6.65 ms for the original query at 20,000 / 200,000 rows, and 3.31–3.52 ms / 14.84–15.92 ms for two-arm OR EXISTS. These are diagnostic local timings. Mechanism and exact-result evidence support the conclusion, with no cross-machine speedup or production SLA claim.
    • Unsafe or unproved arithmetic, non-equality arms, correlated residuals, complex inner relations and over-budget disjunctions retain their guarded paths. Focused planner/compile tests passed for those boundaries. The fix does not promise every correlated expression a hash plan.

    MOTR / BVT Coverage

    • Reused test/distributed/cases/subquery/expression_exists.sql and its committed result. All 43/43 statements passed twice through each endpoint, totaling 258 successful statement comparisons. The second Proxy run and both direct-CN runs included result metadata comparison.
    • Existing committed coverage was sufficient. No duplicate MOTR case, source commit or weekly PR change was added. MatrixOne tracked source and test files remained unchanged.
    • Isolated direct boundary cases and binary-protocol checks ran concurrently across endpoints. Scale queries ran sequentially to limit contention. BVT runs ran sequentially because the runner performs global database cleanup. This scheduling is separate from the verified engine worker parallelism.
    • Package results were terminal PASS. The planner suite reported two existing skipped subtests for HNSW cosine_similarity and interval-frame binding, neither part of these fixes. Selected SQL BVT reported zero failures, ignored statements or abnormal statements.

    Final Conclusion

    Fixed on 80224b0314c6008ecb4de82d1e37b019d5e355df for the reported safe arithmetic and eligible disjunctive EXISTS / NOT EXISTS scenarios.

    Large-data regression was required and completed at 20,000 and 200,000 rows because the original defect depended on quadratic join work. The tested scales exercised the original failure sizes, multi-block scans and real parallel hash execution. Further arbitrary enlargement or TKE performance testing is unnecessary for this scoped regression.

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

Metadata

Metadata

Assignees

Labels

kind/bugperformanceseverity/s0

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions