Skip to content

feat(sql): support multilevel correlated subqueries - #30116

Merged
mergify[bot] merged 8 commits into
matrixorigin:mainfrom
ck89119:issue-7559-from-scratch-main
Oct 18, 2026
Merged

mergify[bot] merged 8 commits into
matrixorigin:mainfrom
ck89119:issue-7559-from-scratch-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Closes #7559

What this PR does / why we need it:

Support multilevel correlated subqueries that cannot safely be flattened into the existing join rewrites. For example, SELECT o.k, (SELECT (SELECT o.k + 1)) FROM t AS o now resolves the ancestor reference and evaluates it for each demanded outer row. Scalar empty results, cardinality errors, tuple comparisons, NULL semantics, and unselected branches retain their SQL behavior.

The implementation binds ancestor values to typed parameter slots, compiles immutable relational programs once, and executes demanded invocations through a continuation on the existing execution lane. It covers aggregate, join, window, pagination, set/CTE/recursive-source, and DML stages while preserving eligible existing fast paths. Each invocation shares the statement transaction, snapshot, and resource budget, with independent cancellation and cleanup ownership.

The approved design is revision r1. Design approval preceded implementation.

Compatibility and execution scope

  • Dependent programs execute on the coordinating CN and require MORPC 112. Ordinary remote fragments reject private dependent expressions.
  • PREPARE, View rebinding, and source/Proxy/target migration check the capability. An incompatible migration target is rejected before changing session state.
  • No new database data format. Existing independent SQL syntax and visibility restrictions remain in place.
  • The general execution path can perform E × I work; it does not cache results across equal-valued outer rows.

Validation

Local validation used Go 1.27.1 and independently built native artifacts on macOS/arm64. The committed implementation matches the validated source fingerprints; the implementation baseline is 175a645a85994f2c95992d3aa8d6dacb6d9e167f.

  • make build; regenerated plan/query protobuf and both postprocessed artifacts matched byte-for-byte.
  • Focused and owning-package tests, including full planner/compiler tests and affected spill operators.
  • Six mo-tester comparison suites: nested scalar 91/91, local outer-reference CTE 268/268, ODKU 425/425, conditional INSERT 166/166, scalar projection 115/115, and correlated LIMIT 55/55, with no failures or ignored cases in these suites.
  • Existing ANY/IN/EXISTS regressions passed their active cases; respectively 3/21/14 existing ignored cases are excluded from the pass claim.
  • Real two-CN/Proxy checks: reject a protocol-111 migration target while preserving the original PREPARE; migrate to protocol 112 and reuse the same PREPARE/session variables; authorization and revocation; cancellation followed by reuse of the same connection.
  • Full -race runs for process, colexec, dependent, mongoscan, and compile. Five focused lifecycle cases passed 100 repetitions each; NativeStages passed 20 repetitions based on its measured runtime.
  • Changed executable-line coverage 81.76% (3618/4425), merged only from profiles matching current production-file fingerprints.
  • go vet on 43 changed packages; incremental golangci-lint with all 150 changed/new Go files in the explicit patch: 0 issues; gofmt and diff checks passed.

Performance

Sequential baseline comparisons, three 1-second runs per case: ordinary planning median 50.413 → 50.769 µs; existing one-level scalar planning 79.997 → 87.132 µs (+7.1 µs, +8.9%); native constant-expression execution 12.17 → 12.15 ns with zero allocations. These are planning/kernel microbenchmarks, not cluster throughput measurements.

General-path benchmarks vary outer rows, inner rows, and depth. They verify result oracles, E+1 table-reader opens, one-time source compilation, balanced source closure, and zero retained budget after every execution. Peak accounted memory grows with active depth rather than accumulated historical invocations.

The branch merges textually without conflicts with main@35c8dd5854. Integration CI for the PR is pending.

@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Oct 13, 2026
@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 725295a235769eccf13e1b53ca64c3c50597735a

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: 725295a235769eccf13e1b53ca64c3c50597735a

Assessment: request_changes

Reviewed the complete 182-file delta and surrounding callers. Typed slots and per-invocation continuations reasonably support multilevel correlation while reusing native operators. One confirmed integration defect remains in prepared-result metadata.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

  • P2 pkg/frontend/result_row_stmt.go:193: With t(k int) containing 1 and 2, set group_concat_max_len=64, then prepare and execute SELECT GROUP_CONCAT(k), (SELECT (SELECT t.k)) FROM t GROUP BY k.
    Impact: The first result column is reported as TEXT instead of VARCHAR, exposing incorrect SQL type metadata to clients.
    Evidence: The new planner appends subprogram roots after the main output, but overlayPreparedGroupConcatResultMetadata still selects len(query.Steps)-1. Here the selected subprogram has one projection versus two result columns, so the overlay returns without applying the <=512 rule. Use query.MainOutputStep(), preserving the RETURNING override, and add a protocol-level regression. The real MySQL PREPARE/EXECUTE probe reports VARCHAR for the ordinary control and TEXT for the correlated query. Retained evidence: review_sql_test.go, review-sql.log and checks/1792008948163279568-13.json under the assigned attempt directory; exact-head execution exited 1 on this assertion.

Validation:

  • Read local_validation before testing; it is empty. Reconciled command, source fingerprint, exit receipts and retained logs. Source remained clean at the assigned head.

  • Private /tmp and loopback preflight passed. Initial native setup failed before tests; compatible repository-built prerequisites were subsequently recovered by verifying 192 native inputs and 46 output hashes.

  • TestDependentJoinAlgorithm, TestDependentIndependentJoinWork and TestDependentNativeStages passed using the supplied test-exec. Receipt: checks/1792008777215397010-13.json; log: focused-native.log. Independent joins used one hash join and zero pair callbacks at both 100 and 200 input rows.

  • Generated descriptor checks preserved existing fields/options and matched the new schemas. Final artifact audit passed: checks/1792009298048683021-4.json and audit-final.log.

  • Rechecked supplied review concerns. Current hash selection and stable DML step ownership address the earlier concrete join and external-INSERT findings. Unsupported historical symbol-based allegations were not carried forward.

  • The frozen exact-head CI snapshot reports successful Ubuntu UT, coverage, proxy and pessimistic multi-CN BVT. Detailed review, change map and evidence audit are retained under /home/xupeng/.local/state/mo-bot/jobs/7252128efcce56864ef58830/attempt-1/.

Limitations:

  • No fresh full-suite, race, multi-CN or mixed-version deployment run. CI summaries were available, not detailed CI execution logs; skipped jobs are not counted as passes.

  • Local performance validation measured join work counts, not throughput. Dependent execution can multiply inner work by demanded environments. Author-reported planning overhead, including approximately 8.9% for a legacy scalar case, lacks retained exact-candidate benchmark receipts and remains independently unverified.

  • The frozen bundle contains no separate linked-issue body; behavioral review used the supplied PR, design document and source. The confirmed metadata defect prevents approval.

@XuPeng-SH

XuPeng-SH commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d53bf3b00f655be99b6176d4d841f69b8dbdefae

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: d53bf3b00f655be99b6176d4d841f69b8dbdefae

Assessment: request_changes

Reviewed the complete 186-file delta. Typed lexical programs, continuations, and reuse of native kernels form a coherent design. Previous join-performance, DML-ownership, and prepared-metadata concerns are resolved. One reproducible test-isolation defect remains.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 test/distributed/cases/stage/dependent_insert_ownership.sql:12: Rerun this case against the same resource directory after a successful or interrupted execution.
    Impact: The fixed CSV glob reads previous outputs because DROP DATABASE and DROP STAGE leave external files intact. The regression test deterministically fails on replay. Clean up this case's files, including after failures, or isolate each invocation's read/write prefix; then verify two successive runs.
    Evidence: Executed the committed SQL twice through a real MySQL connection, changing only the resource directory. Counts were [2,2,6] on run 1 and [8,8,12] on run 2; teardown left three and six CSV files respectively. Retained review_stage_test.go, stage-replay.log, and checks/1792042715819431226-2.json reproduce the failure. This is a fixture defect, not production writer corruption.

Validation:

  • Isolation preflight passed. Verified 192 native source inputs and 46 artifact hashes against this candidate before testing.

  • Four focused frontend metadata/migration tests passed. Runtime/compiler checks passed across five packages: 30 root tests and 197 named pass records.

  • Independent equijoins with 100 and 200 input rows each used one hash join and zero pair callbacks across two generations.

  • Public SQL probe: 16 subtests passed; one exploratory case hit the unchanged table-function argument restriction. Its overall exit was 1 and is not counted as an all-pass run.

  • Protobuf descriptor audit preserved existing fields/options. Frozen exact-head CI records successful build, Ubuntu UT, arm64 SCA, coverage, Connector/J reset, Proxy BVT, and multi-CN pessimistic BVT.

  • Final audit passed: clean source, matching frozen delta, and reconciled command/source/exit receipts and logs. Detailed report and evidence-audit.json are retained under /home/xupeng/.local/state/mo-bot/jobs/6dbab816f9bab142b6a18638/attempt-1.

Limitations:

  • Full CI, race, and multi-CN suites were not repeated locally; raw CI logs and author execution receipts were not supplied.

  • No fresh cluster-throughput comparison was performed. General-path E×I work and coordinator placement remain accepted design costs; author microbenchmarks are documented separately from local measurements.

  • The replay used the committed SQL through an embedded CN, not the mo-tester harness.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

Review in progress.

@XuPeng-SH

XuPeng-SH commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d0eab9e6989d60221f4063b5d3409082c49ee6cd

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: d0eab9e6989d60221f4063b5d3409082c49ee6cd

Assessment: approve

Reviewed the complete 192-file delta and surrounding owners/callers. Typed captures and demand-driven continuations preserve lexical ownership while reusing native relational operators and statement resources. The added state is justified by suspension and cleanup requirements. Previous join-performance, DML ownership, prepared-metadata and stage-cleanup findings are closed on this commit; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Retained report and evidence: /home/xupeng/.local/state/mo-bot/jobs/3bc10d833999c3a29da65112/attempt-1/review-report.json and validation-audit.json. Commands, source fingerprints, exit receipts and log hashes were reconciled. Final proof receipt: checks/1792062106258331607-2.json.

  • Frozen head remained clean; diff --check passed and supplied patch lines matched the base-to-head diff. Isolation preflight passed. Repository-owned native build verified 192 input hashes and 56 artifact hashes.

  • Focused tests passed across eight packages: 41 root tests, 247 tests including subtests, no failures or skips.

  • Race checks passed across six packages: 202 tests including subtests repeated five times, yielding 1,010 passing test events without race warnings, failures or skips.

  • Embedded MySQL probes passed 17 subtests covering relational results, prepared metadata, transaction visibility, rollback and connection reuse. The committed stage case executed twice with counts [2,2,6] and zero remaining files after each teardown.

  • Independent equijoin work checks at 100 and 200 rows, across two generations each, produced one hash join and zero pair-kernel calls.

  • Protobuf audits verified additive schema changes, preservation of existing fields/options, and 265 message plus 42 enum descriptor indexes/registrations.

  • Supplied current-head CI reports successful build, Ubuntu UT, arm64 static analysis, coverage, Connector/J reset, proxy BVT and pessimistic multi-CN BVT. Skipped jobs were excluded from pass claims.

Limitations:

  • Coordinator-only execution, E×I general-path work and no cross-row result cache remain explicit accepted design limits.

  • No fresh cluster-throughput comparison was performed. Earlier author microbenchmarks report an 8.9% one-level scalar planning increase; these are not independent current-head measurements. Local work counters establish closure of the concrete join regression, not zero regression across all workloads.

  • Local checks did not repeat mixed-version cluster migration or use a live external Iceberg service. Adapter/native failure tests, source review and supplied CI evidence have the narrower scopes documented in the report.

  • The linked issue body and detailed CI logs were not supplied; review used the available PR, approved design and regression contracts. The PR description's protocol 112 is stale; current implementation correctly gates on 114.

@mergify

mergify Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-18 03:02 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-10-18 04:05 UTC · at c60ac0703cbc6cfbdb03980d65aa1bd98db5e71b

This pull request spent 1 hour 2 minutes 40 seconds in the queue, with no time running CI.

Reason

The merge conditions cannot be satisfied due to failing checks

  • CI Required

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Requeued — the merge queue status continues in this comment ↓.

ck89119 and others added 6 commits October 18, 2026 20:08
Release account-bound output, key evaluators and metadata before EXECUTE account retirement while preserving unaccounted buffer reuse. Use typed internal errors for correlation validation and satisfy err-check. Add account-generation, failure, idempotent cleanup and prepared set-operation regressions.
@XuPeng-SH

Copy link
Copy Markdown
Contributor

本轮维护更新:rebase 到 main 799523418e9f941afd65cd440d24e7fa0003a35e,新提交 2d241a55c798f96a98fa1072175368c8841fbb4f。

rebase 并保留历史合并决议:最终 tree 与原 PR 加当前 main 的独立三方合并结果完全一致,避免丢失已有的 43 个文件变更。原 CI 的角色刷新清理阶段连接错误未做产品归因;本次是维护交付审查,不是重新批准完整功能。

本地验证:受影响路径的普通 UT、单轮 race 和完整变更 Go 包范围的增量 SCA 均通过。自定义 molint 仍输出原有 unsafe/recover 诊断,命令通过不代表这些提示已清零;本轮没有扩展成对完整相关子查询功能的重新批准。未运行整套 CI/BVT、GPU 或性能负载;不将历史作者记录标作本轮新运行。

变更保留检查覆盖完整原 PR 与 main 的集成结果;仅保留本轮明确说明的维护增量。新提交的 GitHub CI 结果待运行,原 CI 中未定位或未归因的失败仍需单独跟踪。

@mergify

mergify Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-18 14:06 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-10-18 14:36 UTC · at 2d241a55c798f96a98fa1072175368c8841fbb4f

This pull request spent 29 minutes 43 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated

GitHub response: refusing to allow a GitHub App to create or update workflow .github/workflows/iceberg-connector.yml without workflows permission
GitHub only lets Mergify write to .github/workflows/ with the workflows permission. An organization owner can accept Mergify's pending permissions at https://dashboard.mergify.com/orgs/matrixorigin/repositories.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-18 15:54 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-18 17:10 UTC · at 94760aa93223924df314c12d7079323f2e89c2b1 · squash

This pull request spent 1 hour 16 minutes 15 seconds in the queue, including 53 minutes 35 seconds running CI.

Required conditions to merge

This branch was previously deployed

1 inactive deployment
ci — 885a2796 Deployed Oct 18, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/api-change kind/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Support correlated subquery with multi levels

5 participants