Skip to content

Fix LOGICAL_ERROR on INSERT into a table whose projection has a subquery in its SELECT list or GROUP BY - #130143

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-projection-calculation-subquery-names
Nov 8, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-projection-calculation-subquery-names

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118375
Related: #129863

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 INSERT, MATERIALIZE PROJECTION and merges failing with LOGICAL_ERROR Projection ... calculated the columns ... while its metadata describes the columns ... for a table with a projection that has a subquery (x IN (SELECT ...), EXISTS (SELECT ...)) in its SELECT list or GROUP BY and a WHERE clause or aggregation.

Description

On 26.10.2.103, INSERT INTO t VALUES (1, 1) into t (a UInt32, b UInt32, PROJECTION p (SELECT b IN (SELECT b FROM src), a, b WHERE a > 0 ORDER BY b)) fails with Code: 49 ... Projection p calculated the columns in(b, __subquery_X), a, b while its metadata describes the columns a, b, in(b, __subquery_Y). Found by the AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=129764&sha=7327e93b8ee576277e7ba9a36190e846b366ddac&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

A subquery is named by the hash of its AST. The projection metadata is named from the stored query AST, while calculateByQuery (since #118375) names the calculated columns by converting the query tree back to AST, which does not reproduce the subquery (for example it adds FROM system.one), so the hash differs. It affects IN, GLOBAL IN, NOT IN, EXISTS, nested and aggregate arguments, and GROUP BY keys, whenever the projection is calculated by a query (WHERE or aggregation).

The change: collectUnresolvedNodeNames takes the name of a function from the AST it was built from, which is the AST the metadata was named from, and keeps toAST as the fallback. calculateByQuery also pins rewrite_in_to_join = 0, because that rewrite replaces the IN node and its name would be lost again.

Validation: the new test fails on master in every arm (normal projection with WHERE across DETACH/ATTACH, the fuzzer's GLOBAL IN with GLOBAL JOIN, aggregate projection, MATERIALIZE PROJECTION, INSERT under rewrite_in_to_join) and passes with the fix; 50 randomized runs pass; all 356 stateless tests matching projection pass.

Not changed: these column names embed an AST hash that differs between versions, so a part written by another version lacks such a column; no reader of it was observed.


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

Version info

  • Merged into: 26.11.1.1676-master (included in 26.11 and later)
  • Backported to: 26.10.11.5

… name

A subquery is named by the hash of its AST (`__subquery_<hash>`). The
projection metadata is named from the stored projection query, analysed in
place, while `calculateByQuery` (since ClickHouse#118375) renames the columns of the
Analyzer pipeline to names built by converting the query tree back to AST.
That conversion does not reproduce the subquery (a subquery without `FROM`
gets `FROM system.one`, other shapes hash differently too), so a projection
column like `b IN (SELECT ...)` was calculated as `in(b, __subquery_X)` while
the metadata describes `in(b, __subquery_Y)`, and every INSERT,
MATERIALIZE PROJECTION or merge rebuilding a projection with `WHERE` or an
aggregate projection failed with LOGICAL_ERROR (found by the AST fuzzer on
the `05515_global_subquery_projection_where` seed). On 26.9 the same INSERT
silently stored 0 in such a column.

The unresolved names of the functions are now taken from the AST each query
tree node was built from, which is the very AST the metadata was named from;
`toAST` stays the fallback for a node without one (the `tuple` wrapper added
around a tuple `GROUP BY` key).

The names are keyed by node, so a resolution that replaces the `IN` node loses
them: `rewrite_in_to_join` does, so `calculateByQuery` pins it to 0 next to the
other settings it pins. Creating the table under `rewrite_in_to_join = 1`
gives the same metadata names (they come from `InterpreterSelectQuery`, which
does not read it), so `fillProjectionDescriptionByQuery` needs no pin.

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

groeneai commented Nov 8, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review of the diff (0 blockers, 0 majors).

# Sev Finding Verdict Evidence / action
- - No findings - -

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-11:20261108-124600

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local: CREATE TABLE t (a UInt32, b UInt32, PROJECTION p (SELECT b IN (SELECT b FROM src), a, b WHERE a > 0 ORDER BY b)) ENGINE = MergeTree ORDER BY a; INSERT INTO t VALUES (1, 1), (7, 7) aborts on every run of a master debug build; Code: 49 LOGICAL_ERROR on the official 26.10.2.103.
b Root cause explained? Yes. A subquery is named by the hash of its AST. The metadata is named from the stored query AST; calculateByQuery names the calculated columns via toAST of the query tree, which does not reproduce the subquery AST, so the names differ and the completeness check throws.
c Fix matches root cause? Yes. The calculation takes each function's name from the AST it was built from, the same AST the metadata was named from. The check and the stored names are unchanged.
d Test intent preserved / new tests added? New SQL test 05569_projection_calculation_subquery_names, 5 arms; every arm fails on master on its own.
e Both directions demonstrated? Yes. Each arm alone: master aborts in calculateByQuery, the fix returns hand-checked values; the whole test via clickhouse-test: master server aborts, fix [ OK ]. Without the rewrite_in_to_join pin the arm using it still aborts.
f Fix is general across code paths? Yes. One function serves INSERT, MATERIALIZE PROJECTION, merge rebuilds and the lightweight-delete rebuild, all measured. The metadata side is intentionally unchanged (its names are the on-disk names).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Measured Nullable, LowCardinality, DateTime64, tuple IN, NOT IN, GLOBAL IN with GLOBAL JOIN, UNION ALL, aliases, a lambda, an empty set, EXISTS, aggregate arguments, a tuple GROUP BY key; 50 randomized runs pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; the stored column names are unchanged.
i Invariants and contracts preserved? Every column calculateByQuery returns carries the name the metadata gives it. The resolved-node candidate and the candidate selection are unchanged; only the unresolved-node candidate now comes from the source AST. All 356 stateless tests matching projection pass, including the renamed-aggregate cases that candidate was added for.

Session id: cron:clickhouse-impl-slot-4:20261108-121000

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [09d9bc4]

Summary: ✅


AI Review

Summary

Reviewed PR #130143 at 09d9bc43ab7cf81bb404262fa339affd834fba80. The change preserves metadata-defined projection column names for expressions containing subqueries and disables rewrite_in_to_join during projection calculation. No actionable findings.

The new subquery regression test and two existing aggregate naming regression tests passed locally using the PR's ARM Fast test binary; all outputs matched their references. The full CI workflow remains in progress.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 8, 2026
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @KochetovNicolai, could you review this and add the can be tested label so CI runs? calculateByQuery named a projection column containing a subquery via toAST of the query tree, which does not reproduce the subquery AST, so its __subquery_<hash> name differed from the metadata and the completeness check threw LOGICAL_ERROR on every INSERT; it now takes the name from the AST the node was built from.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). labels Nov 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 09d9bc43a with master 7b5f2bf32 (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

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 8, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 8, 2026
Merged via the queue into ClickHouse:master with commit fa0eb19 Nov 8, 2026
373 of 375 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 19, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 22, 2026
The only conflict is in `ProjectionDescription::calculateByQuery`: master
also has the `enable_parallel_replicas` line of #129863 and the positional
arguments change of #126185 there, neither of which is on 26.10. Keep the
26.10 code and add only the `rewrite_in_to_join` line of #130143.

Also take the three lines of #129006 that materialize constant columns of
the calculated projection block. On 26.10 a projection column such as
`exists(SELECT ...)` is calculated as a `ColumnConst`, and once #130143
gives it the right name, writing the projection part fails with
`Bad cast from type DB::ColumnConst to DB::ColumnVector<char8_t>`
(the `t_subquery_normal` case of 05569). The rest of #129006 is not needed
on 26.10: its trigger, `optimize_constant_columns_after_filter`, does not
exist there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll2 added a commit that referenced this pull request Nov 22, 2026
Cherry pick #130143 to 26.10: Fix `LOGICAL_ERROR` on `INSERT` into a table whose projection has a subquery in its `SELECT` list or `GROUP BY`
robot-clickhouse added a commit that referenced this pull request Nov 22, 2026
…le whose projection has a subquery in its `SELECT` list or `GROUP BY`
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 22, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 22, 2026
Backport #130143 to 26.10: Fix `LOGICAL_ERROR` on `INSERT` into a table whose projection has a subquery in its `SELECT` list or `GROUP BY`
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-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). 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.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants