Repository navigation
Description
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 - 1toi.id = k AND k = o.id - 1), not any executor work: hash-joiningi.idagainst 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 countmain @ c6683bd; three-way parity verified; plan excerpt included above; 25s-timeout reproduction at 200k also performed (connection lost, worker pegged).
Activity
Ariznawlll commentedon Oct 30, 2026
Family blast-radius extension (same session, same 20k-row fixture, all parity-checked):
EXISTS (i.id = o.id - 1)(report body)NOT EXISTS (i.id = o.id - 1)EXISTS (i.id = o.id - 1 OR i.id = o.id + 1)EXISTS (i.tenant*10 + i.cat = o.tenant*10 + o.cat)(compound expr correlate)EXISTS (i.id >= o.id AND i.tenant = o.tenant AND i.cat = 9)(mixed eq + range)MAX(amt)... WHERE tenant = o.tenant)NOT IN (SELECT id - 1 ...)(expression in the projection)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.
fix(plan): hash safe arithmetic and OR EXISTS predicates (#32087)
slyunnn commentedon Nov 5, 2026
Regression and extended verification for #31869 (2026-11-05)
Verification Environment
origin/mainat 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 runtimegit_version()all identified80224b0314.arm64, Go1.27.1,GOMAXPROCS=4. Fresh isolated topology of2 CN / 1 TN / 1 Log service / Proxy, using the repository'slaunch-with-proxyconfiguration and local disk file service.127.0.0.1:6001, CN1127.0.0.1:16001and CN2127.0.0.1:16002were connected and version-checked. Original scale queries, direct boundary checks, the complete selected SQL BVT and binary prepared checks were executed through each endpoint.database/sqlwithgo-sql-driver/mysqlandinterpolateParams=false, exercising realCOM_STMT_PREPARE/COM_STMT_EXECUTE.What Was Covered
i.id = o.id - 1correlation at20,000and200,000rows returned exactly19,999and199,999. IndependentINand equality-join rewrites returned the same counts at all three endpoints.NOT EXISTS, two-armOR EXISTS,NOT EXISTSover those arms, compound arithmetic on both sides, and the plain-column equality control returned their independent expected counts at both scales.EXPLAIN ANALYZEand executedEXPLAIN PHYPLAN ANALYZEconfirmed physicalhash joininstead ofloop joinfor the tested eligible shapes. At200,000rows the runtime plan usedmcpu=2, processed multiple blocks and globally merged the results. The disjunctive logicalMARKjoins are backed by physical hash joins.NULLkeys, 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-BIGINTarithmetic behavior. A genuinelyNULLinner key preservedNOT INsemantics.NULLbindings. A deliberate missing-column prepare error was followed by successful reuse of both already-prepared statements on the same connection at all three endpoints.pkg/sql/planandpkg/sql/compilepackage 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.Findings
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 PR3executions after a warm-up at each endpoint, were about1.04–1.21 ms/5.75–6.65 msfor the original query at20,000/200,000rows, and3.31–3.52 ms/14.84–15.92 msfor two-armOR EXISTS. These are diagnostic local timings. Mechanism and exact-result evidence support the conclusion, with no cross-machine speedup or production SLA claim.MOTR / BVT Coverage
test/distributed/cases/subquery/expression_exists.sqland its committed result. All43/43statements passed twice through each endpoint, totaling258successful statement comparisons. The second Proxy run and both direct-CN runs included result metadata comparison.PASS. The planner suite reported two existing skipped subtests for HNSWcosine_similarityand interval-frame binding, neither part of these fixes. Selected SQL BVT reported zero failures, ignored statements or abnormal statements.Final Conclusion
Fixed on
80224b0314c6008ecb4de82d1e37b019d5e355dffor the reported safe arithmetic and eligible disjunctiveEXISTS/NOT EXISTSscenarios.Large-data regression was required and completed at
20,000and200,000rows 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.