Skip to content

Fix the one-argument merge table function reading the default database of other servers in distributed queries - #122985

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-table-function-implicit-database-remote
Nov 13, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-table-function-implicit-database-remote

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122931 (comment)

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 one-argument form of the merge table function, merge('regexp'), in a subquery, a JOIN or a CTE of a query that is sent to other servers (remote, cluster, a Distributed table, *Cluster table functions, parallel replicas): those servers matched the regexp against 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.8.2.7 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` when `default` has a matching table with 0 in it;
-- `merge(currentDatabase(), '^t_')` returns the expected `5 2`

The analyzer resolves merge('regexp') against the current database, but keeps the single argument in the query tree. So the query sent to another server says merge('regexp'), and that server resolves it against its own default database (the session database is not sent, on purpose).

QueryAnalyzer::resolveTableFunction now adds the resolved database as the first argument of the node. It goes into the query tree, not only into the sent text, because IN set names are hashed from the tree and must match between the initiator and the shards: a text-only change fails countIf(x IN (SELECT ... FROM merge('regexp'))) over two shards with NOT_FOUND_COLUMN_IN_BLOCK (measured). A secondary query keeps the form it was sent in, so an older initiator keeps working with a newer shard (without that condition the same query fails). This is the resolve-time part of #110972, which was closed when #115001 superseded it.

The new test covers remote with IN, a CTE, a JOIN, countIf over two shards, and fileCluster; each query fails on master and passes here. Also measured: a Distributed table, cluster(), parallel replicas and serialize_query_plan.

Not changed: loop(t), dictionary('d') and joinGet('t', ...) in a query sent to another server are resolved in its default database too.


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

Version info

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

groeneai and others added 2 commits September 29, 2026 22:12
`merge('regexp')` takes its database from the current database of the
server that resolves it. The analyzer resolved the node with the
initiator's current database but kept the single argument in the query
tree, so every rendering of the query for another server (Distributed,
remote, cluster, `*Cluster` table functions, query-based parallel
replicas, serialized plans) sent `merge('regexp')`, and the receiver
matched the regexp against its own default database: wrong rows, or
CANNOT_EXTRACT_TABLE_STRUCTURE when that database has no matching table.

After resolving a one-argument `merge`, insert the source database as
the first argument of the node. The change is made in the query tree and
not only in the rendered text, because an `IN` set is named after the
tree hash of its subquery and that name appears in the columns of the
WithMergeableState header that the initiator matches by name: with a
render-only change, `countIf(x IN (SELECT ... FROM merge('re')))` over
two shards fails with NOT_FOUND_COLUMN_IN_BLOCK.

A secondary query keeps the form it was sent in, so that its tree hashes
like the sender's: an initiator of an older version sends one argument,
and a receiver that inserted the database would fail the same way.

This is the resolve-time part of ClickHouse#110972, which ClickHouse#115001 superseded
without carrying it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the clause narrating the inserted argument and state the secondary-query condition as one invariant line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 29, 2026
@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 review of the same head (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 The header comment of 04836_merge_table_parallel_replicas_duplicate_announcement.sh (lines 10-12) says that a one-argument merge resolves against the default database on each hop, which this PR changes AGREE, not changed here The test keeps passing, because it runs USE default; the file is outside this diff

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260929-221600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With a current database other than default, each of the 5 fan-out queries of the new test fails with CANNOT_EXTRACT_TABLE_STRUCTURE raised by the remote server, every run, or returns wrong rows (0 1 instead of 5 2) when default has a matching table. Same on 26.8.2.7.
b Root cause explained? merge('regexp') is resolved with the initiator's current database, but the query tree keeps the single argument, so every server the query is sent to re-resolves merge('regexp') against its own default database.
c Fix matches root cause? Yes: the resolved database is written into the query tree where the node is resolved, so the initiator's tree, the sent text and the receiver's re-parse all carry it. One site covers remote, cluster, Distributed, *Cluster functions, parallel replicas and serialized plans (each measured).
d Test intent preserved / new tests added? New test 05300_merge_table_function_implicit_database_remote: IN subquery, CTE, JOIN, countIf over two shards, fileCluster; each query fails without the fix.
e Both directions demonstrated? Without the fix: 5/5 randomized runs fail. With it: 50/50 randomized runs and 50/50 with -j 8 pass.
f Fix is general across code paths? It applies to every merge node the analyzer resolves (subqueries, CTEs, JOIN, merge nested in a non-remote table function). merge nested in remote/cluster stays unresolved on the initiator by design. loop, dictionary and joinGet have the same class but resolve their names their own way; unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Constant and constant-expression regexps, empty regexp, _database/_table virtual columns; the two-argument forms are untouched, and invalid one-argument forms still throw before the change applies. The arguments are String constants, so no type wrappers apply.
h Backward compatible? (maintainer-approved exception only) Yes. An older initiator with a newer shard works because a secondary query keeps the form it was sent in (without that condition the query fails with NOT_FOUND_COLUMN_IN_BLOCK); a newer initiator sends the two-argument form, which every version parses. No setting, no format change.
i Invariants and contracts preserved? A resolved table expression is sent in a form that re-resolves to the same tables and re-parses into a tree that hashes like the initiator's, so IN set names match in the shards' headers (a text-only variant breaks this, measured). The database is added only when the node has one argument, so re-resolving a node does not add it twice, and no skipped-argument index can precede it.

Session id: cron:clickhouse-impl-slot-6:20260929-213700

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad1a658]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 29, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ad1a658e0 with master 9b41283be (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.61, programs/clickhouse-keeper ×0.66 (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.5 s +5.5 s (+267%)
Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b8a7c50

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / space_filling_curve #4 dashboard confirmed_regression, client_time 0.794 -> 0.918 s (+15.6%), still +13.5% after the harness restarted both servers; the shard's own report does not flag it. The query is SELECT sum(mortonEncode(toUInt32(number), toUInt32(number * 3))) FROM numbers(200000000), which does not use the merge table function, the only code path this PR changes. On arm this query has a slow mode of about +14% that some builds draw and others do not, official master builds included: of 568 master builds measured at least 4 times in 30 days, 36 were slow in every run. On this master base the reference build was fast and 4 of 23 PR builds drew the slow mode, this one included a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (the same owner as the row above)

146 of 146 check runs completed (106 passed, 39 not selected, 1 red: the shard above), Finish Workflow is green and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260930-033029

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the arm_release 4/6 perf red (space_filling_curve #4): #123354 (merged 2026-10-02), which changed the mortonEncode loop this query runs. Since 2026-10-04, 3 of 1909 arm runs of the query moved more than 10% either way, against 10 to 165 a day in the week before. This head predates it.

@PedroTadim PedroTadim self-assigned this Nov 12, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ Reviewed, @groeneai — correct and well-targeted fix. CI all-green. ✅ Approve.

The fix rewrites the one-argument merge('^t') into the explicit two-argument merge('<currentdb>', '^t') during analysis on the initiator, so the resolved current database travels with the serialized query tree instead of each remote resolving merge('^t') against its own default database. I verified:

  • Guards are right. typeid_cast<const StorageMerge *> + getArguments().size() == 1 targets exactly the implicit-database form (the 2-arg merge('db','^t') and merge(REGEXP('^db'),'^t') forms are untouched), and getSourceDatabaseNameOrRegexp() returns the resolved current database for that form (parseArguments: source_database_name_or_regexp = context->getCurrentDatabase() when args.size() == 1).
  • IN-set hash consistency holds. The query_kind != SECONDARY_QUERY guard is the key subtlety: the initiator rewrites before computing/serializing, and the secondary (which receives the already-explicit 2-arg form, and is guarded anyway) does not re-rewrite — so the distributed IN-set hashes match. The countIf(... IN (SELECT … FROM merge(…)))-over-two-shards test exercises exactly this.
  • Scope is complete. Being in resolveTableFunction, it covers every distribution path (remote/cluster/Distributed/*Cluster/parallel replicas) and every placement (subquery, JOIN, CTE), which the test covers. The local case is unaffected (rewrites to the same current db).

💡 Nit (optional, defensive)

The argument is inserted at the front after skip_analysis_arguments_indexes is computed. It's safe today — for the 1-arg form TableFunctionMerge::skipAnalysisForArguments returns [] (it only skips REGEXP(...) function nodes, and the 1-arg table-regexp is a string literal; a merge(REGEXP(...)) single arg would error in parseArguments before this code runs). But the ordering is a latent fragility: if merge ever skipped a positional index for the 1-arg form, the front-insert would misalign it. Inserting before computing the skip indices (or documenting the invariant) would be more robust.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes. Today's master still resolves a one-argument merge against the receiving server's default database.

  • Bugfix validation on your master merge (ad1a658) ran the new test on the master build 26.11.1.2098, and it fails there with Code: 636 CANNOT_EXTRACT_TABLE_STRUCTURE from the replica for ... IN (SELECT x FROM merge('^t_implicit_db_')) (amd64 report).
  • Locally on master 7a987ba, with session database db_init, db_init.foo_a = (2), (3) and default.foo_b = (0): SELECT sum(number), count() FROM remote('127.0.0.2', numbers(4)) WHERE number IN (SELECT x FROM merge('^foo')) returns 0 1 instead of 5 2. The CTE, JOIN and two-shard countIf forms are wrong the same way. merge(currentDatabase(), '^foo') and the local read return 5 2.

On the nit, I kept the order. For a one-argument call, index 0 can enter the skip set only as REGEXP(...), an argument that fails to resolve, or a nested table function. Each of those throws in the parseArguments call that runs before executeTableFunction, so the set is empty whenever the insertion runs. Measured on master: merge(REGEXP('^foo')), merge(view(SELECT '^foo')) and merge(concat(no_such_column, '^foo')) all fail in TableFunctionMerge::parseArguments.

Not covered by this PR, same query shape on today's master: loop(foo_a) and dictionary(d) with an unqualified name in the IN subquery also return 0 1 instead of 5 2. A plain foo_a reference returns 5 2.

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 1f096f1 Nov 13, 2026
203 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
lazerg pushed a commit to lazerg/ClickHouse that referenced this pull request Nov 16, 2026
… 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 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). groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR 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.

4 participants