Skip to content

Fix merge('', regexp) reading the default database of other servers in distributed queries - #131528

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-empty-database-remote
Nov 16, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-empty-database-remote

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131316
Related: #122985

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 the merge table function with an empty database, merge('', 'regexp'), in a subquery or a JOIN of a query that is sent to other servers (remote, a Distributed table, *Cluster table functions, parallel replicas): those servers read the tables of their own default database instead of the current database of the query, which returned wrong results or failed with CANNOT_EXTRACT_TABLE_STRUCTURE.

Description

On 26.10.2.103 and master, with a current database other than default:

CREATE TABLE t_1 (x UInt64) ENGINE = Memory; INSERT INTO t_1 VALUES (2);
CREATE TABLE t_2 (x UInt64) ENGINE = Memory; INSERT INTO t_2 VALUES (3);
SELECT sum(number), count() FROM remote('127.0.0.2', numbers(4)) WHERE number IN (SELECT x FROM merge('', '^t_'));
-- CANNOT_EXTRACT_TABLE_STRUCTURE from 127.0.0.2, or `0 1` instead of `5 2` when `default` has a matching table

merge treats the database '' as the current database, but the query tree keeps '', so the query sent to another server says merge('', '^t_') and that server reads its own default database. #122985 fixed the same for the one-argument form by writing the resolved database into the query tree in QueryAnalyzer::resolveTableFunction; the same place now also writes the resolved database over the database argument, whatever its form, unless it is a REGEXP. As before, it is the tree that changes (IN set names are hashed from it), and a secondary query is left as sent, so mixed versions keep working (measured both ways).

The test 05300_merge_table_function_implicit_database_remote gets the merge('', ...) variants of its IN, JOIN, two-shard countIf and fileCluster queries, plus '' as a LowCardinality scalar subquery (it stays a __getScalar call in the query tree); they fail without the fix. Also measured: serialize_query_plan, parallel replicas, '' spelled as concat('', ''), toNullable('') or a query parameter, and unchanged results for other names, currentDatabase() and REGEXP.

loop(t) and dictionary('d'), also named in the issue, read the evaluating server's current database through other code and are fixed separately.


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

Version info

  • Merged into: 26.11.1.2421-master (included in 26.11 and later)

… in distributed queries

`merge` treats the database `''` as the current database: `TableFunctionMerge::parseArguments`
resolves it through `evaluateConstantExpressionForDatabaseName`, but only in its AST copy and in
the `StorageMerge` it builds. The query tree keeps `ConstantNode('')`, and the tree is what is
rendered or serialized for the other servers of a distributed query. Their current database is
their own default (`ClusterProxy::stripDatabaseSetting`), so each of them read its own `default`:
`CANNOT_EXTRACT_TABLE_STRUCTURE`, or wrong rows when `default` had matching tables.

ClickHouse#122985 fixed the one-argument form in `QueryAnalyzer::resolveTableFunction` by writing the
resolved database into the tree. The same block now also replaces a two-argument `merge` whose
database argument is a constant empty `String` with the resolved database. `''` is the only value
whose meaning depends on the evaluating server: other strings are absolute names, constant
expressions are folded on the initiator, and `REGEXP(...)` is not a constant. Keying on the value
covers every spelling that folds to `''` (`concat('', '')`, `toNullable('')`, a query parameter).
The replacement is in place, so the skipped-argument indexes keep their positions.

As in ClickHouse#122985 the tree changes, not only the sent text, because `IN` set names are hashed from
the tree; a secondary query is left as sent, so an older initiator with a newer shard keeps
working, and a newer initiator sends an ordinary `merge('<db>', re)` to an older shard.

Closes ClickHouse#131316

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 database_node is computed before the one-argument branch (QueryAnalyzer.cpp:5993) AGREE, not changed readability only, behaviour identical

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261114-042800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. From a database other than default, the first new merge('', ...) query of 05300 fails with CANNOT_EXTRACT_TABLE_STRUCTURE raised by the remote server on every run without the fix; the issue's own block returns 0 1 instead of 5 2 when default has a matching table. Same on 26.10.2.103.
b Root cause explained? merge('', re) resolves '' to the initiator's current database, but the query tree keeps '', so every server the query is sent to resolves '' against its own default database. #122985 bound the database only for the one-argument form.
c Fix matches root cause? Yes: the database merge actually read replaces the constant '' in the query tree at the same resolve-time place as #122985, so the tree, the sent text, a serialized plan and the receiver's re-parse all name it.
d Test intent preserved / new tests added? 05300_merge_table_function_implicit_database_remote extended with the merge('', ...) variants of its IN, JOIN, two-shard countIf and fileCluster queries; the existing queries are unchanged.
e Both directions demonstrated? Without the fix the test fails (Code 636 from the replica) and the issue's block returns wrong rows; with it, 50/50 randomized runs pass and the issue's block returns 5 2.
f Fix is general across code paths? One site covers remote, Distributed, *Cluster functions, parallel replicas and serialize_query_plan (each measured). merge inside remote()/cluster() arguments stays unresolved on the initiator by design. loop, dictionary and mergeTreeIndex('', t) have the same class but resolve their names elsewhere; measured unchanged, fixed separately.
g Fix generalizes across inputs (params/datatypes/wrappers)? Every constant that folds to an empty String is covered: '', concat('', ''), toNullable(''), toLowCardinality(''), a {db:String} parameter, a WITH alias (each measured). Non-empty names, currentDatabase(), REGEXP(...) and the one-argument form behave as before (measured).
h Backward compatible? (maintainer-approved exception only) Yes. A newer initiator sends an ordinary merge('<db>', re), which an older shard reads correctly (measured). A secondary query is left as sent, so an older initiator with a newer shard keeps working, with no NOT_FOUND_COLUMN_IN_BLOCK (measured). No setting, no protocol change.
i Invariants and contracts preserved? The tree names the database that was read, so receivers read the same tables and re-parse a tree that hashes like the initiator's (IN set names match). The replacement keeps the argument count and positions, so skipped-argument indexes stay valid, and re-resolving a bound node finds a non-empty name and changes nothing.

Session id: cron:clickhouse-impl-slot-6:20261114-025700

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b80e0b6]

Summary: ✅


AI Review

Summary

The PR binds the database resolved by merge into the query tree so distributed subqueries read the initiator's database when the database argument evaluates to an empty string. The current head also handles arguments represented by __getScalar, addressing the previous blocker, while preserving REGEXP arguments and the secondary-query guard. No remaining actionable findings. The updated 05300_merge_table_function_implicit_database_remote regression passes in the head's fast-test report.

Missing context / blind spots
  • ⚠️ The full CI suite is awaiting a rerun after resolution of the prior review thread; the available fast-test result does not establish its outcome.
Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 14, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b80e0b6c8 with master 253dc40d7 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.67 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.1 s +5.1 s (+253%)
Compile time of recompiled translation units

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

Job report

A database that evaluates to `''` is not always a `ConstantNode`: a `LowCardinality` scalar subquery,
`merge((SELECT toLowCardinality('')), re)`, stays a `__getScalar` call in the query tree, so the previous
check skipped it and the other servers again read their own default database (`0 1` instead of `5 2`
in an `IN` subquery, a wrong `JOIN` result, `NOT_FOUND_COLUMN_IN_BLOCK` over two shards).

For any database other than a `REGEXP`, the name `merge` resolved is the absolute database it read, so
it now replaces the database argument whatever its form. A `REGEXP` is the one form that is not
analyzed (`TableFunctionMerge::skipAnalysisForArguments`) and is kept. For a non-empty name the value
does not change; only the tree form does. The secondary-query guard is unchanged.

Found by the automated review of ClickHouse#131528.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit 2381469 Nov 16, 2026
402 of 403 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
…-remote

Needed by the next commit, which replaces the merge binder that ClickHouse#131528 changed.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
A table function that reads the current database, through a name without
a database (`loop(t)`, `dictionary('d')`, `timeSeriesSamples(ts)`) or
through '' (`mergeTreeIndex('', t)`), kept that argument as written in the
query tree. That tree is what remote(), Distributed, *Cluster and
parallel replicas send to other servers, and each of them resolved the
name in its own default database: an IN or JOIN subquery of a
distributed query read other rows or failed with UNKNOWN_TABLE.

As asked in
ClickHouse#131589 (comment),
the knowledge of which arguments name the database moves to the table
function, which computes it in parseArguments: the new virtual
ITableFunction::getQualifiedArguments returns the leading arguments with
that database written out, and QueryAnalyzer::resolveTableFunction
substitutes them in one place. This replaces the `merge` binder of ClickHouse#122985
and ClickHouse#131528 and the `loop` / `dictionary` binder of the first version of
this PR; StorageMerge::getSourceDatabaseNameOrRegexp, which only the
`merge` binder used, is removed. Calls already written that way keep
their nodes. The exclusions are unchanged: the table of remote() or
cluster(), a query printed from a resolved tree (serialize_query_plan
shard plans) and a secondary query.

Implemented by merge, loop, dictionary (a database name containing a dot
stays unqualified), mergeTreeIndex, mergeTreeAnalyzeIndexes,
mergeTreeCodecBlockCounts, mergeTreeTextIndex, mergeTreeProjection,
timeSeriesSamples / Tags / TimeRanges / MetricFamilies (and their
aliases), timeSeriesSelector, prometheusQuery and prometheusQueryRange.
The TimeSeries functions use the `num_table_arguments` names of ClickHouse#128194.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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.

merge('', regexp) still resolves against the shard's default database

3 participants