Skip to content

Fix use-after-free in a correlated subquery over a Merge table inside EXPLAIN or a subquery - #122475

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-correlated-subquery-merge-planner-context-uaf
Sep 27, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-correlated-subquery-merge-planner-context-uaf

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115238 (comment)
Related: #119561

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a heap-use-after-free when a correlated subquery reading a Merge table was planned inside EXPLAIN, a subquery in FROM, a view or an IN subquery.

Description

On 26.9 (v26.9.3.38-stable), a correlated subquery over a Merge table reads freed planner memory (heap-use-after-free) when it is planned inside EXPLAIN, a subquery in FROM, a view or an IN subquery, and a non-empty source table of the Merge table lacks a column the subquery reads.

Found by AST fuzzer (arm_asan_ubsan) on #115238, STID 4877-28b1: https://github.com/ClickHouse/ClickHouse/actions/runs/35807917921/job/107176161332 (report).

A correlated subquery is planned with its own GlobalPlannerContext, which stores raw pointers to the enclosing query's TableExpressionData but does not own the enclosing PlannerContext. ReadFromMerge plans its source tables lazily, during QueryPlan::optimize or pipeline building, and for a source table narrower than the Merge header the fan-out added in #119561 resolves the correlated column through those pointers. EXPLAIN, a FROM subquery, a view and an IN subquery destroy the enclosing Planner before that point, so the pointers dangle.

The fix makes GlobalPlannerContext hold a PlannerContextPtr to each context it points into. Those pointers are written in one place, so this one change covers every reader and every path that drops the enclosing planner early. There is no reference cycle: the subquery's plan goes into the enclosing QueryPlan, never into the enclosing PlannerContext, and LeakSanitizer reports nothing at exit.

Each of the six queries in the new test aborts an unfixed ASan build on its own and passes with the fix, including 50 randomized runs, the parallel replicas settings and a Replicated database.


Workflow [PR]
Sync PR [sync-upstream/pr/122475]

Version info

  • Merged into: 26.10.1.792-master (included in 26.10 and later)
  • Backported to: 26.9.4.3

groeneai and others added 2 commits September 26, 2026 18:57
… EXPLAIN or a subquery

A correlated subquery is planned with its own `GlobalPlannerContext`, and
`collectTableExpressionDataForCorrelatedColumns` stores raw pointers to the
enclosing query's `TableExpressionData` in it, without keeping the enclosing
`PlannerContext` alive. Every context derived from the subquery falls back to
that map when it looks up the correlated column's source.

`ReadFromMerge` plans its source tables lazily (from `applyFilters` during
`QueryPlan::optimize`, or from `initializePipeline`). For a non-empty source
table narrower than the `Merge` header, `convertAndFilterSourceStream` builds
the fan-out added in ClickHouse#119561 and names the correlated column through that map.
`EXPLAIN`, a subquery in `FROM`, a view and an `IN` subquery destroy the
enclosing `Planner` before that point, so the lookup reads freed memory
(AST fuzzer, arm_asan_ubsan, STID 4877-28b1).

`GlobalPlannerContext` now holds a `PlannerContextPtr` to every planner context
whose data it points into. It is the only writer of the map, so this covers all
readers and every place that drops the enclosing planner early, without
changing each of them. No reference cycle: the subquery's plan is united into
the enclosing `QueryPlan`, never stored in the enclosing `PlannerContext`
(correlated subqueries are neither `IN` set sources nor materialized CTEs).

Related: ClickHouse#115238 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A view is planned by its own interpreter in `StorageView::readImpl`, which
destroys the enclosing `Planner` before `ReadFromMerge` plans its source
tables, like `EXPLAIN` and the `FROM` and `IN` subqueries the test already
covers.

CI report of the heap-use-after-free fixed in the previous commit:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115238&sha=28023e4bdf69d407d579274765a2573ac6baa9db&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
https://github.com/ClickHouse/ClickHouse/actions/runs/35807917921/job/107176161332

Related: ClickHouse#115238 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding in round 1, none in round 2 on the final head) and my own cold review in both rounds.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test had no view case, although the changelog entry names views (05258_correlated_subquery_over_merge_nested_planning.sql) AGREE, fixed @ 526b0ee Added a view case. It aborts an unfixed ASan build with the view's own interpreter in the free stack, and it passes with the fix.
2 💡 Commit text: SQL names without inline code, CI report URL missing AGREE, fixed @ 526b0ee The follow-up commit carries the report and job URLs. The PR title uses inline code.
3 💡 The test prefix 05258 is now also used by a test merged to master after this branch was cut AGREE, not changed CI tolerates shared prefixes. I can renumber it if you prefer.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260926-204900

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [526b0ee]

Summary: ✅


AI Review

Summary

This PR fixes the correlated-subquery lifetime bug by making the subquery GlobalPlannerContext retain the enclosing PlannerContext whose TableExpressionData pointers it reuses later during lazy Merge planning, and it adds a focused stateless regression test covering the reported nested-planning surfaces (EXPLAIN, FROM, scalar subquery, IN, and view). I did not find an unresolved correctness issue or a missing test that would justify requesting changes on the current head.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 526b0ee.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 526b0ee2c with master dd5abe7e9 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

52 translation units recompiled, 460 s compile time in total, 52 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into ClickHouse:master with commit 72ae68a Sep 27, 2026
172 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 27, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 27, 2026
… over a `Merge` table inside `EXPLAIN` or a subquery
clickhouse-gh Bot added a commit that referenced this pull request Sep 27, 2026
Backport #122475 to 26.9: Fix use-after-free in a correlated subquery over a `Merge` table inside `EXPLAIN` or a subquery
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.9-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants