Skip to content

Send the temporary tables a query reads to the replicas of cluster table functions - #122791

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:cluster-functions-send-temporary-tables
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:cluster-functions-send-temporary-tables

Conversation

@groeneai

@groeneai groeneai commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122579

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):

Cluster table functions (s3Cluster, urlCluster, fileCluster, azureBlobStorageCluster, hdfsCluster, the data lake *Cluster functions, and url/s3 reads distributed by parallel_replicas_for_cluster_engines) now send the replicas the temporary tables the query refers to. Previously x IN (SELECT ... FROM tmp) over a temporary table returned an empty result, x IN tmp failed with UNKNOWN_IDENTIFIER, and INSERT ... SELECT from such a function with parallel_distributed_insert_select inserted nothing into a Replicated table or failed with UNKNOWN_TABLE for a Distributed one.

Description

On 26.8.10.6 and master, a query over a cluster table function that reads a temporary table in an IN subquery returns no rows at all, with no error:

CREATE TEMPORARY TABLE tmp (id UInt64) AS SELECT arrayJoin([2, 3]);
SELECT sum(n), count() FROM fileCluster('test_cluster_one_shard_three_replicas_localhost', 'f.tsv', 'TSV', 'n UInt64')
WHERE n IN (SELECT id FROM tmp); -- f.tsv holds 0..3: no row; file() gives 5 2

A cluster table function forwards the query text, and each replica resolves its tables itself. The three fan-outs whose source is a cluster table function (ReadFromCluster, and the parallel_distributed_insert_select paths into a Replicated/data lake table and into a Distributed table) passed an empty external-tables map, so the replica failed with UNKNOWN_TABLE, which the forced skip_unavailable_shards treats as a missing shard: every replica was dropped.

A helper, ClusterProxy::getExternalTablesUsedInQuery, returns the temporary tables whose names occur as identifiers in the forwarded query (a column of the same name counts too) or in an additional_table_filters value, also one set in a subquery's SETTINGS, and all three sites send them. Unlike Distributed (#43339), the other temporary tables are not sent: with an unrelated 200000-row one, the initiator sends 2942 bytes instead of 4803828.

The new test fails on master and passes here; each call site, the name filter and the additional_table_filters names have their own reference lines.

Not covered (each behaves as on master): non-Memory temporary tables (only Memory tables are sent, as documented), a temporary table read only by the stored query of a view (unless analyzer_inline_views = 1) or by a SQL UDF used in an additional_table_filters value or in an INSERT ... SELECT with parallel_distributed_insert_select, and INSERT ... SELECT whose source is a Distributed table or a parallel-replicas read (those fail loudly).


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

groeneai and others added 2 commits September 28, 2026 22:34
…ble functions

A cluster table function (`s3Cluster`, `urlCluster`, `fileCluster`, the data
lake ones, and a `url`/`s3` read converted by
`parallel_replicas_for_cluster_engines`) forwards the query text to every
replica, and each replica resolves the tables in it on its own. All three
fan-outs whose source is a cluster table function built their
`RemoteQueryExecutor`s with an empty external-tables map, so a temporary table
the query reads never reached the replicas:

- `ReadFromCluster::initializePipeline` (SELECT),
- `InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage`
  (`INSERT ... SELECT` with `parallel_distributed_insert_select` into a
  Replicated or data lake table),
- `StorageDistributed::distributedWriteFromClusterStorage` (the same into a
  `Distributed` table).

`x IN (SELECT ... FROM tmp)` then failed on the replica with `UNKNOWN_TABLE`,
which the forced `skip_unavailable_shards` hides, so every replica was dropped
and the query returned no rows at all; `x IN tmp` failed with
`UNKNOWN_IDENTIFIER`; the Replicated `INSERT ... SELECT` inserted nothing and
the `Distributed` one failed with `UNKNOWN_TABLE`.

Send each replica the temporary tables that the forwarded query names, via
one helper, `ClusterProxy::getExternalTablesUsedInQuery`, used at all three
sites. Only the named tables are sent, not `getExternalTables()` as a whole
(which is what the `Distributed` fan-out does, see ClickHouse#43339): shipping every
temporary table of the session would add its size times the replica count to
every cluster table function query. Measured with an unrelated 200000-row
temporary table: 2942 bytes sent by the initiator with this change, 4803828
when every temporary table is sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the doc comment of getExternalTablesUsedInQuery to one line and state the identifier-name match exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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; 1 finding, then 0 on a re-run against the corrected description) and my own cold review (1 note).

# Sev Finding Verdict Evidence / action
1 ❌ getExternalTablesUsedInQuery also sends a temporary table whose name matches a column or alias identifier of the forwarded query DISAGREE The SELECT path forwards the analyzer AST with qualified columns (sum(__table1.n), ColumnNode.cpp:111), so the example does not match a table n. Where a bare name does match (raw INSERT AST, lambda arguments), the same-named table is sent as well: results are the same, traffic stays below what Distributed sends. A table-position walk would have to follow the analyzer's resolution rules, and a miss brings back the empty result. The description states the name-based rule.
2 💡 A temporary table read only by an additional_table_filters value is still not sent (the setting is not part of the forwarded query) AGREE, not in this PR Same as master; listed under "Not covered" in the description.

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

Session id: cron:clickhouse-review-self-slot-58:20260929-010700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05292_cluster_table_function_temporary_tables fails on master every time (UNKNOWN_IDENTIFIER on IN tmp); statement by statement: no row for IN (SELECT ... FROM tmp), 0 rows for the Replicated INSERT ... SELECT, UNKNOWN_TABLE for the Distributed one. Same on 26.8.10.6.
b Root cause explained? The three fan-outs whose source is a cluster table function built their RemoteQueryExecutors with an empty external-tables map, so the replica cannot resolve the temporary table named in the forwarded text; its UNKNOWN_TABLE is hidden by the forced skip_unavailable_shards, so every replica is dropped.
c Fix matches root cause? Yes. The missing tables are supplied where the executors are built; no masking, retry or setting change.
d Test intent preserved / new tests added? New .sql test with one reference line per mechanism. Reverting each call site, or sending every temporary table instead of the named ones, reddens only that mechanism's lines.
e Both directions demonstrated? Yes: fails on a pristine build of the same tree, on the master snapshot and on 26.8.10.6; passes with the fix. 50 randomized, 50 default and 50 concurrent runs green.
f Fix is general across code paths? All three cluster-source fan-outs (SELECT, INSERT into Replicated/data lake, INSERT into Distributed) use one helper. The Distributed and parallel-replicas SELECT paths already send tables.
g Fix generalizes across inputs (params/datatypes/wrappers)? IN (subquery), NOT IN, IN tmp, GLOBAL IN tmp, an empty table; fileCluster, urlCluster and a url read converted by parallel_replicas_for_cluster_engines; LowCardinality(Nullable), Nullable, Array and tuple columns. No type logic in the change.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; external tables are part of the native protocol for every query kind.
i Invariants and contracts preserved? RemoteQueryExecutor copies the map and the storage pointers keep the tables alive; getExternalTables runs under the context's own lock with no other lock held, as in the Distributed path.

Session id: cron:clickhouse-impl-self-slot-57:20260928-210900

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e1a6d15]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Changed settings are not reflected in the settings changes history (see changed_settings.txt) FAIL cidb

AI Review

Summary

The PR forwards named temporary tables through the three cluster-storage fan-outs and adds regression coverage. Dependency discovery remains incomplete for SQL UDFs and subquery-local parser settings, leaving queries able to omit data silently. The previously reported view limitation also remains.

Missing context / blind spots
  • ⚠️ Review targets e1a6d15f3f5dd2a54039cdb804102c2382f95553; the modified local files match that PR diff. Current-head CI jobs are pending. The targeted regression passed 50 runs on fd370723a5de47d89d140894e086330f3aeb1e46, but those cases do not exercise the findings below.
  • ⚠️ Findings are based on current-code traces; no local executable is installed, and downloading the earlier CI binary returned HTTP 403. A current-head binary and focused distributed-query reproductions would close the runtime-validation gap.
Findings

❌ Blockers

  • src/Interpreters/InterpreterInsertQuery.cpp:1363: SQL UDF dependencies are discarded. Both optimized insert paths scan an unexpanded AST. With CREATE FUNCTION has_tmp AS x -> x IN (SELECT id FROM tmp), an insert from fileCluster filtered by has_tmp(n) contains no tmp identifier at this point. The replica expands the UDF after tmp has been omitted; the Replicated destination path can silently insert nothing because it enables skip_unavailable_shards. A UDF inside additional_table_filters is missed for the same reason. Expand UDF dependencies, including parsed filter expressions, before pruning, or conservatively retain the tables when dependencies are unresolved. New inline finding.
  • src/Interpreters/ClusterProxy/executeQuery.cpp:379: Dependency discovery uses different parser limits from execution. Nested additional_table_filters values are parsed with the outer settings, ignoring the subquery's effective max_parser_depth, max_parser_backtracks, and max_query_size. A filter accepted under raised subquery-local limits can fail this scan; the exception is swallowed and its temporary table is removed, although the replica can parse the filter. Apply the effective settings at each query scope before collecting dependencies. Existing thread; no duplicate comment posted.

⚠️ Majors

Tests
  • ⚠️ Add focused cases comparing a direct temporary-table predicate with its SQL UDF equivalent for both optimized insert destinations and for additional_table_filters.
  • ⚠️ Add a nested filter whose parsing requires raised subquery-local limits and assert the actual returned rows. The existing nested-settings case uses the outer parser limits successfully and cannot detect this omission.
Final Verdict

Status: ❌ Block. Preserve dependencies introduced by SQL UDF expansion and effective nested settings, with focused regression coverage. The documented view limitation should also stop producing silent empty results.

@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-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e1a6d15f3f5dd2a54039cdb804102c2382f95553 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

The replicas of a cluster table function apply `additional_table_filters`
themselves (the setting travels in the settings packet), so a filter such as
`{'_table_function.fileCluster': 'n IN (SELECT id FROM tmp)'}` reads `tmp` on
the replica. `getExternalTablesUsedInQuery` looked only at the identifiers of
the forwarded query and dropped `tmp`: the subquery form returned no rows (the
forced `skip_unavailable_shards` ignores the replicas' `UNKNOWN_TABLE`),
`n IN tmp` failed with `UNKNOWN_IDENTIFIER`, and the
`parallel_distributed_insert_select` paths inserted nothing into a Replicated
table or failed with `UNKNOWN_TABLE` for a `Distributed` one.

Also keep a temporary table whose name occurs anywhere in the text of an
`additional_table_filters` value. The text is not parsed: parsing every entry
would reject a query over an entry for another table that exceeds
`max_parser_depth` or `max_parser_backtracks`, an entry that is never parsed
today. A name that only occurs as a substring sends one table too many, never
one too few (short of an identifier spelled with escape sequences).

Review: ClickHouse#122791 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`getExternalTablesUsedInQuery` kept a temporary table when its name occurred
anywhere in the text of an `additional_table_filters` value, so a name inside a
string literal or inside another identifier (`t` in `status`) was enough to send
the whole table to every replica. Parse each value and collect its identifier
names instead, the same rule as for the forwarded query.

Every entry is still considered, not only the one keyed by the cluster table
function: a replica applies the entries of every table it reads, including the
tables of subqueries and of views, and a table it misses brings back the empty
result. For the same reason the values set in the `SETTINGS` of a subquery are
read too; they are part of the forwarded query, not of the context.

An entry that does not parse contributes no names and does not fail the query,
because a replica that applies it fails to parse it as well, whatever is sent;
`LOGICAL_ERROR` and `MEMORY_LIMIT_EXCEEDED` are still rethrown.

Review: ClickHouse#122791 (comment)

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

Copy link
Copy Markdown
Collaborator Author

@devcrafter one design choice for this PR: the replicas resolve temporary tables by name, so it sends only the ones named in the forwarded query or in additional_table_filters. A temporary table read only by the stored query of a view (CREATE VIEW v AS SELECT id FROM tmp) is still not sent, and ... WHERE n IN (SELECT id FROM v) returns no rows, as on master. I can (A) keep the name filter and leave views as listed under "Not covered", or (B) send every Memory temporary table as Distributed does, which covers views but has the #43339 cost (4803828 instead of 2942 initiator bytes with an unrelated 200000-row table). Which do you prefer?

{
if (const auto * set_query = ast.as<ASTSetQuery>())
if (const auto * additional_filters = set_query->changes.tryGet("additional_table_filters"))
collectAdditionalFiltersIdentifierNames(SettingFieldMap(*additional_filters).value, settings, names);

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.

collectNestedAdditionalFiltersIdentifierNames reuses the outer settings here, but a subquery runs under its own SETTINGS context (ApplyWithSubqueryVisitor::getSubqueryContext applies those changes before analysis). That means a query whose only reference to tmp is inside a subquery-local additional_table_filters entry that needs a raised max_parser_depth / max_parser_backtracks still drops tmp: this helper parses the filter under the outer limits, suppresses that parse failure, and erases the table, while the replica can parse and apply the same filter under the subquery-local limits.

Can we parse a nested additional_table_filters value under the ASTSetQuery's effective parser settings and add a regression for that shape?

return external_tables;

IdentifierNameSet names;
query->collectIdentifierNames(names);

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.

query->collectIdentifierNames only sees the forwarded SQL AST. With the default analyzer_inline_views = 0, a view that exists on the replicas but whose stored query reads a temporary table still contributes only the view name here, so tmp gets erased below and the shard returns the same silent empty result this PR is trying to fix.

For example, a replicated / ON CLUSTER view v AS SELECT id FROM tmp, then ... WHERE n IN (SELECT id FROM v) over fileCluster(...), still depends on tmp even though the forwarded query text names only v. If the contract is "send the temporary tables the query reads", this helper still needs to follow view expansion as well, or conservatively stop pruning when an unresolved view is referenced.

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f9a1e830-f5ce-42f1-9f75-f16aba73c4fa
  • MIRAI run: b0c3660f-6f56-4fe6-844b-681d18619b1c
  • PR check IDs:
    • clickbench_2674054_1790834471
    • clickbench_2674171_1790834498
    • clickbench_2674185_1790834499
    • tpch_adapted_1_official_2674383_1790834515
    • tpch_adapted_1_official_2674486_1790834526
    • tpch_adapted_1_official_2674549_1790834528

select_to_send.list_of_selects->children.at(0), src_snapshot, local_context, src_storage_cluster->getClusterName());
}

const Tables external_tables = ClusterProxy::getExternalTablesUsedInQuery(query_to_send, local_context);

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.

Include SQL UDF dependencies before pruning temporary tables.

This call inspects the unexpanded INSERT AST. Unlike the regular SELECT path, neither optimized insert path replaces SQL UDF calls with their analyzed bodies before calling getExternalTablesUsedInQuery. For example, after CREATE FUNCTION has_tmp AS x -> x IN (SELECT id FROM tmp), an INSERT INTO dst SELECT n FROM fileCluster(...) WHERE has_tmp(n) SETTINGS parallel_distributed_insert_select = 2 contains no tmp identifier in the scanned AST. The helper removes tmp, so the replicas fail to resolve it; the Replicated destination path enables skip_unavailable_shards and can report success while inserting nothing.

The filter scan has the same gap: parsing an additional_table_filters value of has_tmp(n) collects n, while the replica's analyzer later expands the UDF and reads tmp.

Please expand SQL UDF dependencies on a copy of both the forwarded AST and parsed filter ASTs before pruning, with recursion protection, or preserve external tables when dependencies cannot be established. Add a focused regression using the same predicate directly and through a SQL UDF for the optimized insert paths and an additional filter.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e1a6d15

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
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history not PR-caused: since v26.10.2.103-stable was published, every PR reports use_query_condition_cache_for_time_conditions 1 vs 0 #127687 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261024-093006

This branch has not been deployed

No deployments
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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants