Skip to content

Fix server crash on correlated subquery in ALIAS column expression - #100753

Merged
alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:fix/correlated-subquery-alias-crash
May 18, 2026
Merged

alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:fix/correlated-subquery-alias-crash

Conversation

@groeneai

@groeneai groeneai commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator

ColumnsDescription validation rejects subqueries in column default expressions,
but the check only inspected direct children of the expression AST. A correlated
subquery nested inside function arguments — e.g.
ALIAS toString(intDivOrZero(x, (SELECT max(number) FROM system.numbers WHERE number = x)))
— passed validation and reached the planner. When the planner encountered the
correlated subtree inside CollectTableExpressionData, it threw LOGICAL_ERROR,
which in debug builds calls abort and kills the server.

Per the review on the earlier (planner-side) version of this fix, the validation
is now made deep at the source. hasSubqueryInTree recursively walks the
default expression AST and rejects any ASTSubquery / ASTSelectQuery /
ASTSelectWithUnionQuery node at any depth during CREATE / ALTER TABLE.
This runs in validateColumnsDefaultsAndGetSampleBlockImpl before the
allow_experimental_analyzer branch, so the behavior is identical under both
analyzers.

This is a behavior change beyond just turning a LOGICAL_ERROR into an
exception:

  • Previously, nested non-correlated subqueries inside function arguments
    (e.g. ALIAS x + (SELECT 1)) passed DDL validation and worked at read time.
  • They are now rejected at DDL time with THERE_IS_NO_DEFAULT_VALUE, matching
    the existing treatment of top-level subqueries (DEFAULT (SELECT 1)) and the
    correlated-subquery case that previously crashed.

The planner-side NOT_IMPLEMENTED path is kept as a safety net for any
pre-existing schema that bypassed the older shallow check.

Found by the AST fuzzer (STID: 0250-3bee), recurring across 3+ unrelated PRs
over 30 days.

Changelog category (leave one):

  • Backward Incompatible Change

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

Fix server crash when reading from a table whose ALIAS column contained a correlated subquery nested inside a function call (e.g. ALIAS toString(intDivOrZero(x, (SELECT ...)))). CREATE TABLE and ALTER TABLE now reject any subquery at any depth in DEFAULT / ALIAS / MATERIALIZED column expressions with THERE_IS_NO_DEFAULT_VALUE. Previously, the shallow validation accepted nested subqueries, so the correlated case crashed at read time and the nested non-correlated case appeared to work but could lead to unexpected behavior; both are now rejected at DDL time.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.738

groeneai and others added 2 commits March 25, 2026 21:14
ClickHouse validates column default expressions by checking only
direct children for subquery nodes, missing nested correlated
subqueries inside function arguments. This allows creating ALIAS
columns like:

  ALTER TABLE t ADD COLUMN s ALIAS toString(intDivOrZero(x,
    (SELECT max(number) FROM system.numbers WHERE number = x)))

When a query later reads such a column, the planner encounters
the correlated subquery and throws LOGICAL_ERROR, which in debug
builds calls abort() — killing the server.

The fix changes the error from LOGICAL_ERROR to NOT_IMPLEMENTED,
so the server returns a user-facing error instead of crashing.

Closes STID: 0250-3bee

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate

a) Deterministic repro? Yes. The following reproduces the crash deterministically:

CREATE TABLE t_alias_correlated (x Int64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_alias_correlated SELECT * FROM system.numbers LIMIT 10;
ALTER TABLE t_alias_correlated ADD COLUMN s Decimal(2,0) ALIAS toString(intDivOrZero(x, (SELECT max(number) FROM system.numbers WHERE number = x LIMIT 1)));
SELECT arraySort(groupArray(x)), arraySort(groupArray(s)) FROM t_alias_correlated; -- crashes without fix

b) Root cause explained? ColumnsDescription.cpp validation checks only direct children for subqueries, missing nested correlated subqueries inside function arguments. The ALTER TABLE ADD COLUMN succeeds, but when the planner processes the ALIAS expression in CollectTableExpressionData.cpp, PlannerActionsVisitor::visit() detects correlated subtrees and hits a LOGICAL_ERROR assertion — which calls abort() in debug builds.

c) Fix matches root cause? Yes — changes the error from LOGICAL_ERROR (abort) to NOT_IMPLEMENTED (user-facing error). The assertion assumed validation was exhaustive; since it isn't, this is a reachable state that should be handled gracefully.

d) Test intent preserved? N/A (new test). The test verifies: correlated subquery in ALIAS returns NOT_IMPLEMENTED error, and non-correlated scalar subquery in ALIAS still works.

e) Both directions demonstrated? Yes — without the fix, the SELECT crashes the server. With the fix, it returns NOT_IMPLEMENTED error. Confirmed locally.

Session: cron:clickhouse-ci-task-worker:20260325-205529

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [249d662]

Summary: ✅


AI Review

Summary

This PR moves the fix to the root cause by making subquery detection in column default expressions recursive, so nested subqueries in DEFAULT / ALIAS / MATERIALIZED expressions are rejected at DDL time, and keeps a planner-side NOT_IMPLEMENTED guard for legacy metadata paths. I re-checked the current diff and prior discussion threads against the latest code and did not find unresolved correctness, safety, or performance issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Mar 25, 2026
@pufit pufit added pr-bugfix Pull request with bugfix, not backported by default and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Mar 26, 2026
groeneai and others added 2 commits March 26, 2026 01:56
The old analyzer resolves ALIAS column references at DDL time,
producing UNKNOWN_IDENTIFIER (Code 47) instead of the new
analyzer's NOT_IMPLEMENTED path tested here. Skip the test
under old analyzer mode.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The old analyzer resolves ALIAS column references at DDL time,
producing UNKNOWN_IDENTIFIER (Code 47) instead of the new
analyzer's NOT_IMPLEMENTED path tested here. Skip the test
under old analyzer mode.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai
groeneai force-pushed the fix/correlated-subquery-alias-crash branch from f6ba9b8 to a703723 Compare March 26, 2026 05:20
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @KochetovNicolai — could you review this? It fixes a server crash when a correlated subquery appears in an ALIAS column expression (CollectTableExpressionData).

throw Exception(ErrorCodes::LOGICAL_ERROR,
"Expected single output in actions dag for alias column {}. Actual {}", column_node->dumpTree(), outputs.size());
/// ColumnsDescription validation (ColumnsDescription.cpp) rejects top-level
/// subqueries in ALIAS expressions, but the check is shallow — it only inspects

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai, Why don't you make that check deep to fix the root cause?

@alexey-milovidov alexey-milovidov self-assigned this Apr 7, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Can't adjust last granule error in CI is a known issue. The fix is in #101641

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai look at the review comments.

Address review feedback: make the subquery validation in
ColumnsDescription recursive so that subqueries nested inside function
arguments (e.g. `ALIAS toString((SELECT ...))`) are rejected during
CREATE/ALTER TABLE rather than persisting invalid schema and crashing
later at query time.

Previously, the check only inspected direct children of the default
expression AST, so a subquery wrapped in a function call would slip
through validation. The planner would then hit a LOGICAL_ERROR
assertion on correlated subqueries.

Changes:
- Add `hasSubqueryInTree()` recursive helper in ColumnsDescription.cpp
- Replace the shallow type-check with the recursive walk
- Keep the planner-level NOT_IMPLEMENTED as a safety net for tables
  created before this validation was added
- Update regression test to verify DDL-time rejection
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in b97e4ea.

The subquery check in ColumnsDescription::validateColumnsDefaultsAndGetSampleBlockImpl was only inspecting direct children of the default expression list. A subquery nested inside function arguments (e.g. ALIAS toString(intDivOrZero(x, (SELECT ...)))) would slip through.

Fix: Added a hasSubqueryInTree() recursive walker that finds ASTSubquery/ASTSelectQuery/ASTSelectWithUnionQuery nodes at any depth. Now both CREATE TABLE and ALTER TABLE ADD COLUMN reject subqueries in DEFAULT/ALIAS/MATERIALIZED expressions at DDL time, regardless of nesting.

The planner-level NOT_IMPLEMENTED safety net is kept for backward compatibility — tables created before this validation was added could still have subqueries in their persisted metadata.

Verified locally: 50/50 test runs pass with full randomization.

Validation in validateColumnsDefaultsAndGetSampleBlockImpl now rejects
subqueries (via hasSubqueryInTree) before branching on
allow_experimental_analyzer, so the test exercises the same code path on
both analyzers and does not need the no-old-analyzer tag.

Addresses clickhouse-gh[bot] review on PR ClickHouse#100753.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the follow-up review. Addressed both comments:

PR description / changelog mismatch (line 18):
Updated the PR description and the changelog entry to spell out the
stricter contract — CREATE TABLE / ALTER TABLE now reject any
subquery at any depth in DEFAULT / ALIAS / MATERIALIZED column
expressions with THERE_IS_NO_DEFAULT_VALUE. Previously only the
correlated case crashed at read time; the nested non-correlated case
silently worked. The new behavior is fail-fast at DDL time for both.

no-old-analyzer tag (line 1):
Dropped the tag in b50bc57 — the rejection now happens in
validateColumnsDefaultsAndGetSampleBlockImpl before the
allow_experimental_analyzer branch, so the test exercises the same
DDL validation path on both analyzers. The no-replicated-database
tag is kept because the test reuses a fixed table name.

cc @alexey-milovidov

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@clickhouse-gh

clickhouse-gh Bot commented May 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.10% -0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 80.00% (16/20) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 17, 2026
Merged via the queue into ClickHouse:master with commit 391cd40 May 18, 2026
167 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: validateColumnsDefaultsAndGetSampleBlockImpl in ColumnsDescription.cpp and CollectSourceColumnsVisitor::enterImpl in CollectTableExpressionData.cpp — core code present in all supported branches.

Why this might apply: This PR fixes a crash (LOGICAL_ERROR exception which calls abort() in debug builds) when reading from tables with correlated subqueries in ALIAS columns. The affected code path in validateColumnsDefaultsAndGetSampleBlockImpl and CollectTableExpressionData has existed since before all supported branches. The crash can be triggered by valid DDL followed by a SELECT, making it a user-facing crash that should be backported.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 18, 2026
@alexbakharew alexbakharew added the pr-backward-incompatible Pull request with backwards incompatible changes label Jun 3, 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 pr-backward-incompatible Pull request with backwards incompatible changes pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants