Skip to content

Fix scalar subqueries in table function arguments in CREATE TABLE ... AS SELECT - #110254

Merged
CheSema merged 4 commits into
masterfrom
fix-scalar-subquery-table-function-args
Jul 23, 2026
Merged

CheSema merged 4 commits into
masterfrom
fix-scalar-subquery-table-function-args

Conversation

@CheSema

@CheSema CheSema commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

A scalar subquery used as an argument of a table function worked in a plain SELECT but failed when the same query was wrapped in CREATE TABLE ... AS SELECT:

CREATE TABLE path_table ENGINE = MergeTree ORDER BY () AS
SELECT 'http://localhost:11111/test/a.tsv' AS s3path;

-- works
WITH (SELECT s3path FROM path_table) AS p
SELECT * FROM s3(p, NOSIGN, 'TSV');

-- Code: 36. DB::Exception: Host is empty in S3 URI. (BAD_ARGUMENTS)
CREATE TABLE s3_table ENGINE = MergeTree ORDER BY () AS
WITH (SELECT s3path FROM path_table) AS p
SELECT * FROM s3(p, NOSIGN, 'TSV');

CREATE TABLE ... AS SELECT infers the structure of the SELECT in only-analyze mode. In that mode the analyzer does not execute scalar subqueries and replaces them with type-only placeholder values (see evaluateScalarSubqueryIfNeeded). But table functions are resolved into storages even in only-analyze mode — the storage is required to infer the query header — so the placeholder reached the table function: s3 received an empty URL. The bug is not specific to s3: any table function taking a path or URL from a scalar subquery is affected (file reads from an empty path, for example).

Now scalar subqueries are executed for real while table function arguments are being resolved, even in only-analyze mode. The executed scalar is cached in the query context, so it is not recomputed when the query is executed after analysis.

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

Fix Host is empty in S3 URI error when a scalar subquery is used as the URL argument of the s3 table function (or as an argument of any other table function) in CREATE TABLE ... AS SELECT queries: scalar subqueries in table function arguments are now evaluated during query analysis.

Version info

  • Merged into: 26.7.1.1375 (included in 26.7 and later)

… in only-analyze mode

`CREATE TABLE ... AS SELECT` infers the structure of the `SELECT` in
only-analyze mode, where the analyzer replaces scalar subqueries with
type-only placeholder values instead of executing them. But table
functions are resolved into storages even in only-analyze mode (the
storage is needed to infer the header), so the placeholder reached the
table function: `s3` got an empty URL and failed with `Host is empty
in S3 URI`, while the same `SELECT` worked on its own.

Execute scalar subqueries for real while table function arguments are
being resolved, even in only-analyze mode.
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9887ae3]

Summary: ✅


AI Review

Summary

This PR fixes the main CREATE TABLE ... AS SELECT failure where a table function saw only-analyze placeholders instead of the real scalar-subquery result. The core idea is reasonable, but I do not think the implementation fully satisfies the broader contract in the PR description: two existing analyzer paths still serialize placeholder values or skip the scalar entirely, so I would keep this at request-changes.

Findings

⚠️ Majors

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:4565][dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/110254#discussion_r3623745828] The new table_function_arguments_in_resolve_process scope only helps scalar subqueries that the initiator actually reaches before resolveTableFunction falls back on UNKNOWN_IDENTIFIER. resolveExpressionNodeList is left-to-right, so an argument like remote(..., cityHash64(concat(toString(x), (SELECT ...)))) still throws on x first, hits the fallback, and returns the raw subtree without ever evaluating the trailing scalar during analysis. That means the changelog/body claim for “any other table function argument” is still false for mixed remote/local expressions: a scalar that must be resolved on the initiator (for example one reading a session temporary table or other initiator-only state) is still order-dependent here.
    Suggested fix: once this fallback path is chosen, do a second walk over the skipped subtree in a mode that executes scalar subqueries but tolerates unresolved identifiers, or otherwise reorder this path so scalar subqueries are resolved before ordinary identifiers.
  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:4502][dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/110254#discussion_r3630666453] Parameterized-view argument collection still happens before the new “execute scalars for real” scope begins, so a scalar parameter is serialized from an only-analyze placeholder and fed directly into buildParameterizedViewStorage. The added test proves that predicate-only parameters still populate the right rows, but it does not cover schema-sensitive parameter use. Query parameters are substituted as ordinary literals everywhere, including positions such as CAST(value, {type_name:String}) or tupleElement(tuple, {i:UInt8}), where the parameter value changes header inference itself. In those cases CTAS can still infer the wrong schema or fail during analysis even though the real execution would succeed with the actual scalar value.
    Suggested fix: either collect parameterized-view arguments under the same real-scalar mode, or defer buildParameterizedViewStorage until the non-only_analyze pass that actually populates the destination table.
Tests
  • ⚠️ Add a CTAS regression where a skipped remote/cluster argument hits UNKNOWN_IDENTIFIER before a later scalar that must be evaluated on the initiator.
  • ⚠️ Add a CTAS regression over a parameterized view whose parameter affects the projected type/header, not just row filtering.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@novikd novikd self-assigned this Jul 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Your PR was poisoned by the test 02346_text_index_bug108519_qcc_skip_index. It is fixed in master. Please update the branch.

/// into storages even in only-analyze mode (the storage is required to infer the query
/// header), so scalar subqueries in their arguments must be executed for real instead of
/// being replaced with type-only placeholders. See evaluateScalarSubqueryIfNeeded.
bool table_function_arguments_in_resolve_process = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This field is not needed. You can just check if there is TableFunctionNode in the expressions_in_resolve_process_stack or equivalent

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Also, table_expressions_in_resolve_process could be used

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.

Both options are not better:

  • expressions_in_resolve_process_stack -- would not wok, a TableFunctionNode is never pushed onto it
  • table_expressions_in_resolve_process -- is per scope, so in the query SELECT * FROM (SELECT (SELECT 1)) x JOIN url('http://...', 'CSV', 'a UInt8') y ON 1 for the left part (SELECT 1) would be executed for real in only-analyze mode.

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.

It is possible to add a push to the resolveExpressionNode stack for expressions in the resolve process, but it would create a really big difference that I could not comprehend due to my limited knowledge of the analyzer.

auto skip_analysis_arguments_indexes = table_function_ptr->skipAnalysisForArguments(table_function_node, scope_context);

bool previous_table_function_arguments_in_resolve_process = table_function_arguments_in_resolve_process;
table_function_arguments_in_resolve_process = true;

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.

This flag now covers arguments that resolveTableFunction only probes speculatively and then abandons on the existing UNKNOWN_IDENTIFIER fallback (remote(..., cityHash64(key)), concat(x, (SELECT 1)), etc.). In only_analyze mode that means we eagerly execute scalar subqueries even when the whole argument is later skipped as opaque to the initiator. A concrete repro is CREATE TABLE dst ENGINE = Memory AS SELECT * FROM remote('localhost', view(SELECT 2 AS x), cityHash64(assumeNotNull((SELECT number FROM numbers(2)) + x)));: resolveExpressionNodeList visits (SELECT number FROM numbers(2)) before x, so this change throws INCORRECT_RESULT_OF_SCALAR_SUBQUERY during header inference instead of leaving a typed placeholder and letting StorageDistributed build the header. The “execute for real” mode needs to be scoped to arguments that actually survive resolution, or the original subtree has to be restored when the UNKNOWN_IDENTIFIER path is taken.

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.

The mechanism is right: the flag also covers arguments that the UNKNOWN_IDENTIFIER fallback later abandons, and the scalar is resolved before the identifier fails, so an invalid scalar now throws during header inference. But this does not regress any working query — the same repro already fails on master in every phase, because non-only-analyze resolution executes the scalar in the same order:

  • plain SELECT * FROM remote('localhost', view(SELECT 2 AS x), cityHash64(assumeNotNull((SELECT number FROM numbers(2)) + x))) fails with INCORRECT_RESULT_OF_SCALAR_SUBQUERY on 26.6.2 (which includes the fallback from 5a2fea1);
  • the CREATE TABLE ... AS form passes analysis on master but then fails at execution with THERE_IS_NO_QUERY ("query context has expired").

So this change moves the failure earlier and replaces THERE_IS_NO_QUERY with the accurate error, before the table is created. The residual cost is eagerly executing a scalar inside an argument that ends up skipped — the same work execution already performs for the same query. Scoping real execution to arguments that survive resolution would require resolving the argument twice, since executing the scalar is part of resolving it; that seems disproportionate for a pattern that already fails.

Added 04614_scalar_subquery_in_skipped_table_function_argument pinning both behaviors: the single-row scalar in a skipped argument keeps working (SELECT and CTAS), and the multi-row scalar fails with INCORRECT_RESULT_OF_SCALAR_SUBQUERY in both.

…lved

A sharding key referencing a remote-side column is kept unresolved by the
`UNKNOWN_IDENTIFIER` fallback in `resolveTableFunction`. Scalar subqueries
inside such an argument are executed before the fallback fires: a single-row
scalar keeps working (the argument is still delegated to the remote side),
while a multi-row scalar fails with `INCORRECT_RESULT_OF_SCALAR_SUBQUERY` -
now also during `CREATE TABLE ... AS SELECT` header inference, where it
previously failed at execution time with `THERE_IS_NO_QUERY`.
auto skip_analysis_arguments_indexes = table_function_ptr->skipAnalysisForArguments(table_function_node, scope_context);

bool previous_table_function_arguments_in_resolve_process = table_function_arguments_in_resolve_process;
table_function_arguments_in_resolve_process = true;

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.

The new table_function_arguments_in_resolve_process scope starts only here, after the parameterized-view fallback above has already resolved and serialized pv(...) arguments. In CREATE TABLE ... AS SELECT, resolveExpressionNode(nodes[1], ...) at 4502-4528 still runs scalar subqueries in only_analyze mode there, so buildParameterizedViewStorage bakes the sample-block default into the synthesized StorageView.

That turns this into a wrong-result path, not just a missing edge case. The plain-SELECT behavior already covered by 03209_parameterized_view_with_non_literal_params.sql should also work under CTAS:

CREATE TABLE dst ENGINE = Memory AS
SELECT id FROM date_pv(dtparam = (SELECT dt FROM date_table_pv WHERE id = 2));

With the current code, analysis can freeze dtparam to the default Date instead of the scalar result, so dst is populated from the wrong parameterized view instance. The same “execute scalar for real” mode needs to cover parameterized-view argument collection too, or the storage build has to be deferred until real execution.

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.

The ordering is right — the parameterized-view branch resolves and serializes pv(...) arguments before the new scope starts, so under only_analyze a scalar parameter is serialized from the type-only placeholder into the synthesized StorageView. But that storage is used only to infer the header, which does not depend on the parameter value (parameters are typed); the table is populated by a fresh non-only-analyze analysis of the INSERT SELECT, where the scalar is executed for real and the correct view instance is built. There is no wrong-result path: the suggested repro returns the correct row (2, not the default-Date instance) in plain SELECT, CREATE TABLE ... AS SELECT, and CREATE VIEW over it — including on 26.6.2, since this branch is not modified by this PR at all.

Extending the "execute for real" scope to parameterized-view argument collection would make DESCRIBE/EXPLAIN of pv((SELECT ...)) execute subqueries with no observable benefit, so leaving that path as is. Added 04615_parameterized_view_scalar_subquery_param_ctas pinning that CTAS over a parameterized view with a scalar parameter is populated from the correct view instance.

The view storage synthesized during only-analyze header inference of
`CREATE TABLE ... AS SELECT` serializes a placeholder parameter value
(`resolveTableFunction` collects `pv(...)` arguments before scalars are
executed for real), but that storage is only used to infer the header;
the population runs a fresh non-only-analyze analysis with the real
scalar value. Pin that the populated rows come from the correct view
instance.
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 23/23 (100.00%) · Uncovered code

Full report · Diff report

@CheSema
CheSema added this pull request to the merge queue Jul 23, 2026
Merged via the queue into master with commit 93bef07 Jul 23, 2026
180 checks passed
@CheSema
CheSema deleted the fix-scalar-subquery-table-function-args branch July 23, 2026 09:14
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 23, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ery-table-function-args

Fix scalar subqueries in table function arguments in CREATE TABLE ... AS SELECT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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