Skip to content

Register prepared sets before expanding ALIAS columns of Merge child tables - #113757

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-alias-in-prepared-set
Aug 7, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-alias-in-prepared-set

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #113712

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):

Fix Logical error: No set is registered for key ... when reading through a Merge table whose child declares an ALIAS column containing IN, and the children disagree about that column's default.

Description

Reproducer, which aborts the server on master:

CREATE TABLE t1 (x UInt8) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE t2 (y UInt8, x UInt8 ALIAS y IN (1, 2, 3)) ENGINE = MergeTree ORDER BY tuple();
SELECT * FROM merge(currentDatabase(), '.+');

getColumnsDescriptionFromSourceTablesImpl clears a column's default when children disagree about it, so the Merge-level x looks physical and is requested from every child. t2 still declares it as ALIAS, so ReadFromMerge::getModifiedQueryInfo expands it and builds actions with a PlannerActionsVisitor. That visitor resolves IN through PlannerContext::getPreparedSets, but its context was derived a few lines earlier and the deriving constructor does not copy prepared_sets, so the registry is empty and the lookup misses. Since LOGICAL_ERROR aborts at throw time under a sanitizer, the call has to be avoided rather than guarded.

The fix calls collectSets before building the actions, as two existing sites already do here: Planner/Utils.cpp for row policies, and CollectTableExpressionData.cpp for the same ALIAS expansion pattern. It is idempotent. The reachable right-hand sides here are a constant tuple and a Set table, and both now resolve; the Set table reaches the same lookup through a different branch. A subquery is rejected at DDL time, and a plain table already fails identically without a Merge table, so it is untouched.

convertAndFilterSourceStream needs the same call, being reached when a child hits the query info cache, which skips getModifiedQueryInfo and builds another empty context. The issue's LIMIT -326, 33 FORMAT ORC is incidental; a plain SELECT * aborts.

Validation: the new test fails on master and passes with the fix, through clickhouse-test, 100/100 runs (50 randomized, 50 with randomization off). Reverting either call reddens only the cases reaching that site. A 437-test slice over merge() and ALIAS columns has an identical failure set on both arms.

Version info

  • Merged into: 26.8.1.951 (included in 26.8 and later)
  • Backported to: 26.7.5.7, 26.6.4.6, 26.5.8.8

…tables

Reading through a `Merge` table aborted the server with
`Logical error: No set is registered for key __set_...` when a child table
declared an `ALIAS` column whose expression contains `IN`, and the children
disagreed about that column's default.

`StorageMerge::getColumnsDescriptionFromSourceTablesImpl` clears the default on
such a disagreement, so the Merge-level column looks physical and is requested
from every child. The child still declares it as `ALIAS`, so
`ReadFromMerge::getModifiedQueryInfo` expands it and builds actions for the
expression with a `PlannerActionsVisitor`. That visitor resolves `IN` through
`PlannerContext::getPreparedSets`, but the context it is given was derived a few
lines earlier and its constructor copies only `query_context`,
`global_planner_context` and `is_ast_level_optimization_allowed`. `prepared_sets`
is a member of the derived context, so the registry is empty and the lookup
misses. In a debug or sanitizer build `Exception::handleErrorCode` aborts at
throw time, so the call has to be avoided rather than guarded.

`collectSets` is what registers those sets, and two existing call sites do
exactly this before visiting: `Planner/Utils.cpp` for row policies and
additional table filters, and `CollectTableExpressionData.cpp` for the same
ALIAS expansion pattern, whose header comment states the rule. Call it before
both visitor sites in `StorageMerge.cpp`. It is idempotent, so registering a set
that is already present is a no-op.

The second site, `convertAndFilterSourceStream`, is reached when a child table
hits the query info cache: that path skips `getModifiedQueryInfo` entirely,
restores the aliases from the cache and builds another empty planner context.
Reverting only that call makes the new test's `query info cache` case abort in
`convertAndFilterSourceStream`, while the other cases stay green.

Two right-hand sides are reachable through a `Merge` table here and both are
covered: a constant tuple, and a `Set` table whose registry key carries no
element types, which is why a constant-tuple-only fix would be incomplete. A
subquery cannot occur, because an `ALIAS` expression containing one is rejected
at DDL time with `Code: 116`. A bare table identifier registers a set that
nothing outside a SELECT pipeline fills, and it already aborts the same way
without any `Merge` table, so it is left alone.

Closes ClickHouse#113712
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two independent review passes over this change: a cold read of the resulting code, and a separate
model pass that does not see the first. Findings below with the verdict I reached on each. After
those fixes, a final pass over the whole change returned nothing, having also run the regression
itself.

Finding Verdict
⚠️ The nullable case asserted assumeNotNull(x), and one of the three pinned array elements is assumeNotNull(NULL), which the function is documented to leave unspecified. Agreed, fixed. Replaced with a specified expression, keeping the null-count assertion that is what actually pins the behaviour.
💡 The two new comments wrote the class name PlannerActionsVisitor and the SQL construct IN without inline code formatting. Agreed, fixed.
💡 Saying collectSets "covers constant tuples, Set tables and subqueries" is true of the function but reads as a claim about what is reachable here. Agreed, corrected in the body and the commit message. The reachable right-hand sides are a constant tuple and a Set table.
❌ An ALIAS whose IN right-hand side is a plain table still reaches Not-ready Set is passed as the second argument, so the change is incomplete. Disagreed on ownership, with a measurement. That shape aborts identically on unmodified master with no Merge table anywhere: reading the same ALIAS column directly gives the same message, and the stack contains no StorageMerge frame at all, being pure expression execution through Functions/in.cpp. Registering an unbuilt set for such an operand is existing behaviour of ALIAS-column expansion, which extractKeyExpressionList.cpp documents and handles by refusing the shape where it is reachable. This change only affects which error a merge() read reports first, and six control shapes that work on master still work here, so nothing regresses. Fixing it inside ReadFromMerge would add a second concern to this pull request and leave the direct read broken.

Test liveness was checked rather than assumed. Reverting either of the two calls reddens only the
cases that reach that site, and the second call is proven necessary rather than defensive: reverting
just it aborts the query info cache case alone. The test also pins the analyzer explicitly, because
without that the whole file passes on an unfixed server under the old-analyzer profile, which was
verified by running both arms.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation (a-i)

Every file:line below resolves against origin/master, verified mechanically.

Check Answer
a Deterministic repro? Yes. CREATE TABLE t1 (x UInt8) ENGINE = MergeTree ORDER BY tuple(); CREATE TABLE t2 (y UInt8, x UInt8 ALIAS y IN (1, 2, 3)) ENGINE = MergeTree ORDER BY tuple(); SELECT * FROM merge(currentDatabase(), '.+'); aborts every time. Scored on three conditions, never on the exit code alone: rc == 134, the message No set is registered for key, and a StorageMerge.cpp frame at the expanding site. Measured rc=134, message twice, frame twice, with the stack matching the reported one frame for frame down to optimizePrimaryKeyConditionAndLimit.cpp:83.
b Root cause explained? Yes. getColumnsDescriptionFromSourceTablesImpl clears the default when children disagree (StorageMerge.cpp:250), so the Merge-level column looks physical and is requested from every child. The child still declares it ALIAS (:1197), so getModifiedQueryInfo expands it and builds actions with a PlannerActionsVisitor over the context derived at :1142, whose constructor (PlannerContext.cpp:83-86) copies only query_context, global_planner_context and is_ast_level_optimization_allowed. prepared_sets is a member of the derived context, so the registry is empty and the lookup throws at PlannerActionsVisitor.cpp:1120.
c Fix matches the root cause? Yes: the sets are registered in that context before actions are built, so the lookup cannot miss. It is not a guard, which could not work anyway because Exception::handleErrorCode aborts at throw time in debug and sanitizer builds. Nothing is widened, no tag is added, no dataset is shrunk.
d Test intent preserved, new test added? New test 04812_merge_alias_in_prepared_set with 9 cases. 8 of them abort on master, attributed one by one by deleting the aborting case and re-running until the file completes: constant tuple, explicit column, with filter, set table, not in, tuple key, nullable, query info cache. The 9th is a control with identical children, which already passed before the fix and is what shows the discriminating condition is the disagreement between children. Its number was verified free with the repo's own check_gaps_in_tests_numbers, clean with the new file and correctly reporting a gap for an injected 99999 control.
e Demonstrated in both directions? Yes, through clickhouse-test with a server restart per arm and SELECT lower(buildId()) asserted against readelf -n before any verdict. Master: FAIL, server died. With the fix: OK. 50 randomized plus 50 non-randomized runs, 100 of 100 pass.
f General across code paths? The invariant is that a PlannerActionsVisitor visit over a freshly derived planner context must have its sets registered first. All 18 visitor construction sites across 10 files were enumerated (git grep -nE 'PlannerActionsVisitor [a-z_]+\(' -- src/, same count on origin/master): StorageMerge.cpp holds both of the sites that build over a fresh context, and before this change neither registered its sets. Every other site either calls collectSets or runs under the query's own context, already populated at Planner.cpp:2238; the site in PlannerActionsVisitor.cpp itself reuses the context it was handed, for indexHint arguments. Separately, make_shared<PlannerContext> appears at 9 places in src/; the 2 in StorageMerge.cpp are these sites, Planner.cpp is the query's own, and the remaining 6 all call collectSets already. The old-analyzer branches of both functions use TreeRewriter and never touch PreparedSets, so they are not carriers.
g Generalizes across inputs? 17 shapes measured, each aborting on master and returning the correct result with the fix: Nullable; LowCardinality(String); LowCardinality(Nullable(String)); Enum8; Array(UInt8); a two-column tuple key; a single-element set; NOT IN; GLOBAL IN; IN under a lambda; an alias over another alias; two INs in one expression; the same set used by both the query and the alias; an explicit column list; a WHERE filter; three disagreeing children; the Log engine. IN (SELECT ...) is unreachable: an ALIAS containing a subquery is rejected at DDL time with Code: 116, identically on both arms.
h Backward compatible? Yes. No setting, no default change, no serialization or protocol change, so no SettingsChangesHistory.cpp entry. The only behaviour change is that queries that aborted now return the correct result.
i Invariants and contracts preserved? collectSets takes the node by const reference and its visitor derives from ConstInDepthQueryTreeVisitor, so the node that is then visited is unchanged. It is idempotent: each of its three branches returns early when the key is already registered, which is what makes the LOGICAL_ERROR "Duplicate set" at PreparedSets.cpp:650 unreachable from here. Stressed with four children plus the same set registered by the query itself: 0 occurrences of Duplicate set and 0 of Not-ready Set. A 437-test slice covering merge(), StorageMerge and ALIAS columns was run on both arms: 92 failures on each, 0 only on one arm, 0 reason changes, identical reason buckets, and all of them environmental for this harness (missing clusters, no ZooKeeper, no macros).

Mutation matrix, each arm built and run with its Build ID asserted:

Mutant Result
revert the first call all 8 aborting cases abort again at getModifiedQueryInfo; the control stays green
revert the second call only the query info cache case aborts, in convertAndFilterSourceStream; the other 8 stay green
revert both all 8 non-control cases abort; the control stays green

The second mutant is what shows the second site is real rather than defensive. After the matrix the restored tree rebuilt to the shipping Build ID byte for byte.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @vdimir, could you review this? Reading through a Merge table hit Logical error: No set is registered for key when a child declares an ALIAS column containing IN and the children disagree about that column's default: the disagreement clears the Merge-level default so the column is requested from every child, and ReadFromMerge then builds actions for the alias over a freshly derived planner context whose prepared_sets is empty, so this calls collectSets first, as two existing sites already do.

@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e4dd39]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer-only prepared_sets gap in ReadFromMerge by registering sets before PlannerActionsVisitor expands ALIAS expressions, including the query-info-cache path in convertAndFilterSourceStream, and it adds focused stateless coverage for the previously aborting shapes. I did not find a correctness, compatibility, or coverage issue in the current head.

Final Verdict

✅ No blocking or major findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 11/11 (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 Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4e4dd39ab with master 31081d9f0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 16bd8e494; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.17 MiB 687.14 MiB -3.03 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 377d227 Aug 7, 2026
180 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 Aug 7, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 10, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@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 Aug 20, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 20, 2026
Backport #113757 to 26.7: Register prepared sets before expanding ALIAS columns of Merge child tables
PedroTadim added a commit that referenced this pull request Aug 20, 2026
Backport #113757 to 26.5: Register prepared sets before expanding ALIAS columns of Merge child tables
clickhouse-gh Bot added a commit that referenced this pull request Aug 20, 2026
Backport #113757 to 26.6: Register prepared sets before expanding ALIAS columns of Merge child tables
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…anding ALIAS columns of Merge child tables
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
…anding ALIAS columns of Merge child tables
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 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.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error "No set is registered for key" in ReadFromMerge::getModifiedQueryInfo for a merge() table with ALIAS columns

4 participants