Skip to content

Fix a logical error when the merge table function is used in a mutation - #113185

Merged
alexey-milovidov merged 6 commits into
masterfrom
fix-merge-table-function-in-mutations
Aug 5, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
fix-merge-table-function-in-mutations

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Related: #111997

A mutation is interpreted in a background thread, where the current database is not set. When the predicate of ALTER TABLE ... DELETE/UPDATE used the merge table function with a single argument, the source database was resolved to an empty string, and DatabaseCatalog::getDatabase failed on chassert(!database_name.empty()). The mutation is persisted, so the server aborted a second after every start attempt and could not start at all - the CI report below contains both Logical error: '!database_name.empty()' and Cannot start clickhouse-server for this single cause.

Reproducer (a logical error in a debug build, Database `` does not exist in release):

CREATE TABLE t (id UInt64) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1), (2);
CREATE TABLE t2 (id UInt64) ENGINE = MergeTree ORDER BY id;
INSERT INTO t2 VALUES (1);
ALTER TABLE t DELETE WHERE id IN (SELECT id FROM merge('^t2$')) SETTINGS mutations_sync = 2;

The database of the mutated table is now substituted into the merge table function when the mutation is created, in the same way as it is already done for table names, so the mutation reads the same tables as the ALTER query does. This also fixes silently wrong results: merge(currentDatabase(), 'regexp') in a mutation used to resolve to the database from the default_database configuration setting, because currentDatabase is evaluated in the background thread. The substitution covers currentDatabase and its aliases anywhere in the database argument (which can be an arbitrary constant expression, e.g. merge(concat(currentDatabase(), ''), 'regexp')), nested table functions such as remote('127.0.0.1', merge('regexp')), and ALTER ... ON CLUSTER, where the query previously left for the DDL queue before the canonicalization, and currentDatabase() was replaced with the database of the session instead of the database of the mutated table.

Additionally, the table function now throws UNKNOWN_DATABASE when it is called with a single argument and the current database is not set, instead of passing an empty database name down the stack.

Found by the AST fuzzer in a stress test: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111997&sha=17d2ddbbdee6ee0f726b7621839905cd5caa65e3&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 (the report belongs to an unrelated pull request; the failure comes from master, and it also happened on master itself and in five other pull requests on the same day).

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed an exception (in release builds - an error that prevents the server from starting) when a mutation predicate uses the merge table function without an explicit database name. The database of the mutated table is now used, the same way as it is done for table names.

Version info

  • Merged into: 26.8.1.859 (included in 26.8 and later)

…tion

A mutation is interpreted in a background thread, where the current database is not set.
When the predicate of `ALTER TABLE ... DELETE/UPDATE` used the `merge` table function with
a single argument, the source database was resolved to an empty string, and
`DatabaseCatalog::getDatabase` failed on `chassert(!database_name.empty())`. The mutation is
persisted, so the server kept aborting a second after every start attempt, and could not start.

Now the database of the mutated table is substituted into the `merge` table function when the
mutation is created, in the same way as it is done for table names, so the mutation reads the
same tables as the `ALTER` query. Before, `merge(currentDatabase(), 'regexp')` in a mutation
silently resolved to the database from the `default_database` configuration setting instead.

Additionally, the table function now throws `UNKNOWN_DATABASE` when it is called with a single
argument and the current database is not set, instead of passing an empty name down the stack.

Found by the AST fuzzer in a stress test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111997&sha=17d2ddbbdee6ee0f726b7621839905cd5caa65e3&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
Related: #111997

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

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e7ab5db]

Summary: ✅


AI Review

Summary

This PR fixes the explicit ALTER TABLE ... UPDATE/DELETE carrier and the explicit ALTER ... ON CLUSTER carrier for merge(...) inside mutation predicates by canonicalizing the database argument before the query is persisted or dispatched. The remaining blocker is that the same invariant is still violated by the lightweight-update carrier used by DELETE FROM, so the fix is not complete across the supported delete modes.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterAlterQuery.cpp:441; src/Interpreters/InterpreterDeleteQuery.cpp:167-217; src/Interpreters/InterpreterUpdateQuery.cpp:113-149] The new rewrite only exists in InterpreterAlterQuery. A DELETE FROM that switches to the lightweight-update implementation (lightweight_delete_mode = 'lightweight_update' or lightweight_update_force) still formats a raw UPDATE and runs it through InterpreterUpdateQuery, which never substitutes the database into merge(...). That means the same delete query now behaves differently depending on lightweight_delete_mode: the alter_update path uses the mutated table's database after this PR, while the lightweight-update path still resolves merge('^src$') against the session/default database or throws UNKNOWN_DATABASE on worker execution. The new lightweight-delete test does not cover that carrier because the default mode is still alter_update.
Final Verdict

Changes requested. The explicit ALTER path looks fixed, but the lightweight-update carrier still bypasses the new canonicalization, so supported DELETE FROM executions can still read from the wrong database or fail.

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: 45/52 (86.54%) · 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 3, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Aug 4, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

Ok. It is quite ad-hoc, but not more ad-hoc than the whole premise of AddDefaultDatabaseVisitor.

…uments

The canonicalization of the `merge` table function now also replaces an
explicit `currentDatabase()` first argument with a literal, because
`currentDatabase` would otherwise be evaluated in the background thread
that interprets the mutation, where the current database can be
different. The rewrite also recurses into arguments of table functions,
so a nested carrier like `remote('127.0.0.1', merge('tables_regexp'))`
is covered as well.

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

Copy link
Copy Markdown
Member Author

🕵 The AST fuzzer (amd_debug) failure (Logical error: 'database_name != "_temporary_and_external_tables"' on merge(REGEXP('.+'), 't.*')) is unrelated to this change: it happens on master and in several other pull requests (e.g. #110073, #110746, #66467, #110231), because StorageMerge with a database regexp iterates over the internal database of temporary tables. A fix is already open: #113224.

robot-clickhouse and others added 2 commits August 4, 2026 23:42
… argument of `merge`

The database argument of the `merge` table function can be an arbitrary constant
expression, e.g. `merge(concat(currentDatabase(), ""), ""tables_regexp"")`, and only
the bare `currentDatabase()` form was substituted. Now `currentDatabase` and its
aliases (`DATABASE`, `SCHEMA`, `current_database`) are replaced with a literal
everywhere in the first argument, so the persisted mutation does not depend on
the current database of the background thread.

Co-Authored-By: Claude Fable 5 <[email protected]>
…. ON CLUSTER`

The clustered path returned to `executeDDLQueryOnCluster` before the command
list was canonicalized, and `executeDDLQueryOnCluster` replaces
`currentDatabase()` with the database of the session, so a clustered mutation
could read different tables than a non-clustered one. Now the database of the
altered table is substituted into table functions in the command list before
the query is written to the DDL queue. The table identifiers are not qualified
at this point: they are qualified with the database of the altered table when
the query is interpreted on each host, as before.

Co-Authored-By: Claude Fable 5 <[email protected]>
…`currentDatabase`

The test number 05021 left a gap larger than 100 after the next test number,
and the query to `system.mutations` matched none of the patterns the style
check accepts for a database filter. Renumber the test to 04811 and add a
check that no mutation of the table is visible under the database of the
session.
/// of the altered table when the query is interpreted on each host.
if (table_id)
{
AddDefaultDatabaseVisitor visitor(getContext(), table_id.getDatabaseName());

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.

ALTER now canonicalizes merge(...) before the clustered dispatch, but the same carrier still bypasses the rewrite through InterpreterUpdateQuery. UPDATE ... ON CLUSTER goes straight to executeDDLQueryOnCluster, and InterpreterDeleteQuery reaches that code whenever lightweight_delete_mode is lightweight_update or lightweight_update_force.

A focused repro is:

SET lightweight_delete_mode = 'lightweight_update';
DELETE FROM db.t
    WHERE id IN (SELECT id FROM merge('^src$'));

run from a session whose current database is not db (and the ... ON CLUSTER ... form is even worse, because the worker context has no matching session database to fall back to). The explicit ALTER TABLE db.t DELETE ... path now persists merge('db', '^src$'), but this branch still formats a raw UPDATE and executes it through InterpreterUpdateQuery, which never substitutes the database into the merge table function. So the same lightweight delete keeps reading default.src or throws UNKNOWN_DATABASE, depending on where it runs, instead of using db.src.

Could we factor this substitution into InterpreterUpdateQuery as well, and let the DELETE FROM rewrite reuse it?

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.

@groeneai, After this PR merges, please continue with extending the fix as described.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Acknowledged, I will take this.

The scope I read from the thread: factor the merge(...) database substitution into InterpreterUpdateQuery so it applies on both of its exits, executeDDLQueryOnCluster (InterpreterUpdateQuery.cpp:117) and the local table->updateLightweight (:149), and have the DELETE FROM rewrite at InterpreterDeleteQuery.cpp:189 reuse it instead of formatting a raw UPDATE that bypasses it.

Two details I measured on master (26.8.1.1) while reading, in case they change what you want:

  • The repro reproduces with no cluster involved, and the observed failure in the one-argument form is Code: 636 ... There are no tables satisfied provided regexp rather than UNKNOWN_DATABASE, because the regexp is matched against the fallback database where the source table does not exist. The same statement with merge('d1', '^src$') deletes the expected row, so the local lightweight-update path is a carrier as well.
  • The gap is confined to the non-default lightweight_delete_mode: alter_update (the default) routes through InterpreterAlterQuery at InterpreterDeleteQuery.cpp:192-217, which is where this PR adds the substitution, while lightweight_update and lightweight_update_force route through InterpreterUpdateQuery at :189. enable_lightweight_update is already on by default, so only lightweight_delete_mode has to be moved off its default to reach it.

I will open the follow-up once this merges and link it here.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Opened as #113748.

It landed a little wider than the scope in my note above, in two ways worth flagging:

  • InterpreterDeleteQuery needed no change after all. Its lightweight_delete_mode branch builds an InterpreterUpdateQuery from a formatted string, so it inherits the substitution rather than needing its own call; that removes the raw-format bypass without touching the file.
  • Besides the merge(...) substitution, the interpreter was missing the whole canonicalization step that InterpreterAlterQuery performs, so a plain unqualified identifier and a SQL user-defined function body resolved against the session database too. The fix mirrors both of your calls: the narrow one inside the ON CLUSTER branch, and the common-table-expression expansion plus the full visitor after the replicated-database branch.

One inherited limit is disclosed on the PR rather than fixed there: AddDefaultDatabaseVisitor::visitTableFunction canonicalizes merge only, so a bare loop(t) or dictionary(d) still resolves its argument against the session database. That is the shared visitor's scope and the ALTER path has it identically today, so widening it belongs in its own change.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 5, 2026
Merged via the queue into master with commit ed1b2e4 Aug 5, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-table-function-in-mutations branch August 5, 2026 19:23
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
alexey-milovidov added a commit that referenced this pull request Aug 6, 2026
…ded-by-query-limit

Pull in the fix for the logical error in `StorageMerge::DatabaseNameOrRegexp::getDatabaseIterator`
(#113185), which caused the unrelated
`Stress test (arm_msan)` failure on an earlier head, and refresh the wedged `CH Inc sync` check.
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 9, 2026
`UPDATE` and the lightweight `DELETE` rewrite read the wrong tables, silently, when the
database of the updated table differs from the database of the session. With `t` in `db1`,
a `src` in both `db1` and the session database, and the session on the latter,
`UPDATE db1.t SET v = 9 WHERE id IN (SELECT id FROM merge('^src$'))` updates the row
selected from the session's `src`. The same happens with a plain identifier `FROM src`, in
the expressions of the assignments, and for `DELETE` at
`lightweight_delete_mode = 'lightweight_update'`. The direct `UPDATE` form needs no
non-default session setting.

`InterpreterUpdateQuery::execute` had two exits, `executeDDLQueryOnCluster` and
`table->updateLightweight`, and neither substituted a database, so the expression reached
`MutationsInterpreter` verbatim and every unqualified name resolved against whatever
current database that context held.

This is a disagreement of the engine with itself rather than a choice of semantics:
forcing `ALTER ... UPDATE` through `tryRewriteToLightweightUpdate` calls the same
`table->updateLightweight` (both arms show no mutation and two patch parts, the
lightweight patch-part signature) yet resolves the name in the database of the table.

The two calls of `InterpreterAlterQuery` are mirrored: the narrow
`substituteDatabaseInTableFunctions` inside the `ON CLUSTER` branch, because
`executeDDLQueryOnCluster` builds a visitor that rewrites only a bare `currentDatabase()`
and has no table-function arm; and the full visitor after the replicated-database branch,
which a replica also runs when it re-executes the queued entry with its own database.
`InterpreterDeleteQuery` needs no change, since its rewrite already constructs an
`InterpreterUpdateQuery`. The database of the resolved table is pinned at the existing
best-effort resolution, before the access rights are built, so an unqualified target no
longer reaches the distributed DDL queue with an empty database while those rights are
expanded to the configured default database of every host.

Follow-up to ClickHouse#113185, which did this for `ALTER`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants