Repository navigation
Fix a logical error when the merge table function is used in a mutation - #113185
Conversation
…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]>
|
Workflow [PR], commit [e7ab5db] Summary: ✅
AI ReviewSummaryThis PR fixes the explicit Findings❌ Blockers
Final VerdictChanges requested. The explicit LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 45/52 (86.54%) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
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]>
|
🕵 The |
… 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]>
…ction-in-mutations
…`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()); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
@groeneai, After this PR merges, please continue with extending the fix as described.
There was a problem hiding this comment.
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 regexprather thanUNKNOWN_DATABASE, because the regexp is matched against the fallback database where the source table does not exist. The same statement withmerge('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 throughInterpreterAlterQueryatInterpreterDeleteQuery.cpp:192-217, which is where this PR adds the substitution, whilelightweight_updateandlightweight_update_forceroute throughInterpreterUpdateQueryat:189.enable_lightweight_updateis already on by default, so onlylightweight_delete_modehas to be moved off its default to reach it.
I will open the follow-up once this merges and link it here.
There was a problem hiding this comment.
Opened as #113748.
It landed a little wider than the scope in my note above, in two ways worth flagging:
InterpreterDeleteQueryneeded no change after all. Itslightweight_delete_modebranch builds anInterpreterUpdateQueryfrom 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 thatInterpreterAlterQueryperforms, 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 theON CLUSTERbranch, 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.
…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.
`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`.
Related: #111997
A mutation is interpreted in a background thread, where the current database is not set. When the predicate of
ALTER TABLE ... DELETE/UPDATEused themergetable function with a single argument, the source database was resolved to an empty string, andDatabaseCatalog::getDatabasefailed onchassert(!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 bothLogical error: '!database_name.empty()'andCannot start clickhouse-serverfor this single cause.Reproducer (a logical error in a debug build,
Database `` does not existin release):The database of the mutated table is now substituted into the
mergetable 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 theALTERquery does. This also fixes silently wrong results:merge(currentDatabase(), 'regexp')in a mutation used to resolve to the database from thedefault_databaseconfiguration setting, becausecurrentDatabaseis evaluated in the background thread. The substitution coverscurrentDatabaseand its aliases anywhere in the database argument (which can be an arbitrary constant expression, e.g.merge(concat(currentDatabase(), ''), 'regexp')), nested table functions such asremote('127.0.0.1', merge('regexp')), andALTER ... ON CLUSTER, where the query previously left for the DDL queue before the canonicalization, andcurrentDatabase()was replaced with the database of the session instead of the database of the mutated table.Additionally, the table function now throws
UNKNOWN_DATABASEwhen 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 onmasteritself and in five other pull requests on the same day).Changelog category (leave one):
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
mergetable 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
26.8.1.859(included in26.8and later)