Skip to content

Cherry pick #126292 to 26.7: Fix heap-use-after-free in TablesDependencyGraph and reject a materialized view selecting from itself - #126846

Merged
PedroTadim merged 10 commits into
backport/26.7/126292from
cherrypick/26.7/126292
Oct 20, 2026
Merged

PedroTadim merged 10 commits into
backport/26.7/126292from
cherrypick/26.7/126292

Conversation

@robot-clickhouse

Copy link
Copy Markdown
Member

Original pull-request #126292

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 10 commits October 16, 2026 12:41
`addDependency` kept the raw node of `table_id` while adding `dependency`.
`addOrUpdateNode` resolves a name conflict by removing the node that holds
the name, and that node can be the node of `table_id` itself: after
`RENAME` of a materialized view that selects from itself, the view graph
holds `{old name, UUID}` and `{new name}` for the one view, and the next
`ALTER TABLE ... MODIFY QUERY SELECT ... FROM <new name>` renames the first
onto the name of the second, removes the second and then wrote into it.

Keep the node alive while the dependency is added, and if it was removed,
use the dependency's node, which now has its name. Paths where the node
survives are unchanged.

Found by BuzzHouse (arm_asan_ubsan), STID 3810-3700.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`CREATE MATERIALIZED VIEW` cannot select from itself (the name does not exist
yet), but `ALTER TABLE ... MODIFY QUERY` accepted a query whose source table is
the view, directly or through a subquery. That puts a self-loop into the view
dependency graph, and after `RENAME` the next such `MODIFY QUERY` made
`TablesDependencyGraph::addDependency` write into a node it had just removed.

Throw `BAD_ARGUMENTS` for it instead, and drop the graph-level workaround:
without the self-loop the removed node is never the one `addDependency` holds.
Other alters of an existing view that already selects from itself still work,
so such a view stays loadable and can be fixed with `MODIFY QUERY`.

Found by BuzzHouse (arm_asan_ubsan), STID 3810-3700.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A `MODIFY QUERY` that makes the view read itself through another view is
already rejected by the referential cycle check in
`DatabaseOrdinary::alterTable` with `INFINITE_LOOP`; only a direct
self-reference escapes it, because `getDependencies` drops the table's own
name. Add the indirect case to the test so both stay covered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous check compared only the view's trigger table, the first
table of the first `SELECT`, so a self-reference in a `JOIN`, an `IN` or
scalar subquery, a nested derived table, or a later `UNION ALL` branch was
still accepted. The referential cycle check does not see it either,
because `getDependenciesFromCreateQuery` drops the table's own name.
Collect every table the new query references with the same visitor and
reject the alter when the view is one of them.

No current database is passed to the visitor: `InterpreterAlterQuery`
has already expanded the non-recursive CTEs and qualified every table
name with the view's database, so a name left unqualified is a recursive
CTE referring to itself, which must not match a view of the same name.

Refreshable views are excluded: inserts do not trigger them, so a refresh
that reads the view's current contents is a valid query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The referential dependency visitor read the right operand of `IN` with
`tryGetQualifiedNameFromArgument`, which also accepts a string literal,
so `x IN ('db.t')` was recorded as a dependency on the table `db.t`.
That literal is a set of values; the query never reads the table.

The self-reference check added to `MODIFY QUERY` collects references
with this visitor, so it rejected a valid query such as
`ALTER TABLE db.mv MODIFY QUERY SELECT c0 FROM db.src WHERE c0 IN ('db.mv')`
(`CREATE` with the same query succeeds). The cyclic dependency check had
the same false positive before: `x IN ('v')`, where `v` reads the view,
failed with `INFINITE_LOOP`. Both are accepted now; `x IN db.mv`,
`x IN (SELECT ... FROM db.mv)` and the other self-references are still
rejected.

The loading dependency visitor had the same rule for column defaults, so
two tables whose defaults are `c0 IN ('t2')` and `c0 IN ('t1')` could not
both be created (`INFINITE_LOOP`). It skips literals now too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The self-reference check of `MODIFY QUERY` collects dependencies with an
empty current database, so that an unqualified name (a recursive CTE) is not
taken for a table of the view's database. When an argument of `cluster`,
`clusterAllReplicas`, `joinGet` or `dictGet` is an expression, such as
`currentDatabase()`, the visitor evaluated it after
`setCurrentDatabase("")`, which throws the logical error "Database name
cannot be empty" (AST fuzzer, STID 3941-1dea).

The visitor now keeps the context's own database when none is given, and
the check passes the context the alter applies the new query in, so such an
argument is evaluated in the view's database, as the alter itself does.

The test also checks the self-reference after `RENAME TABLE`, the sequence
of the original use-after-free.

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

`AddDefaultDatabaseVisitor` leaves the name of a temporary table unqualified,
so `ALTER TABLE db.mv MODIFY QUERY SELECT ... FROM mv` with a temporary
table `mv` passed the self-reference check. The stored query names `db.mv`
for everyone outside the session, including the view dependency graph,
which got the self-loop back; after `RENAME TABLE db.mv TO db.mv2` the same
`ALTER` through a temporary table `mv2` reached the heap-use-after-free in
`TablesDependencyGraph::addDependency` again (a master ASan build aborts on
that sequence). `CREATE MATERIALIZED VIEW db.mv ... AS SELECT ... FROM mv`
created the same self-loop.

The check now qualifies a copy of the query with the global context, where
no temporary table exists, so a temporary table's name becomes a table of
the view's database while a recursive CTE stays unqualified as before. It
runs for `MODIFY QUERY` and for a fresh `CREATE` of a non-refreshable view.

Also restore the graph-level fix of the first revision: `addDependency`
keeps the node of `table_id` alive while `addOrUpdateNode(dependency)` may
remove it, and uses the dependency's node if it was removed. The SQL routes
to that state are rejected now, so the unit test builds the two-node state
`RENAME` leaves; it fails without the fix (the dependency is lost).

Reported by the AI review of #126292.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…add-dependency-uaf

Fix heap-use-after-free in `TablesDependencyGraph` and reject a materialized view selecting from itself
@robot-clickhouse robot-clickhouse added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Oct 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The only conflict is in StorageMaterializedView.cpp: on master, selectReadsView sits next to the incremental refresh helpers (getIncrementalSourceTableExpression and others), which are not in 26.7, so taking the master side of the conflict would also bring those helpers in. I added only selectReadsView and kept the rest of this PR unchanged.

git fetch https://github.com/groeneai/ClickHouse resolve-26.7-cherrypick-126292 && git push origin FETCH_HEAD:cherrypick/26.7/126292
  • 58ba1378867e is a fast-forward from the cherry-pick head 1a83e922fd52. Compared with backport/26.7/126292 it changes exactly the files of this PR, with the same added and removed lines (+106/-4).
  • On a 26.7 build (Debug, clang-21), 05404_materialized_view_cannot_select_from_itself passes 50/50 with randomized settings and the new TablesDependencyGraph.AddDependencyWhenTableNodeIsRemoved gtest passes. Without the source changes both fail.

@PedroTadim
PedroTadim merged commit ea4584e into backport/26.7/126292 Oct 20, 2026
174 of 177 checks passed
@PedroTadim
PedroTadim deleted the cherrypick/26.7/126292 branch October 20, 2026 09:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants