Skip to content

Fix distributed INSERT ... SELECT FROM cluster functions ignoring column DEFAULT expressions - #127657

Merged
skuznetsov-clickhouse merged 4 commits into
masterfrom
fix-cluster-insert-select-keep-auto-structure
Oct 26, 2026
Merged

skuznetsov-clickhouse merged 4 commits into
masterfrom
fix-cluster-insert-select-keep-auto-structure

Conversation

@devcrafter

@devcrafter devcrafter commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Related: #120488
Related: #121070

A distributed INSERT ... SELECT FROM s3Cluster(...) (and the other object storage cluster functions, or a plain s3 converted by parallel_replicas_for_cluster_engines) into a replicated table with parallel_distributed_insert_select = 2 (the default), or into a Distributed table, silently wrote 0, '' or 1970-01-01 instead of the DEFAULT expressions of the destination table for fields missing in the source files. No error is raised. When a TTL depends on such a column, the rows are expired right after insertion.

The cause is #120488, which started to apply IStorageCluster::updateQueryToSendIfNeeded to the forwarded INSERT (#121070 did the same for a Distributed destination). Besides renaming the function to its *Cluster variant, which is what fixed the duplicate inserts, it adds the structure of the source storage to the arguments in place of an omitted or 'auto' structure. That structure has names and types only. Before, the forwarded query was sent as written, and every node took the structure from the insertion table (use_structure_from_insertion_table_in_table_functions), which carries the DEFAULT expressions, so the missing fields got their defaults.

updateQueryToSendIfNeeded now has an add_structure_and_format argument. IStorageCluster::read still adds the structure and format, because the initiator merges the streams of the nodes and needs them to produce its header. The two INSERT ... SELECT paths skip that step: only the rename to the *Cluster variant and the cluster name argument are applied, and all other arguments reach the nodes as written, as before #120488. Every node inserts on its own and only reports progress, so there is no header to agree on.

An earlier version of this PR passed 'auto' as the structure instead. That still rewrote the arguments and replaced an explicit structure = '...' key-value argument with 'auto', so a node could infer a different type than the query gave; skipping the step entirely avoids changing anything that was not changed before #120488.

Notes

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 INSERT INTO <replicated or Distributed table> SELECT ... FROM s3Cluster(...) (and other object storage cluster table functions, or s3 converted to s3Cluster by parallel replicas) writing the default values of the column types (0, empty string, 1970-01-01) instead of the DEFAULT expressions of the destination table for fields missing in the source files.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.782-master (included in 26.11 and later)
  • Backported to: 26.10.3.7, 26.9.26.20, 26.8.35.16

…er functions

The forwarded `INSERT ... SELECT` used to carry the names-and-types structure
of the source storage instead of `'auto'`, so the nodes did not take the
structure from the insertion table and filled fields missing in the files
with the default values of their types instead of the `DEFAULT` expressions
of the destination table.

Related: #120488
Related: #121070

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f3abf4e]

Summary: ✅


AI Review

Summary

This PR restores destination DEFAULT expressions for missing source fields in distributed INSERT ... SELECT by omitting source schema injection. Review of head f3abf4e536a00c45ca5010ef6cb07cbdb667ed36 retains one existing correctness blocker: the same change also removes initiator-side argument evaluation, allowing workers to read a different source. The earlier explicit keyword structure issue is fixed; no new inline findings were identified.

Findings

❌ Blockers

  • Preserve initiator-side source argument evaluation — src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp:449–450,476–477. Both distributed insert callers pass add_structure_and_format = false, skipping the helper that also replaces positional expressions with literals. TableFunctionObjectStorage::parseArguments evaluates a clone, so the forwarded query still contains expressions such as getMacro('ingest_url'). If that macro selects bucket A on the initiator and bucket B on a worker, the initiator assigns object keys from A but the worker opens them using B's connection configuration, silently inserting the wrong rows. An initiator-only macro instead causes the insert to fail. This affects both replicated and Distributed destinations, including automatically converted s3 sources. The current code still has both guards; the existing review discussion also records a reproduction with three server processes. Required fix: preserve initiator-side positional argument materialization independently of schema injection while retaining omitted/'auto' structures and explicit user schemas. Keep the existing thread open; no duplicate comment is needed.
Tests
  • ⚠️ Add a focused regression with separate initiator and worker processes whose source URL macros differ, asserting that workers read the initiator's bucket and still apply destination DEFAULT expressions. Include an initiator-only macro case. The new 05446_insert_select_cluster_function_column_defaults test routes every cluster entry to the same server, so it cannot detect this regression.
Missing context / blind spots
  • ⚠️ No local runtime tests were run during this review. The retained finding is supported by current-source tracing and the existing review's reported runtime reproduction; a run of the focused regression on the current head would close this gap.
Final Verdict

Status: ❌ Block. Preserve initiator-side argument evaluation and add the focused regression above before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 23, 2026
@devcrafter devcrafter added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 23, 2026
@devcrafter
devcrafter requested review from azat and groeneai and a balanced review from Copilot October 23, 2026 23:00

Copilot AI left a comment

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.

🟡 Changes recommended

Forwarded S3 inserts overwrite explicit key-value structures with auto, changing source parsing and default-value semantics.

1 open issue
What changed in this PR

This PR restores destination-column DEFAULT expressions for distributed INSERT ... SELECT from cluster table functions, addressing regressions introduced by #120488 and #121070.

Changes:

  • Adds forward_structure to distinguish reads requiring a shared schema from independently executed inserts.
  • Keeps automatic structure resolution for forwarded inserts while preserving cluster-function rewriting.
  • Adds stateless regression coverage for S3 and URL sources with replicated and Distributed destinations.
File Description
tests/​queries/​0_stateless/​05446_insert_select_cluster_function_column_defaults.sh Tests missing-field defaults across distributed insert paths.
tests/​queries/​0_stateless/​05446_insert_select_cluster_function_column_defaults.reference Records expected default and explicit field values.
src/​Storages/​StorageURLCluster.h Extends the URL rewrite interface.
src/​Storages/​StorageURLCluster.cpp Makes URL structure forwarding conditional.
src/​Storages/​StorageFileCluster.h Extends the file rewrite interface.
src/​Storages/​StorageFileCluster.cpp Makes file structure forwarding conditional.
src/​Storages/​StorageDistributed.cpp Disables structure forwarding for distributed inserts.
src/​Storages/​ObjectStorage/​StorageObjectStorageCluster.h Extends the object-storage rewrite interface.
src/​Storages/​ObjectStorage/​StorageObjectStorageCluster.cpp Makes object-storage structure forwarding conditional.
src/​Storages/​IStorageCluster.h Defines and documents the structure-forwarding flag.
src/​Storages/​IStorageCluster.cpp Keeps structure forwarding enabled for reads.
src/​Interpreters/​InterpreterInsertQuery.cpp Disables structure forwarding for replicated-table and data-lake inserts.

Review effort: Balanced


ASTs & args = expression_list->children;
const auto & structure = storage_snapshot->metadata->getColumns().getAll().toNamesAndTypesDescription();
const String structure = forward_structure ? storage_snapshot->metadata->getColumns().getAll().toNamesAndTypesDescription() : "auto";
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Oct 23, 2026

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I reproduced the line 389 finding on a local debug build of bbc1d71, and it is a regression against master: with parallel_distributed_insert_select = 2, a key-value structure = '...' reaches the nodes as structure = 'auto'. Only the key-value branch of the S3 helper overwrites an explicit structure; its positional branches, the named-collection branch, Azure and HDFS keep it.

  • With the 05446 files, the case below gives q = 7 (the destination's DEFAULT) for {"id":1}. Master (44cf9c0), parallel_distributed_insert_select = 0 and plain s3 give 0. An auto-converted s3 into a Distributed table behaves the same way.
  • A headerless CSV read with structure = 'a UInt32, b UInt32' and SELECT toString(a + b) now fails on the nodes with UNKNOWN_IDENTIFIER, since they infer c1, c2. Master inserts 3 and 7.

With configuration->structure instead of "auto" (inline suggestion), both behave as on master and 05446 still matches its reference. The case, which fails on bbc1d71 and passes with the suggestion:

$CLICKHOUSE_CLIENT -q "
    INSERT INTO dst_05446 (id, q) SELECT id, q FROM s3Cluster('${CLUSTER}', '${S3_GLOB}', 'JSONEachRow', structure = 'id UInt32, q UInt32')
    SETTINGS parallel_distributed_insert_select = 2"
check dst_05446 "s3Cluster, key-value structure"
--- s3Cluster, key-value structure ---
1	2000-01-01	0	unknown	10
2	2000-01-01	5	unknown	20

The rest of the change looks right to me.


ASTs & args = expression_list->children;
const auto & structure = storage_snapshot->metadata->getColumns().getAll().toNamesAndTypesDescription();
const String structure = forward_structure ? storage_snapshot->metadata->getColumns().getAll().toNamesAndTypesDescription() : "auto";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

configuration->structure is the structure as the user wrote it ('auto' unless given), so an explicit key-value structure survives and everything else still gets 'auto'.

Suggested change
const String structure = forward_structure ? storage_snapshot->metadata->getColumns().getAll().toNamesAndTypesDescription() : "auto";
const String structure = forward_structure
? storage_snapshot->metadata->getColumns().getAll().toNamesAndTypesDescription()
: configuration->structure;

@clickhouse-gh

clickhouse-gh Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f3abf4e536a00c45ca5010ef6cb07cbdb667ed36 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.

…`INSERT ... SELECT`

Passing `'auto'` through the structure and format helper still rewrote the
arguments: it overwrote an explicit `structure = '...'` key-value argument
with `'auto'`, so a node could infer a different type than the query gave.
Skip the helper on the `INSERT ... SELECT` paths instead: only the rename to
the `*Cluster` variant and the cluster name argument are applied, and the
other arguments reach the nodes as written, as before #120488.

Add type-sensitive test cases for an explicit structure, positional and as a
key-value argument.

Related: #120488
Related: #121070

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment on lines +439 to +440
if (add_structure_and_format)
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/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.

❌ [P1] Keep initiator-side argument evaluation when skipping schema injection

This helper also materializes positional argument expressions: the S3 implementation calls StorageURL::evalArgsAndCollectHeaders, which replaces them with literals. Skipping it changes which source the workers open. The earlier argument parsing does not preserve those evaluated values in the forwarded AST because TableFunctionObjectStorage::parseArguments parses a clone.

For example, consider a distributed insert whose source is:

s3Cluster('cluster', getMacro('ingest_url'), 'JSONEachRow', 'id UInt32')

If the initiator's ingest_url is http://s3/bucket_a/file.jsonl and a worker's is http://s3/bucket_b/file.jsonl, previously the forwarded URL was the initiator's literal URL. Now the worker evaluates getMacro again and constructs its storage for bucket_b, while the initiator assigns it the key file.jsonl from bucket_a. The task carries the object path, not the S3 connection configuration, so this can silently insert rows from the wrong bucket; an initiator-only macro instead makes the insert fail. Both distributed insert callers pass false, and the auto-converted plain-function branch has the same regression.

Separate argument materialization from structure/format injection, retaining initiator-side evaluation on both branches while leaving omitted/'auto' structures available for destination defaults. Add a regression with different source-URL macros on the initiator and worker.

A `DEFAULT now64(3)` column missing in the files, with a TTL on it,
inserted through `s3Cluster` with `src AS dest` aliases, query parameters
and `NOSIGN`: with the default values of the type, the rows got
`1970-01-01` and the TTL deleted them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@devcrafter
devcrafter requested a review from groeneai October 24, 2026 19:04
@groeneai

Copy link
Copy Markdown
Collaborator

It is not caused by this PR. The only failing row in Upgrade check (amd_release) is:

Changed settings are not reflected in the settings changes history (see changed_settings.txt)
use_query_condition_cache_for_time_conditions | new_value 1 | old_value 0

The check compares against the previous release, which became v26.10.2.103-stable at 04:17 UTC today. That release includes #127632 (the setting is experimental and off by default on 26.10), while master still records its default change to true under 26.10. Since 04:20 UTC the same row failed on 106 PRs, and never on master. The fix is #127687 (mine, open).

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed 759cfb0 (merged into master 06be024, debug build) on a real 3-process cluster (one shard, three replicas, MinIO), parallel_distributed_insert_select = 2 into a ReplicatedMergeTree.

  1. c345e9e fixes the key-value structure finding: structure = 'id UInt32, v String' reaches the nodes as written and gives 1.50. 05446 (pointed at my MinIO) matches its reference, while master still writes 1970-01-01, 0 and '' in it.

  2. The bot's P1 (r4367065709) is real, but only reachable with a node-dependent argument. addStructureAndFormatToArgsIfNeededS3 materializes the positional arguments through StorageURL::evalArgsAndCollectHeaders, so skipping it makes every node evaluate them again. Macro src = bucket-a on the initiator and bucket-b on the two other nodes, INSERT INTO dst SELECT id, tcpPort() FROM s3Cluster('pr3', concat(getMacro('src'), '/part_{1,2,3,4,5,6}.jsonl'), ..., 'JSONEachRow', 'id UInt32'):

build rows of the two other nodes macro defined on the initiator only missing field with DEFAULT 7
master 06be024 bucket-a inserts 0
26.8.28.14 bucket-a inserts 0
this PR bucket-b (101..105) Code: 139 ... No macro init_only in config 7
26.8.2.7 bucket-b Code: 139 7

The initiator's own share still comes from bucket-a, so one INSERT mixes both buckets. This is the behavior from before #120488 (26.8.2.7 predates its backport), and with pr-must-backport it would also come back on 26.7 to 26.10. A plain SELECT from the same s3Cluster reads bucket-a on every build, since IStorageCluster::read still materializes the arguments. urlCluster/fileCluster are not involved: their helper edits a copy of the arguments.

If you want to keep the evaluation on the initiator: calling the helper with the structure as written instead of skipping it (add_structure_and_format ? structure : configuration->structure, my earlier suggestion, at both call sites) gives bucket-a, inserts with the initiator-only macro, DEFAULT 7 and 1.50, and 05446 matches its reference. The flag then only selects the structure, so its name and the comment in IStorageCluster.h would need an update.

Comment on lines +412 to +413
if (add_structure_and_format)
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/true);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
if (add_structure_and_format)
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/true);
configuration->addStructureAndFormatToArgsIfNeeded(
args, add_structure_and_format ? structure : configuration->structure, configuration->format, context, /*with_structure=*/true);

Comment on lines +439 to +440
if (add_structure_and_format)
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/true);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
if (add_structure_and_format)
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/true);
configuration->addStructureAndFormatToArgsIfNeeded(
args, add_structure_and_format ? structure : configuration->structure, configuration->format, context, /*with_structure=*/true);

@skuznetsov-clickhouse skuznetsov-clickhouse left a comment

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.

Looks good for a majority of cases.
For possible edge cases I created an issue #127792

Merged via the queue into master with commit c7b6832 Oct 26, 2026
179 checks passed
@skuznetsov-clickhouse
skuznetsov-clickhouse deleted the fix-cluster-insert-select-keep-auto-structure branch October 26, 2026 01:06
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 26, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 26, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 26, 2026
Backport #127657 to 26.10: Fix distributed `INSERT ... SELECT FROM` cluster functions ignoring column `DEFAULT` expressions
skuznetsov-clickhouse added a commit that referenced this pull request Oct 26, 2026
Keep the release branch older cluster API and carry the fix at its existing distributed INSERT path. Forward the source arguments as written for INSERT so destination DEFAULT expressions remain available; SELECT continues adding structure and format. Omit the test Distributed-destination case, whose newer source rewrite is absent on this branch.

Related: #127657

Related: ClickHouse/support-escalation#8987

Verification: git diff --check against the PR base; bash -n on the 05446 test. Build and runtime test remain for CI.
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 26, 2026
Cherry pick #127657 to 26.8: Fix distributed `INSERT ... SELECT FROM` cluster functions ignoring column `DEFAULT` expressions
robot-clickhouse added a commit that referenced this pull request Oct 26, 2026
…uster functions ignoring column `DEFAULT` expressions
clickhouse-gh Bot added a commit that referenced this pull request Oct 26, 2026
Backport #127657 to 26.8: Fix distributed `INSERT ... SELECT FROM` cluster functions ignoring column `DEFAULT` expressions
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 26, 2026
Cherry pick #127657 to 26.9: Fix distributed `INSERT ... SELECT FROM` cluster functions ignoring column `DEFAULT` expressions
robot-clickhouse added a commit that referenced this pull request Oct 26, 2026
…uster functions ignoring column `DEFAULT` expressions
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 26, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 26, 2026
Backport #127657 to 26.9: Fix distributed `INSERT ... SELECT FROM` cluster functions ignoring column `DEFAULT` expressions
alexey-milovidov pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 31, 2026
An old server (the public `clickhouse/clickhouse-server:26.6` image) creates a `DataLakeCatalog` database over a local REST catalog, an `IcebergS3` table through a named collection, and views and materialized views over them, then is restarted on the binary under test with the same metadata. An old and a new server also run parallel replicas over a catalog table, `icebergS3Cluster`, cross-version Iceberg writes and a distributed `INSERT ... SELECT FROM s3Cluster` that must apply the destination `DEFAULT` expressions (ClickHouse#127657). Single-node clusters make each version read every file for a query initiated on the other one.
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…uster functions ignoring column `DEFAULT` expressions
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…uster functions ignoring column `DEFAULT` expressions
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…luster functions ignoring column `DEFAULT` expressions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants