Skip to content

Build the deferred set of a column default that contains IN <table> - #119664

Open
alexey-milovidov wants to merge 72 commits into
masterfrom
fix-117276-in-table-column-default
Open

alexey-milovidov wants to merge 72 commits into
masterfrom
fix-117276-in-table-column-default

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #117276
Related: #117272
Related: #117113

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 the Not-ready Set is passed as the second argument for function 'in' logical error for a column defined as ALIAS, DEFAULT or MATERIALIZED over a bare IN <table> membership test, such as flag UInt8 ALIAS p IN keys. Reading such a column, filtering by it, inserting into its table and mutating through it now compute the set instead of throwing, and a mutation referencing the column no longer wedges in a permanent retry loop.

Description

A column definition whose expression is a bare IN <table> membership test - flag UInt8 ALIAS p IN keys, or the same with DEFAULT / MATERIALIZED - is accepted at CREATE time, because a bare table identifier is not a subquery node and so passes validateColumnsDefaults, which rejects the explicit IN (SELECT ...) spelling. The set for the expanded in was registered in the prepared sets, but nothing ever built it, so every consumer of the definition threw at pure default settings.

Two places were missing the build:

  1. createComputeAliasColumnsStep assembles the Compute alias columns expression step from the DAG that CollectSourceColumnsVisitor produced when it expanded the column, but it never reported the sets that DAG carries. addBuildSubqueriesForSetsStepIfNeeded gives a CreatingSet step only to the sets reported as useful, so an ALIAS column's set was dropped from the plan and never built. Report them. The analysis-time half of the same gap was closed by aa6140a (Register sets of ALIAS expressions at expansion time), which stopped No set is registered for key; this is the build-time half. This covers SELECT flag FROM t, SELECT ... WHERE flag, and - less obviously - the mutation, whose isStorageTouchedByMutations runs a plain SELECT count() ... WHERE <predicate> over the part and hit the very same step; the direct spelling WHERE p IN keys builds no alias-column step and worked all along.

  2. createExpressionsAnalyzer in inplaceBlockConversions builds an ActionsDAG that is executed as a standalone ExpressionActions over a block. There is no query plan there, so no CreatingSet step can ever build the set. Build the deferred sets in place instead, with the new buildPreparedSetsInplace in Planner/Utils, which plans each set subquery like addBuildSubqueriesForSetsStepIfNeeded does and then fills it through FutureSetFromSubquery::buildSetInplace. This covers INSERT into a table with f UInt8 DEFAULT p IN keys or the MATERIALIZED variant, and reading a part in which such a column is missing.

    The call has to come after the actions are built, and buildPreparedSetsInplace says so: planning a set subquery assigns unique aliases to the table expressions it reads, and that table expression node is the very IN right-hand side whose tree hash the set is keyed by, so building first makes the later PlannerActionsVisitor lookup fail with No set is registered for key. The regular planner path observes the same order for the same reason.

A Merge table computes the ALIAS columns of each underlying table in that child's own plan (ReadFromMerge::convertAndFilterSourceStream), which had no CreatingSet step for their sets either. The sets of those expression steps are now registered in ReadFromMerge::alias_sets, shared by all children (a later child finds the set registered by an earlier one by its key), planned with planPreparedSetSubqueries (factored out of buildPreparedSetsInplace), and built once for the whole read in front of the united pipeline of the children in ReadFromMerge::initializePipeline. So, like the direct spelling p IN keys, the right-hand side is read once per query and every child sees the same snapshot of it.

A Set engine table on the right-hand side is a ready set rather than a deferred one and worked all along; the new test keeps that covered. An explicit subquery in a column default stays rejected at CREATE time.

A skip index cannot evaluate such a set either, so IN <table> that reaches a skip index through an ALIAS column is now rejected, as the direct spelling already was: an explicit index over such a column fails at CREATE time with BAD_ARGUMENTS, and no implicit min-max index (add_minmax_index_for_numeric_columns and similar) is created for it. Also, the in-place build for a part read with a missing DEFAULT runs with the storage's global context. It now gets an initiator version and has parallel replicas disabled, the same as the scalar subqueries of a standalone expression, so a set subquery that becomes distributed no longer throws Sending a distributed query with unknown (zero) client version.

A DEFAULT of a column missing in a part is evaluated on behalf of the reading query: with its user's privileges, row policies, query status and set/read limits. A background merge or mutation has no reading query, so such a default that reads a table throws ACCESS_DENIED there. It does not read the right-hand side with the storage's full access and store the result in the merged part.

Partition pruning: now that a mutation through such a column executes, ALTER ... DELETE WHERE <alias column> on a partitioned table must not have its block_numbers narrowed to the submission-time contents of the set, or rows in a partition that matches only the execution-time contents escape the mutation (#117113). This PR includes the guard of #117272: getPartitionIdsPrunedByPredicate follows an identifier into its ALIAS/EPHEMERAL definition and treats a bare table identifier on the right of IN as a deferred set, leaving such a mutation unpruned.

The rejection of a skip index over such an ALIAS column applies only to new definitions (CREATE, ALTER ADD INDEX, an ALTER that makes an existing index read a table). A definition accepted before this change, e.g. with a Set table on the right-hand side, still loads.

Tested locally against a release build: the four reproducers from the issue (SELECT ... WHERE flag, SELECT flag, INSERT with DEFAULT and with MATERIALIZED, and ALTER ... DELETE WHERE flag) all throw LOGICAL_ERROR on master and pass with this change; the new test passes five times in a row under randomized settings (including parallel replicas). No regressions in the 161 .sql tests that use ALIAS columns, nor in the set/subquery and column-default test groups, compared against a master binary on the same server configuration.


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

A column definition whose expression is a bare `IN <table>` membership test - `flag UInt8 ALIAS p
IN keys`, or the same with `DEFAULT` / `MATERIALIZED` - is accepted at CREATE time, because a bare
table identifier is not a subquery node and so passes the validation that rejects subqueries in
column defaults. The set for the expanded `in` was registered in the prepared sets, but nothing
ever built it, so at pure default settings every consumer of the definition threw `Not-ready Set
is passed as the second argument for function 'in'` (`LOGICAL_ERROR`), and a mutation referencing
the column was accepted and then wedged in a permanent retry loop.

Two places never built it:

- `createComputeAliasColumnsStep` assembles the `Compute alias columns` expression step from the
  actions `CollectSourceColumnsVisitor` produced when it expanded the column, but it never
  reported the sets those actions carry. `addBuildSubqueriesForSetsStepIfNeeded` gives a
  `CreatingSet` step only to the sets reported as useful, so the set of an `ALIAS` column was
  dropped from the plan. Report them. The analysis-time half of the same gap was closed by
  aa6140a (`Register sets of ALIAS expressions at expansion time`), which stopped `No set is
  registered for key`; this is the build-time half.

  This covers `SELECT flag FROM t` and `SELECT ... WHERE flag`, and - less obviously - the
  mutation: `isStorageTouchedByMutations` runs a plain `SELECT count() ... WHERE <predicate>` over
  the part, which expands the `ALIAS` column through the very same step. The direct spelling
  `WHERE p IN keys` builds no alias-column step, which is why it worked all along.

- `createExpressionsAnalyzer` in `inplaceBlockConversions` builds actions that are executed as a
  standalone `ExpressionActions` over a block. There is no query plan there, so no `CreatingSet`
  step can ever build the set. Build the deferred sets in place instead, with the new
  `buildPreparedSetsInplace`, which plans each set subquery the way
  `addBuildSubqueriesForSetsStepIfNeeded` does and then fills it through
  `FutureSetFromSubquery::buildSetInplace`. This covers `INSERT` into a table with
  `f UInt8 DEFAULT p IN keys` or the `MATERIALIZED` variant, and reading a part in which such a
  column is missing.

  The call has to come after the actions are built: planning a set subquery assigns unique aliases
  to the table expressions it reads, and that table expression node is the very `IN` right-hand
  side whose tree hash the set is keyed by, so building first makes the later lookup fail with
  `No set is registered for key`.

A `Set` engine table on the right-hand side is a ready set rather than a deferred one and worked
all along; new test `05210_column_default_in_table_set` keeps that covered, and also asserts that
an explicit subquery in a column default stays rejected at CREATE time.

Closes: #117276

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dea32a4]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR builds deferred sets for column ALIAS, DEFAULT, and MATERIALIZED expressions containing IN <table>, and shares them across readers. Changes are still required: missing-column and conversion defaults can discard the reader's table filters, and experimental enablement can undo copied function restrictions. Both behaviors were reproduced with the Fast test binary for dea32a48b9fe26b5a0ccede2d6973238f8b0a022.

Findings

❌ Blockers

  • src/Storages/MergeTree/IMergeTreeReader.cpp:457–462: The nested set query loses additional_table_filters. This setting is absent from the copied settings, so replacing the reader's settings with storage settings removes its row restrictions. With keys containing 1, 2, existing t.p values 1, 2, 3, and a subsequently added f UInt8 DEFAULT p IN keys, SELECT sum(f) FROM t SETTINGS additional_table_filters = {'keys': 'p = 1'} returns 2; direct membership and an equivalent ALIAS return 1. Nullable conversion defaults are affected too: DEFAULT toUInt8(2) IN keys returns 1, versus 0 directly. Preserve the reader's table filters throughout RHS analysis, execution, and reuse; cover both default-evaluation paths.

⚠️ Majors

  • src/Storages/MergeTree/IMergeTreeReader.cpp:471: Experimental enablement undoes reader restrictions after copying and clamping them. enableAllExperimentalSettings re-enables allow_fuzz_query_functions, among other gates. With an RHS view defined as SELECT p FROM keys WHERE notEmpty(fuzzQuery('SELECT 1')), a missing DEFAULT p IN rhs succeeds under allow_fuzz_query_functions = 0, readonly = 1, while direct p IN rhs throws SUPPORT_IS_DISABLED. Preserve the reader's effective restrictions for the newly executed RHS query while allowing types needed by the stored expression. Add a regression for a gate changed by this helper. Replied with current evidence and reopened the existing bot-authored thread, whose latest reply claimed the restriction was fixed.
Final Verdict

Status: ❌ Block

Preserve table filters and function restrictions for default-set queries, with focused regressions for the reproduced cases.

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

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dea32a48b with master 0b5613b71 (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.

Object file sizes

242 object files changed (+264.58 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/inplaceBlockConversions.cpp.o 326.46 KiB 409.68 KiB +83.22 KiB (+25.49%)
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.58 MiB 1.61 MiB +29.49 KiB (+1.82%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/IMergeTreeReader.cpp.o 426.70 KiB 450.70 KiB +24.00 KiB (+5.62%)
src/CMakeFiles/dbms.dir/Planner/Utils.cpp.o 359.00 KiB 377.34 KiB +18.34 KiB (+5.11%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR builds the sets for x IN table in column DEFAULT/MATERIALIZED/ALIAS expressions, adds create-time checks for skip indexes, and holds back progress packets while an INSERT is being prepared. None of this runs for ClickBench SELECTs over tables without ALIAS columns, so the Q13 (+11.3%) and Q14 (+10.7%) regressions are downgraded to not_sure. The suppressed Q16, Q17, Q33 and Q34 rows check out: each PR median sits inside master's recent range. Q13 and Q14 also fall inside their ranges even though they were not suppressed. All flagged queries are aggregation-heavy, show a uniform rise in CPU time, and two PR runs shared a node, which points to environment variance rather than this change.

clickbench

⚠️ 7 inconclusive

Flagged queries (7 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 351 390 +11.3% <0.0001 aggregation: This GROUP BY SearchPhrase query with uniq(UserID) is +11.3% slower, and its 390.5 ms median is still inside master's recent 338–394.5 ms range. The PR changes no aggregation, scan, or SELECT planning code that this query uses.
⚠️ 14 not_sure 312 346 +10.7% <0.0001 aggregation: This two-key GROUP BY is +10.7% slower, but its 345.5 ms median is inside master's recent 303.5–349 ms range. The PR's changes to ALIAS columns, column defaults and INSERT progress are not executed by this query.
⚠️ 16 not_sure 530 644 +21.5% <0.0001 aggregation: Suppression is consistent with the data: the 644 ms median is inside master's 519–669 ms range. The query reads no ALIAS columns and evaluates no column defaults, so the +21.5% cannot be pinned on this diff.
⚠️ 17 not_sure 235 263 +11.9% <0.0001 aggregation: The 263 ms median is inside master's 231–272 ms range, and the PR runs were noisy. Nothing in the diff touches this GROUP BY path.
⚠️ 32 not_sure 717 790 +10.2% <0.0001 aggregation: The two tests disagree and both sides were very noisy. The +10.2% is not tied to any code this PR changes.
⚠️ 33 not_sure 1137 1230 +8.2% 0.0003 aggregation: The 1230 ms median is inside master's 1092–1346 ms range. This high-cardinality GROUP BY does not reach the changed set-building or ALIAS code.
⚠️ 34 not_sure 1139 1227 +7.7% 0.0010 aggregation: The 1227 ms median is inside master's 1093–1342.5 ms range. Like Q33, this GROUP BY does not reach any changed code.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: a17786b4-ae9d-453e-8186-947eea43e14b
  • MIRAI run: eca30768-e9a7-4238-9285-7a7a162abbd6
  • PR check IDs:
    • clickbench_42977_1791306098
    • clickbench_42983_1791306097
    • clickbench_42989_1791306097
    • tpch_adapted_1_official_43000_1791306098
    • tpch_adapted_1_official_43012_1791306097
    • tpch_adapted_1_official_43049_1791306098

alexey-milovidov and others added 2 commits September 19, 2026 01:59
…ault

The flaky check of `05210_column_default_in_table_set` failed on the `INSERT` into the table with
`f UInt8 DEFAULT p IN keys`, with `Unexpected packet from server (expected Data, Exception, Log or
TimezoneUpdate, got Progress)` (`UNEXPECTED_PACKET_FROM_SERVER`) - 1 run in 50 on `amd_binary`,
`amd_debug` and `amd_asan_ubsan` alike.

The set of the column default is built in place while the `INSERT` is being prepared, at a point
where the client is still waiting in `receiveSampleBlock` for the header of the table it is about to
upload into. `FutureSetFromSubquery::buildSetInplace` gives the executor of the set subquery the
interactive cancellation callback of the query, and that callback sends the client an interactive
update - a `Progress` packet among the rest - on every tick of `interactive_delay`, floored at 100
ms. A set that takes longer than one tick to build therefore writes a `Progress` into the connection
at a point where neither of the two states the client can be in - waiting for the `INSERT` header, or
uploading its data - accepts one. Hence the timing dependence: a build under the tick is invisible.

Turn the interactive cancellation off for the in-place builds that run from a block conversion, with
the new `allow_interactive_cancel` argument of `buildSetInplace`. The default stays on, so the
ordinary set builds - primary key analysis and the like, which run while the client does expect
progress - are unchanged.

Reproduced deterministically with a set large enough to take longer than one tick, on a server
without the fix:

    CREATE TABLE bigkeys (p UInt64) ENGINE = MergeTree ORDER BY p;
    INSERT INTO bigkeys SELECT number FROM numbers(20000000);
    CREATE TABLE tdef (p UInt64, f UInt8 DEFAULT p IN bigkeys) ENGINE = MergeTree ORDER BY p;
    INSERT INTO tdef (p) VALUES (1), (2);  -- UNEXPECTED_PACKET_FROM_SERVER, every time

`05210_column_default_in_table_set` now pins `async_insert = 0`: an asynchronous insert answers the
client before the block is converted, so it never reaches this path, and the randomization of the
setting would silently drop the coverage.

Also close the same gap on the old-analyzer half of `performRequiredConversions`, which the review of
the pull request pointed out: `createExpressions` registers the set of the column default without
ever filling it, and `FunctionIn` would report `Not-ready Set is passed as the second argument for
function 'in'` there too. The set registered by `ActionsVisitor` already carries its own plan, so it
only has to be filled. There is no test for it: the analyzer is mandatory since v26.9, a query that
asks for the old query analysis is refused with `SETTING_CONSTRAINT_VIOLATION`, and the path is left
only for a query another server sends.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Planner/Utils.cpp Resolved
Comment thread src/Interpreters/PreparedSets.cpp Resolved
alexey-milovidov and others added 4 commits October 3, 2026 04:35
…, fail closed on an uncreated set

Instead of disabling the interactive cancellation of every in-place set build from a column default
(which also covers reads of old parts through `evaluateMissingDefaults`, where the client expects
cancellation and progress), suppress only the interactive updates in `TCPHandler` while `executeQuery`
prepares an `INSERT`: the client is waiting in `receiveSampleBlock` for the table header and accepts
neither `Progress` nor `ProfileEvents` there. Cancellation is still polled. The
`allow_interactive_cancel` argument of `buildSetInplace` is removed.

`FutureSetFromSubquery::buildSetInplace` now throws when the pipeline stopped without creating the
set (e.g. `timeout_overflow_mode = 'break'`): `build` consumed `source`, so the set can never be
built later and `FunctionIn` would report "Not-ready Set is passed as the second argument".

Add a test case for a `DEFAULT ... IN <table>` column added by `ALTER` and read from old parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ate suppression

`buildSetInplace` threw `LIMIT_EXCEEDED` whenever the set was not created, which also broke its
other callers that tolerate an uncreated set, such as index analysis through
`buildSetsForDAGExcludingGlobalIn` (`02844_subquery_timeout_with_break`). Check the set only in
`buildPreparedSetsInplace`, which is the path for column defaults.

`TCPHandler` suppressed interactive updates during `executeQuery` whenever the context had an
insertion table, which includes `CREATE ... AS SELECT`, whose whole `INSERT` runs inside
`executeQuery` while the client expects progress
(`03629_create_or_replace_as_select_with_progress_tcp`). Suppress them only for `INSERT` queries.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119664&sha=9e37a8a395e1ae476ceee5a7ce77a93409af7ff2&name_0=PR&name_1=Fast%20test
PR: #119664

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 5, 2026
The targeted AST fuzzer fuzzed the queries of `05075` and ran mutations
over the `ALIAS p IN t_prune_in_table_keys` column, which hit the
`Not-ready Set` exception of #117276
(STID: 0250-4e52) when they execute. Its fix,
#119664, is separate.

Make the test a `.sh` one, since the targeted fuzzer takes only `.sql`
files, and pass `ast_fuzzer_runs = 0` to disable the server-side fuzzer.
The queries and the reference are unchanged.

CI: https://github.com/ClickHouse/ClickHouse/actions/runs/37213398607/job/111474365208
PR: #117272

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 5, 2026 20:04
A skip index over an `ALIAS` column whose expression is `p IN <table>` evaluated the expanded
`in` with a set that nothing ever built, so an `INSERT` threw `Not-ready Set is passed as the
second argument for function 'in'`. The AST fuzzer reached it through the implicit min-max index
created by `add_minmax_index_for_numeric_columns`. Key and index expressions already reject
`IN <table>` written directly, but the check ran before the `ALIAS` expansion.

Check the expanded index expression too, and do not create an implicit min-max index for an
`ALIAS` column whose expanded expression would be rejected.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119664&sha=e2da9a01391a4e62b2c871cc435951491f6b16c6&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: #119664

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reading old parts evaluates a missing `DEFAULT` with the global context of the storage, which never
went through `makeQueryContext` and so has a zero client version. When the set subquery of a
`DEFAULT ... IN <table>` became distributed - with parallel replicas enabled in the profile, or for a
`Distributed` table on the right-hand side - `RemoteQueryExecutor` threw `Sending a distributed query
with unknown (zero) client version`. Fill the initiator version and disable parallel replicas for the
default expression, as `ExecuteScalarSubqueriesVisitor` does for the scalar subqueries of a
standalone expression.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119664&sha=e2da9a01391a4e62b2c871cc435951491f6b16c6&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: #119664

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 6, 2026
In the private sync CI (`ReplicatedMergeTree` replaced with `SharedMergeTree`),
`SYSTEM STOP REPLICATION QUEUES` does not keep the mutations pending, so
`DELETE WHERE is_hit` over the `ALIAS ... IN <table>` column executes and hits the
`Not-ready Set` exception of #117276
(its fix is #119664).

Related: ClickHouse/clickhouse-private#71724

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/IndicesDescription.cpp Resolved
alexey-milovidov and others added 2 commits October 14, 2026 23:59
…ts children

`ReadFromMerge::convertAndFilterSourceStream` computes the `ALIAS` columns of an
underlying table with its own `ExpressionStep`, whose sets `collectSets` registers in
the planner context of the child. No `CreatingSet` step was added for them, so an
`ALIAS` column over `IN <table>` read through `merge` threw `Not-ready Set is passed
as the second argument for function 'in'`. Report the sets of these steps and add a
`DelayedCreatingSetsStep` for them to the child plan, planning the set subqueries
with the new `planPreparedSetSubqueries`, factored out of `buildPreparedSetsInplace`.

Found by the AST fuzzer: `SELECT flag FROM merge(currentDatabase(), '^') ORDER BY x DESC NULLS LAST`
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119664&sha=761fe0ec119978cd5be4b2c412bcf6fcefc83427&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
#119664

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 7 commits November 16, 2026 07:17
…the same settings

A set of a column default reading a table depends on the settings of the reader
(`transform_null_in`, `max_rows_in_set` with `set_overflow_mode = 'break'`, ...),
and the readers of one query may have different settings, e.g. the children of a
`Merge` table that are views with their own `SETTINGS`. Include the settings in the
identity under which the sets are shared, except the ones that only limit the
parallelism, which `Merge` sets differently for each child.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-column-default

# Conflicts:
#	src/Interpreters/PreparedSets.h
#	src/Processors/QueryPlan/SourceStepWithFilter.h
#	src/Storages/IndicesDescription.h
…ding a table

`keepReaderSettingsConstraints` returned early without explicit constraints and cleared
`readonly` before clamping, so with `allow_executable_tables = 0` and `readonly = 1`
the storage value `1` was used for the read of `DEFAULT p IN exec_rhs`, and the script
ran. Now the settings of the storage that differ from the reader's are checked with the
readonly mode of the reader as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… reads

A nested `ReadFromMerge` kept its own `alias_sets` and built them for its children, so a
set of `f ALIAS p IN keys` was built once per nested `Merge` table, and the children could
see different snapshots of `keys`. Now the outer read hands its registry to the nested reads
of its child plans which have the same access and settings (`canShareSetsOfExpressions`),
and only the outer read builds the sets, in front of the pipelines of all its children.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 19, 2026
alexey-milovidov and others added 2 commits November 22, 2026 11:44
…-column-default

Conflict in `src/Processors/QueryPlan/SourceStepWithFilter.h`: keep both the `setDefaultExpressionsSets` method of this branch and `canSkipDataByFilterOn` from master.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… reads at the default settings

`canShareSetsOfExpressions` compared `Settings` with `operator==`, which compares the lists of the changed settings, so a default value and the same value assigned explicitly were unequal. A `Merge` read assigns `enable_parallel_replicas = 0` for its children, so a nested `Merge` read never shared the registry of the sets with the outer one unless the query had this setting explicitly, and each nested read built its own set.

Compare the effective values with the new `Settings::hasSameValues`. Also compare a nested read with the context the child plan is created with instead of the context of the outer read, so the settings assigned for every child (`enable_parallel_replicas`, `make_distributed_plan`) do not prevent the sharing when parallel replicas are enabled.

New test `05843_column_alias_in_table_set_nested_merge_plain_columns`: nested `Merge` tables with plain intermediate columns and no explicit parallel replicas setting.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed b3af759 (merged master; one conflict in src/Processors/QueryPlan/SourceStepWithFilter.h, where both sides added a method - kept both) and effc38a (the remaining review thread: nested Merge reads now share the sets of ALIAS columns at the default settings, new test 05843_column_alias_in_table_set_nested_merge_plain_columns). The only red check was the review-threads gate in Finish Workflow; the full CI suite was skipped because of it.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119664&sha=effc38aa8e320fc0331749a271830d36487b4e60&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

05829_read_by_layers_reads_only_key_prefix (added on 2026-11-21 by #132720) printed 05829_join 0 instead of 05829_join 1: the merge join read more than a tenth of the compressed size of the column s. It looks unrelated to this PR, which does not touch the read in order or the split into layers:

  • It does not reproduce on this branch merged with master (release build, arm): with the randomized query and MergeTree settings of the failed run the join reads 17100 compressed bytes against a threshold of about 597000, and the same with each of the suspicious settings forced separately (merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 1, enable_join_runtime_filters, query_plan_optimize_join_order_randomize, query_plan_read_in_order_through_join, the page cache).
  • In CI the test has 4646 OK results over the last 10 days and this single failure outside of its own PR, so it is a rare flake of a new test, possibly specific to the ASan build.

Pushed dc4e04a (merged master, no conflicts, the diff of the PR is unchanged). The *_column_default_in_table_set_* and *_column_alias_in_table_set_* tests pass locally on the merged build, except 05461_column_default_in_table_set_mutation_partitions, which needs ZooKeeper and was not run locally.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 05829_read_by_layers_reads_only_key_prefix failure; I'll follow up here with a PR (or my findings) shortly.

Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 23, 2026 02:11

AI review of a later commit does not approve the PR, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #133653 (test-only).

The excess bytes were column statistics, not the read: the failing join had ReadCompressedBytes 426184 vs 17100 in the other runs, with identical SelectedMarks/read_rows/read_bytes and StatisticsCacheMisses 2. The concurrent 05081_ill_typed_skip_index_expression_attach.sh dropped an Ordinary database between the EXPLAIN and the join, and Context::clearCaches emptied the statistics cache, so the join reloaded the randomized uniq statistics (~408 KB). The server codec ZSTD(1) of that job puts the threshold at ~326 KB (~597 KB with LZ4), which is why it did not reproduce on a release build. The PR creates the table with auto_statistics_types = '': 9/100 failures before, 0/250 after under a cache-clear loop.

alexey-milovidov and others added 3 commits November 23, 2026 07:35
A default of a column missing in a part is evaluated with the settings of
the storage context, except the limits and the settings restricting the
access, which are taken from the reading query. Of the latter only
`readonly`, `allow_ddl` and `allow_introspection_functions` were taken
unconditionally; the other ones kept the value of the reader only when a
constraint or the readonly mode pinned it. So
`SELECT sum(f) FROM t SETTINGS allow_executable_tables = 0`, where `f` is
`DEFAULT p IN exec_rhs`, still read the `Executable` table, while the direct
spelling `p IN exec_rhs` threw `SUPPORT_IS_DISABLED`.

Take every setting named `allow_*` from the reading query: they say what the
query is allowed to do and do not change the meaning of an expression.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…er settings and definers

A `Merge` read shares the sets of the `ALIAS` columns only between the
children it computes these columns for, which are tables, with its own
context. A child that is a view computes them in its own plan, with the
settings of the view and on behalf of its `SQL SECURITY DEFINER` user, and a
nested `Merge` read under such a view does not share the sets of the outer
one (`canShareSetsOfExpressions`). The test pins this down for views with
`transform_null_in`, `max_rows_in_set` and different definers, directly over
the tables and over nested `Merge` tables.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed dea32a4 (merged master, no conflicts) with two commits for the remaining review threads:

  • 40e2df0: a default of a column missing in a part now takes every allow_* setting from the reading query, so SELECT sum(f) FROM t SETTINGS allow_executable_tables = 0 throws SUPPORT_IS_DISABLED without any constraint, the same as the direct p IN exec_rhs. 05770_column_default_in_table_set_reader_constraints covers it.
  • d76d168: new test 05857_column_alias_in_table_set_merge_view_identities. The sharing of ALIAS ... IN table sets across Merge children with other settings or definers does not reproduce (such children are views, which compute the ALIAS columns in their own plans); the test pins that down. Details are in the thread.

The only red check was the review-threads gate in Finish Workflow. Locally the *_column_default_in_table_set_* and *_column_alias_in_table_set_* tests pass on the merged build, except 05461_column_default_in_table_set_mutation_partitions, which needs ZooKeeper and was not run.

Comment on lines +457 to +462
auto default_expressions_settings = storage_context->getSettingsCopy();
const auto & reader_settings = settings.read_context->getSettingsRef();
for (std::string_view name : getReaderSettingsForDefaultExpressions())
default_expressions_settings.set(name, reader_settings.get(name));
keepReaderSettingsConstraints(default_expressions_settings, *settings.read_context);
context_copy->setSettings(default_expressions_settings);

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.

[Blocker] Preserve the reader's additional_table_filters for the RHS query

additional_table_filters matches none of the settings copied above, so replacing the reader's settings with the storage settings drops its row restrictions before the new set query is analyzed and executed. This exposes membership in rows excluded by the caller's filter.

Reproduced with this head's Fast-test binary:

CREATE TABLE keys (p UInt8) ENGINE = MergeTree ORDER BY p;
INSERT INTO keys VALUES (1), (2);
CREATE TABLE t (p UInt8) ENGINE = MergeTree ORDER BY p;
INSERT INTO t VALUES (1), (2), (3);
ALTER TABLE t ADD COLUMN f UInt8 DEFAULT p IN keys;

SELECT sum(p IN keys) FROM t
SETTINGS additional_table_filters = {'keys': 'p = 1'}; -- 1
SELECT sum(f) FROM t
SETTINGS additional_table_filters = {'keys': 'p = 1'}; -- 2

An ALIAS with the same expression correctly returns 1. The nullable-to-nonnullable conversion path also uses this context: substituting DEFAULT toUInt8(2) IN keys returns 1 despite the same filter, while direct membership returns 0.

Keep the reader's table filters throughout RHS planning/execution and set reuse, and add regressions for both missing columns and nullable conversions.

Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Nov 23, 2026
The measured merge join loads the column statistics of the table on a
statistics cache miss, and the compressed bytes of that load count in
`ReadCompressedBytes`, which the test compares with a tenth of the
compressed size of `s`. The `EXPLAIN PIPELINE` before the join normally
warms the statistics cache. A concurrent test that drops a table in an
`Ordinary` database empties the server-wide caches in between
(`MergeTreeData::dropAllData` calls `Context::clearCaches` for a table
without a UUID), so the join loads the statistics again. With the
randomized `uniq` statistic (about 408 KB here) and the randomized server
codec `ZSTD(1)` (threshold about 326 KB) the oracle prints 0. The read
itself is unchanged.

Create the table without statistics, so the measured queries count only
their column reads.

Related: ClickHouse#132720, ClickHouse#119664

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants