Skip to content

Add setting force_materialized_cte to throw when a MATERIALIZED CTE cannot be materialized - #118853

Open
novikd wants to merge 27 commits into
masterfrom
force-materialized-cte
Open

novikd wants to merge 27 commits into
masterfrom
force-materialized-cte

Conversation

@novikd

@novikd novikd commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Related: #118032
Related: #118982
Related: #118983
Related: #120021
Related: #120022
Related: #120179

Motivation

WITH cte AS MATERIALIZED (...) is honoured only when enable_materialized_cte = 1 and the analyzer is used. In every other case the keyword was silently dropped and the CTE was inlined at each reference like an ordinary one (since #118032 the analyzer at least logs a warning). A user who writes MATERIALIZED to guarantee a single evaluation, for example over input() or a non-deterministic subquery, got a different query instead of an error.

Changes

  • New setting force_materialized_cte (Bool, default 1). When a CTE is declared AS MATERIALIZED but cannot be materialized, the query throws SUPPORT_IS_DISABLED instead of inlining it. With force_materialized_cte = 0 the previous behaviour is kept: the keyword is ignored and the analyzer logs a warning.
  • Analyzer: the check lives in QueryTreeBuilder, next to the existing RECURSIVE + MATERIALIZED check. It reads the per-query context, so SETTINGS enable_materialized_cte = 1 on a subquery still enables materialization for that subquery, and it also rejects materialized CTEs that are declared but never referenced.
  • Old query analysis: the analyzer is mandatory since 26.9, so enable_analyzer = 0 no longer reaches users, but InterpreterSelectQuery and TreeRewriter still run for mutations on a server configured with use_analyzer_for_mutations = 0. A dedicated RejectMaterializedCTEVisitor throws there for any WITH element declared AS MATERIALIZED: in InterpreterSelectQuery before the CTE rewrite and again in TreeRewriter::normalize after SQL UDF expansion, where a CTE hidden in a UDF body first becomes visible.
  • View definitions: CREATE VIEW, CREATE MATERIALIZED VIEW, a fresh full-definition ATTACH and ALTER TABLE ... MODIFY QUERY inline their CTEs through ApplyWithSubqueryVisitor before any analyzer runs, so AS MATERIALIZED there was silently dropped even with enable_materialized_cte = 1 (a view over a materialized rand() CTE evaluated it per reference). With the guard on these entry points now reject such definitions, including a materialized CTE introduced by a SQL UDF (the check runs after UDF expansion). Stub ATTACH, startup loading, RESTORE and the replay of an already committed Replicated database entry are exempt, so an upgraded replica never rejects a definition an older initiator committed. Preserving the references instead is a bigger change, tracked in Materialized CTEs lose single-evaluation semantics in stored view definitions and lightweight UPDATE #118982.
  • Lightweight UPDATE and DELETE: the mutation command is stored as text, which undoes the pre-enqueue CTE rewrite, so with the analyzer these statements materialize their CTEs like a SELECT. InterpreterUpdateQuery checks early, before the Replicated enqueue, the table lock and the block-number allocation: with the analyzer it rejects only under the general contract (force_materialized_cte = 1 and enable_materialized_cte = 0), with the same message as the analyzer check; without the analyzer (enable_analyzer = 0, or the server setting use_analyzer_for_mutations) it rejects AS MATERIALIZED regardless of force_materialized_cte, because the old-analyzer mutation path cannot run a CTE at all and there is nothing to inline into.
  • parallel_distributed_insert_select routes: the two fast paths (StorageDistributed::distributedWrite and the ReplicatedMergeTree / data-lake variant in InterpreterInsertQuery) expand the source query's WITH clauses in place to find the source storage, so a local shard executing that AST evaluated a materialized CTE per reference, and the parallel-replicas insert route forwards the analyzer's resolved query, in which a materialized CTE has become the initiator's temporary table. An INSERT ... SELECT whose SELECT declares a materialized CTE, directly, in a nested subquery, in a SQL UDF body or in an APPLY transformer, now skips these routes and runs on the initiator; a debug log line records the decision. Ordinary CTEs keep taking the routes as before. The detection walks the AST read-only, looking up SQL UDF bodies without substituting arguments (the substitution visitor rejects asterisk and COLUMNS arguments that the analyzer accepts) and inspecting the APPLY function name and lambda, which are not AST children. Two pre-existing route bugs found on the way are filed separately: Parallel-replicas INSERT SELECT route accepts a CTE in FROM and forwards a SELECT without its WITH clause (Unknown table expression identifier) #120021 (a CTE in FROM accepted for non-replicated destinations and forwarded without its WITH clause) and Parallel-replicas INSERT SELECT route forwards a materialized CTE as the initiator's _materialized_cte_* temporary table #120022 (a materialized CTE forwarded as the initiator's temporary table).
  • The PromQL-to-SQL entry points (prometheusQuery* table functions and the Prometheus HTTP API) now enable enable_materialized_cte unconditionally, since the generated SQL relies on materialized CTEs, and log at debug level when they do; previously they enabled it only when the caller had not changed it.
  • The enable_materialized_cte description and the WITH documentation describe the new behaviour; the input() error message no longer says that MATERIALIZED is only a hint and names enable_analyzer = 1 next to enable_materialized_cte = 1. BuzzHouse randomises both settings. The SQLAlchemy guide under docs/integrations/language-clients/python is a one-way copy from ClickHouse/clickhouse-connect; its paragraph on the old fallback behaviour is updated in a separate PR there.
  • Tests: new 05141_force_materialized_cte (including definition-time, ATTACH-independent read-time, UDF and lightweight UPDATE cases), 05142_force_materialized_cte_attach (fresh full-definition ATTACH versus stored-metadata replay), 05143_force_materialized_cte_on_cluster (DDL entry formats 5, 2 and 1), 05155_force_materialized_cte_udf_definitions (a UDF hiding a materialized CTE in a view definition or MODIFY QUERY; the UDF tests are shell tests with per-database function names, since UDF names are server-global and the flaky check runs a test concurrently with itself) , 05154_force_materialized_cte_parallel_insert_select (a materialized CTE bypasses both fast paths and the parallel-replicas insert route for Distributed and ReplicatedMergeTree destinations and is still evaluated once, also when declared inside a scalar subquery with an inner SETTINGS clause; forwarded-query evidence from system.query_log; a LIMIT inside a CTE in FROM; WITH alias forms on every route), 05212_force_materialized_cte_insert_routes_udf (the same bypass for a materialized CTE hidden in a SQL UDF body, in APPLY <udf>, in an APPLY lambda and in a UDF calling another UDF, plus a UDF with a COLUMNS argument that keeps taking the route; the CTE bodies are scalar subqueries, since a materialized CTE inside an IN subquery under parallel replicas hits the pre-existing Materialized CTE referenced twice + parallel replicas: replica gets the initiator's _materialized_cte_* temp table name and throws UNKNOWN_TABLE #112642 and NOT_FOUND_COLUMN_IN_BLOCK for a materialized CTE inside an IN subquery with parallel replicas when parallel_replicas_local_plan = 0 #120179 on the general path) and the integration test test_replicated_database_materialized_cte_replay (a format-1 entry, which carries no settings, replayed on a replica with the guard on); 05046 now enables enable_materialized_cte for its materialized CTE case; 04561 passes --force_materialized_cte 0 for its disabled case; 04811 creates its view over a materialized CTE with the guard off, since a stored view definition cannot honour it.

Changelog category (leave one):

  • Backward Incompatible Change

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

A CTE declared AS MATERIALIZED now throws SUPPORT_IS_DISABLED when it cannot be materialized, that is when the setting enable_materialized_cte is disabled or the old analyzer is used. Previously the MATERIALIZED keyword was silently ignored and the CTE was inlined at each reference. The check is controlled by the new setting force_materialized_cte (enabled by default); set force_materialized_cte = 0 (or compatibility = '26.8') to restore the previous behaviour.


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

A CTE declared `AS MATERIALIZED` was silently inlined as a regular CTE
whenever it could not be materialized: with `enable_materialized_cte`
disabled, or with the old analyzer. The new setting
`force_materialized_cte` (enabled by default) makes both cases throw
`SUPPORT_IS_DISABLED` instead; disabling it restores the previous
behaviour (the keyword is ignored, the analyzer logs a warning).

The analyzer check lives in `QueryTreeBuilder` next to the
`RECURSIVE` + `MATERIALIZED` check, so it reads the per-query context
(a subquery-level `SETTINGS enable_materialized_cte = 1` still works)
and also covers unreferenced materialized CTEs. The old-analyzer check
is done by `ApplyWithSubqueryVisitor` when invoked from
`InterpreterSelectQuery`.

The PromQL-to-SQL entry points disable the setting on their query
context: the `MATERIALIZED` marks they emit are hints, not user intent.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30fa1fe]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05238_analyzer_compatibility_allow_cte_redefinition FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Sep 8, 2026
novikd and others added 2 commits September 8, 2026 20:49
`ApplyWithSubqueryVisitor` is a rewriting pass shared by `CREATE`,
`INSERT`, `ALTER` and `UPDATE`; the validation does not belong there.
`RejectMaterializedCTEVisitor` walks the whole AST once from
`InterpreterSelectQuery` and throws for any `WITH` element declared
`AS MATERIALIZED`, since the old analyzer does not support them.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The SQL generated for PromQL relies on materialized CTEs, so the
`prometheusQuery*` table functions and the Prometheus HTTP API enable
`enable_materialized_cte` unconditionally instead of only when the
caller left it untouched, and log at debug level when they do. The
`force_materialized_cte` override is no longer needed there. The test
sections that exercised the inlined path are replaced by one asserting
that disabling the setting has no effect for PromQL.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 8, 2026
Comment thread src/Parsers/ParserWithElement.cpp Outdated
Materialized CTEs are an **experimental** feature.
They require the [analyzer](/guides/clickhouse/performance-and-monitoring/analyzer) and the setting `enable_materialized_cte` to be enabled.
If the setting is disabled, the `MATERIALIZED` keyword is ignored: the CTE is inlined at each reference like an ordinary CTE, and a warning is logged.
With the default `force_materialized_cte = 1`, using `AS MATERIALIZED` when these conditions are not met is an error (`SUPPORT_IS_DISABLED`).

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.

What are the conditions that are to be met?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Enabled enable_analyzer and enable_materialized_cte

@nikitamikhaylov nikitamikhaylov self-assigned this Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit d72eeaa664aab82846c4b027cab09d0fa473ba46 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

A stored view definition (`CREATE VIEW`, `CREATE MATERIALIZED VIEW`,
`ALTER TABLE ... MODIFY QUERY`, a fresh full-definition `ATTACH`) and a
lightweight `UPDATE` inline their CTEs through `ApplyWithSubqueryVisitor`
before any analyzer sees them, so `AS MATERIALIZED` there was silently
dropped: a view over a materialized `rand()` CTE evaluated it per
reference. With `force_materialized_cte` on, these entry points now
reject such definitions, including a materialized CTE introduced by a
SQL UDF (the check runs after UDF expansion).

Replay of an already committed Replicated database entry is exempt
(`ZooKeeperMetadataTransaction::isInitialQuery` is false there), so an
upgraded replica keeps applying definitions committed by an initiator
that predates the setting. Stub `ATTACH`, startup loading and `RESTORE`
are exempt as well. The guard runs before the entry is enqueued.

Tests: definition-time and read-time cases in `05141`, a fresh
full-definition `ATTACH` versus stored-metadata replay in `05142`,
`ON CLUSTER` with DDL entry formats 5, 2 and 1 in `05143`, and an
integration test that replays materialized-CTE definitions from a
format-1 entry on a replica with the guard on.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
novikd and others added 2 commits September 9, 2026 11:56
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
A non-refreshable materialized view cannot be created over a table
function, so the `MODIFY QUERY` section of
`05143_force_materialized_cte_on_cluster` failed in the fast test with
`QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW`. Use a `Memory` source
table, as `05141` does.

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

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The old-analyzer check in `InterpreterSelectQuery` runs before SQL UDF
bodies are inlined by `TreeRewriter::normalize`, so a materialized CTE
inside a UDF bypassed it and failed later with `UNKNOWN_TABLE` instead of
`SUPPORT_IS_DISABLED`. `normalize` now runs the same check right after
UDF expansion. The constructor check stays: it rejects a directly written
CTE before its body is cloned or its tables are resolved.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
…ECT` fast paths

`StorageDistributed::distributedWrite` and
`InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage`
expanded the `WITH` clauses of the source `SELECT` in place to find the
source storage. A local shard executing that AST, and the
parallel-replicas insert route that runs after both fast paths decline,
then saw plain subqueries carrying only a `cte_name`: a materialized
`rand64()` CTE referenced twice was evaluated twice. Text shipped to
remote shards was unaffected, because `ASTSubquery` formats a `cte_name`
as the bare name.

The expansion now runs on a clone used only for source detection and for
the `WHERE` / `PREWHERE` filter extraction, which keeps seeing the
expanded form; the query executed and forwarded stays untouched.
`buildInsertSelectPipelineParallelReplicas` judges its eligibility on an
expanded clone too, so a CTE in `FROM` is still a subquery there and its
own `ORDER BY` / `LIMIT` is never applied per replica.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Parsers/ParserWithElement.cpp Outdated
Materialized CTEs are an **experimental** feature.
They require the [analyzer](/guides/clickhouse/performance-and-monitoring/analyzer) and the setting `enable_materialized_cte` to be enabled.
If the setting is disabled, the `MATERIALIZED` keyword is ignored: the CTE is inlined at each reference like an ordinary CTE, and a warning is logged.
With the default `force_materialized_cte = 1`, using `AS MATERIALIZED` when these conditions are not met is an error (`SUPPORT_IS_DISABLED`).

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.

docs/integrations/language-clients/python/sqlalchemy.mdx:311 still documents the pre-PR fallback: it says enable_materialized_cte=0 or enable_analyzer=0 only re-inlines the CTE and "raises nothing". After force_materialized_cte defaults to 1, a SQLAlchemy-generated materialized=True CTE now throws SUPPORT_IS_DISABLED in exactly those sessions unless the user also disables force_materialized_cte.

Please update that hand-written guide alongside these reference-doc changes so the public docs do not contradict each other.

Comment thread src/Storages/StorageInput.cpp Resolved
… and the `input()` hint

The SQLAlchemy guide still said that a materialized CTE query with
`enable_materialized_cte = 0` or `enable_analyzer = 0` succeeds and only
loses the optimisation; with the default `force_materialized_cte = 1` it
now fails with `SUPPORT_IS_DISABLED`, so the paragraph describes that and
the `force_materialized_cte = 0` / `compatibility = '26.8'` escape hatch.
The `input()` hint also names `enable_analyzer = 1`, since the suggested
rewrite is rejected on the old analyzer.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@novikd

novikd commented Sep 10, 2026

Copy link
Copy Markdown
Member Author

Addressed the two remaining review findings in 792ca5e: the SQLAlchemy guide describes the force_materialized_cte default and its escape hatch (warning mentioned for the analyzer path only), and the input() hint names enable_analyzer = 1 next to enable_materialized_cte = 1.

@mintlify

mintlify Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 27, 2026, 1:23 AM

extern const int SUPPORT_IS_DISABLED;
}

/// Throws for a `WITH` element declared `AS MATERIALIZED` anywhere in the query, so a path that cannot

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.

force_materialized_cte stops being a real per-query setting on the paths that use this whole-tree visitor.

executeQuery only forbids changing enable_analyzer / allow_experimental_analyzer inside subqueries; force_materialized_cte is otherwise allowed to vary per nested SELECT. But InterpreterSelectQuery, InterpreterCreateQuery, InterpreterAlterQuery, and InterpreterUpdateQuery all call this visitor on the entire AST with the outer context. As a result, an inner query cannot override the default on those paths: with outer force_materialized_cte = 1 it still throws even if the inner query does SETTINGS force_materialized_cte = 0, and with outer force_materialized_cte = 0 it is still silently inlined even if the inner query turns the guard back on.

The analyzer path already honors nested settings in QueryTreeBuilder, so this is an observable inconsistency rather than just an implementation detail. Can we stop / restart this check at subquery boundaries (or otherwise evaluate it in the nested query's own settings context) instead of walking the whole AST under the top-level setting?

novikd and others added 3 commits September 11, 2026 12:16
SQL UDF names are server-global and the flaky check runs a new test
concurrently with itself, so `05141` and `05153` collided on their fixed
function names with `FUNCTION_ALREADY_EXISTS`. The UDF cases move to
shell tests named after `${CLICKHOUSE_DATABASE}`: `05153` becomes a shell
test and the view-definition cases of `05141` move to the new `05155`.

The integration test's `MODIFY QUERY` selected `number` from a table
whose column is `x`; it now selects `x`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118853&sha=792ca5e52e672eece058f080cafeb02104318b5e&name_0=PR

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ckhouse-connect

`docs/integrations/language-clients/python` is synced from the `docs`
folder of `ClickHouse/clickhouse-connect`, so the paragraph about the
`force_materialized_cte` default has to be changed there.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
novikd and others added 3 commits September 14, 2026 18:16
…CT routes

`StorageDistributed::distributedWrite`, `distributedWriteFromClusterStorage` and
`InterpreterInsertQuery` go back to master: the fast paths expand CTE references in place
again, and the parallel-replicas insert route judges eligibility on that AST as before. The
next commit keeps materialized CTEs away from these routes instead.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ialized CTE

The `parallel_distributed_insert_select` fast paths expand CTE references in place before
executing or forwarding the query, and the parallel-replicas insert route forwards the
analyzer's resolved query, in which a materialized CTE has already become the initiator's
temporary table. Both evaluate a CTE declared `AS MATERIALIZED` once per reference, or fail on
the replicas.

An `INSERT ... SELECT` whose `SELECT` declares such a CTE now skips these routes and runs on
the initiator. The detection walks the AST read-only: nested subqueries, SQL user-defined
function bodies looked up without argument substitution (the substitution visitor rejects
asterisk and `COLUMNS` arguments the analyzer accepts), and the name and lambda of `APPLY`,
which are not AST children. It does not depend on `enable_materialized_cte`, because a
`SETTINGS` clause inside a subquery can enable materialization on the executing shard.

`05154_force_materialized_cte_parallel_insert_select` now describes the bypass and checks a
nested declaration with an inner `SETTINGS` clause and the forwarded-query evidence in
`system.query_log`; the new `05212_force_materialized_cte_insert_routes_udf` covers UDF and
`APPLY` shapes and keeps a UDF with a `COLUMNS` argument on the route.

Related: #120021
Related: #120022

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… tests

The style check requires a per-database condition on every `system.query_log` query. The rows
these tests look for are the forwarded secondary inserts, which record `current_database =
'default'` on the remote connection while their `databases` column names the test database, so
the accepted `has(databases, currentDatabase())` form is used instead of a `current_database`
comparison, which would have hidden exactly those rows.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118853&sha=0fae6f64cd33a9ae5586242139d345ab10a03612&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Fable 5.1 <[email protected]>
with_element->name, data.reason, data.remedy);
}

static bool needChildVisit(const ASTPtr &, const ASTPtr &) { return true; }

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.

APPLY is still a bypass for the new reject logic. ASTColumnsApplyTransformer keeps func_name, parameters, and lambda outside children, but both ConstInDepthNodeVisitor and UserDefinedSQLFunctionVisitor::visit only recurse through children. That means APPLY f and APPLY (x -> ...) can still hide a materialized CTE from the old-analyzer and view-definition guards, even though this PR already had to special-case the same carrier in InterpreterInsertQuery::hasMaterializedCTE.

Please teach the reject path to inspect ASTColumnsApplyTransformer::{func_name,parameters,lambda} too; otherwise AS MATERIALIZED still does not fail closed on APPLY.

reject->remedy = "A lightweight `UPDATE` uses the analyzer when `enable_analyzer` is on "
"and the server setting `use_analyzer_for_mutations` does not override it";
}
else if (shouldRejectMaterializedCTE(getContext()) && !settings[Setting::enable_materialized_cte])

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.

This pre-check still uses only the outer mutation context. In analyzer mutations, a nested subquery can legitimately turn enable_materialized_cte on for itself even when the outer UPDATE/lightweight DELETE keeps it off, but this branch arms RejectMaterializedCTEVisitor for the whole predicate/assignment tree before those inner settings ever take effect.

As a result, a case like UPDATE ... SET v = (WITH c AS MATERIALIZED (...) SELECT ... SETTINGS enable_materialized_cte = 1) SETTINGS enable_materialized_cte = 0 now throws SUPPORT_IS_DISABLED even though the inner query should materialize. Could this guard stop and restart at subquery boundaries, or otherwise evaluate the nested query in its own settings context?

novikd and others added 3 commits September 15, 2026 14:10
`05212_force_materialized_cte_insert_routes_udf` put its materialized CTE inside an `IN`
subquery. The bypass works, but the insert then runs on the general path, whose `SELECT`
keeps the parallel-replicas settings, and that combination hits two pre-existing bugs when
another replica takes the read: the initiator's `_materialized_cte_*` temporary table name is
shipped to the replica (#112642), and with `parallel_replicas_local_plan = 0` the set column
is not found in the remote block (#120179). Neither is what the test covers.

The CTE bodies are now scalar subqueries, folded on the initiator before any fragment is
forwarded, for every shape the test exercises: a UDF, a UDF with the argument, `APPLY <udf>`,
an `APPLY` lambda and a UDF calling a UDF. The `DB::Exception` marker on stdout is gone: an
error reaches stderr with its message instead of a bare word.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118853&sha=af50264501671e30cde13d0852c9cef439f9ab7d&name_0=PR

Related: #112642
Related: #120179

Co-Authored-By: Claude Fable 5.1 <[email protected]>
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
#	src/Parsers/ParserWithElement.cpp
Master froze `enable_analyzer` at `1` (#118629): setting it to `0` is rejected and the
`no-old-analyzer` tag is gone from the harness. The old-analyzer sections of
`05141_force_materialized_cte` and the two `enable_analyzer = 0` variants of the `05154` alias
section are removed, `05153_force_materialized_cte_old_analyzer_udf` is deleted as a test of
the retired configuration, and the tags this PR had added to `04076` and `04700` go away.

The old query analysis still runs for mutations on a server configured with
`use_analyzer_for_mutations = 0`, so the checks in `InterpreterSelectQuery`,
`TreeRewriter::normalize` and `InterpreterUpdateQuery` stay; the setting descriptions, the
`WITH` documentation and the rejection message name that server setting instead of
`enable_analyzer`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
novikd and others added 2 commits September 17, 2026 21:30
# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
Master moved to 26.10 after the 26.9 release branch was cut, and the setting does not exist on
that branch, so its record moves from the 26.9 block to the 26.10 block: `compatibility` with
26.9 or older resets it to `false`, as for a version without the setting.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118853&sha=8da51dbfb4b91f20756736a8f85b75bc9cc15fb4&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Fable 5.1 <[email protected]>
/// query, so a materialized CTE would be evaluated per reference or shipped as the initiator's temporary
/// table. Such queries take the general path.
std::unordered_set<String> visited_udfs;
const bool has_materialized_cte = hasMaterializedCTE(*query.select, visited_udfs);

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.

force_materialized_cte = 0 / compatibility = '26.8' no longer restore the old parallel_distributed_insert_select behavior here. hasMaterializedCTE is a pure syntax scan, so INSERT INTO ... WITH c AS MATERIALIZED (...) SELECT ... SETTINGS enable_materialized_cte = 0, force_materialized_cte = 0 still sets has_materialized_cte = true and disables every fast route even though the query will inline c and used to be forwarded like an ordinary CTE.

That changes execution locality and performance relative to the advertised escape hatch. Can this gate honor the settings scope that actually decides whether each AS MATERIALIZED is real, instead of keying solely on the presence of the keyword?

@novikd

novikd commented Sep 21, 2026

Copy link
Copy Markdown
Member Author

Needs fixing #120778 first

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

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

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Dear @nikitamikhaylov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch was successfully deployed

1 active deployment
staging - docs — 30fa1fe7 Deployed Sep 27, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants