Skip to content

Reject nested cluster table functions with a clear error instead of crashing - #107107

Merged
nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-nested-cluster-table-function-task-iterator
Jun 30, 2026
Merged

nickitat merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-nested-cluster-table-function-task-iterator

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

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 a server crash (Distributed task iterator is not initialized logical error) when a cluster table function (urlCluster, fileCluster, s3Cluster, ...) is nested inside another distributed query such as clusterAllReplicas(..., urlCluster(...)). Such a query is now rejected with a BAD_ARGUMENTS error instead of aborting the server.

Description

clusterAllReplicas(..., urlCluster(...)) (a cluster table function nested inside another distributed query) shipped the inner function to the replicas as a secondary query. There the inner function enabled distributed reads and sent a read-task request back to an initiator that had installed no cluster-function task iterator, hitting a LOGICAL_ERROR in RemoteQueryExecutor::processReadTaskRequest that aborts the server in debug builds. Found by the BuzzHouse fuzzer (STID 4662-3e65 / 4662-4342).

The nested configuration is unsupported. A read-task request reaches that gate only from a worker running a cluster table function with distributed reads enabled, and the initiator installs a task iterator only for the legitimate top-level dispatch paths (top-level *Cluster read, INSERT INTO distributed SELECT FROM *Cluster). A missing iterator there is therefore exactly the nested case, so it is now rejected with BAD_ARGUMENTS (a normal query error that leaves the server alive). This is the single shared gate for every cluster function, so no new setting or protocol change is needed; the legitimate top-level and INSERT-SELECT paths keep distributing.

Approach agreed with @nickitat in the review thread (throw BAD_ARGUMENTS, no new setting), superseding the earlier ClientInfo-flag and internal-setting prototypes.

Added regression test 03850_nested_cluster_table_function_task_iterator: nested urlCluster/fileCluster under clusterAllReplicas now return BAD_ARGUMENTS, the nested s3Cluster case does not abort the server, and the legitimate top-level urlCluster and INSERT INTO distributed SELECT FROM urlCluster paths still distribute (each task read once).

Version info

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Local debug server (master HEAD, contains #100146) with a 3-replica and a 2-shard test cluster. SELECT count() FROM clusterAllReplicas('test_cluster_one_shard_three_replicas_localhost', urlCluster('test_cluster_two_shards', 'http://localhost:<http>/?query=SELECT+1', 'TSV', 'x UInt8')) aborts the server every time with Distributed task iterator is not initialized (RemoteQueryExecutor.cpp:787). Matches the BuzzHouse fuzzer query from fatal.log.
b Root cause explained? Yes. Outer clusterAllReplicas (StorageDistributed) ships SELECT ... FROM urlCluster(...) to replicas as secondary queries. The inner urlCluster on a replica saw query_kind == SECONDARY_QUERY and enabled distributed_processing, sending a ReadTaskRequest to the outer initiator, which is a plain StorageDistributed with no cluster-function task iterator -> LOGICAL_ERROR. The shard wrongly assumed any secondary cluster-function query has an IStorageCluster initiator with an iterator.
c Fix matches root cause? Yes. The discriminator is client_info.distributed_depth: IStorageCluster::read (the legit top-level fan-out) builds its RemoteQueryExecutor with the iterator and does not increase distributed depth (worker sees 0), while StorageDistributed / ClusterProxy::executeQuery call increaseDistributedDepth() (nested worker sees >= 1). The fix enables distributed_processing only when distributed_depth == 0, i.e. only when the initiator actually set up the iterator.
d Test intent preserved / new tests added? New regression test 03850_nested_cluster_table_function_task_iterator covers clusterAllReplicas(urlCluster(...)), clusterAllReplicas(fileCluster(...)), and asserts the legitimate top-level urlCluster still distributes (single URL read exactly once). No existing test weakened.
e Both directions demonstrated? Yes. On the unfixed master binary the nested query fails with the logical error (4 fatal hits, server abort). On the fixed binary all test queries pass (output 1x5), 0 logical errors, server stays alive. Verified the running binary via /proc/<pid>/exe in both cases.
f Fix is general, not a narrow patch? Yes. Applied to all three cluster table functions that take the shard-side distributed_processing path: TableFunctionURLCluster, TableFunctionFileCluster, and TableFunctionObjectStorageCluster (covers s3Cluster / azureBlobStorageCluster / hdfsCluster / iceberg/delta/hudi cluster variants). The fix is at the source of the wrong assumption (the shard-side enablement), not a guard at the throw site in RemoteQueryExecutor.
Session id: cron:clickhouse-worker-slot-11:20260610-225800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @arthurpassos — could you review this? It extends #100146 to the explicit *Cluster table functions: when urlCluster/s3Cluster/fileCluster is nested inside an outer distribution (e.g. clusterAllReplicas(urlCluster(...))), the inner function on a replica wrongly enabled distributed_processing and sent a ReadTaskRequest to an initiator with no task iterator, aborting the server. Fix: enable it only when distributed_depth == 0.

@pufit pufit added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [05b9dbb]

Summary: ✅


AI Review

Summary

This PR rejects unsupported nested explicit cluster table functions by converting the missing cluster-function task iterator path from LOGICAL_ERROR to BAD_ARGUMENTS, and it adds stateless coverage for urlCluster, fileCluster, and s3Cluster. The explicit table-function path now looks covered, but the new gate still conflicts with the DataLakeCatalog parallel-replicas behavior fixed in #100146: a non-explicit DataLake table can still send a cluster-function ReadTaskRequest from a parallel-replicas secondary query and now gets rejected.

Findings

⚠️ Majors

  • [src/Databases/DataLake/DatabaseDataLake.cpp:711] DataLakeCatalog still uses collaborate_with_initiator && can_use_parallel_replicas as the signal to enable object-storage task reads. In a parallel-replicas secondary query this signal is also true when the initiator has only parallel_reading_coordinator and no cluster-function task_iterator; the DataLake StorageObjectStorage source then sends ReadTaskRequest and hits the new BAD_ARGUMENTS branch in RemoteQueryExecutor::processReadTaskRequest instead of the local-read behavior restored by #100146. That regresses supported DataLakeCatalog queries evaluated inside a parallel-replicas query, even though they are not explicit nested *Cluster table functions.
    Suggested fix: make the DataLake path enable distributed_processing only when the initiator actually installed a cluster-function task_iterator, or explicitly disable it for nested parallel-replicas secondary queries.
Tests
  • ⚠️ Add or restore a focused DataLakeCatalog regression for a table evaluated inside a parallel-replicas query where the initiator has a parallel-reading coordinator but no cluster-function task iterator. It should prove the query does not hit the new BAD_ARGUMENTS gate unless that compatibility break is deliberately accepted and documented.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: fix the DataLake task-read signal/fallback so #100146 remains compatible, and cover that path with a regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
@groeneai
groeneai force-pushed the fix-nested-cluster-table-function-task-iterator branch 2 times, most recently from dd2cd73 to ada72e6 Compare June 11, 2026 03:36
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated after review)

# Question Answer
a Deterministic repro? Yes. Nested crash: SELECT count() FROM clusterAllReplicas('<3-replica>', urlCluster('<2-shard>', '<self-http>', 'TSV', 'c0 Date, c1 Int32')) WHERE c1 IS NOT NULL aborts the unpatched server every time at RemoteQueryExecutor.cpp:787. Review regression: INSERT INTO <Distributed over single-shard> SELECT * FROM urlCluster('test_cluster_two_shards', '.../{1,2,3}...', 'TSV', 's String') SETTINGS parallel_distributed_insert_select=2 inserts 9/6 rows (depth==0 guard) vs 3 (correct).
b Root cause explained? Yes. A *Cluster table function as a secondary query enabled distributed_processing from collaborate_with_initiator, which is also set for parallel-replicas / plain-Distributed broadcasts that carry no cluster-function task iterator. When such a broadcast wraps a nested cluster function, the worker sends a ReadTaskRequest to an initiator with no iterator -> LOGICAL_ERROR. distributed_depth cannot disambiguate: legitimate INSERT INTO distributed SELECT FROM *Cluster runs at depth 1 with an iterator, the nested broadcast at depth >= 1 without one.
c Fix matches root cause? Yes. Adds an explicit initiator signal ClientInfo::is_cluster_function_distributed_read, set only when the initiator passes a cluster-function task_iterator to the RemoteQueryExecutor. The worker enables distributed_processing only when that signal is set, exactly distinguishing "initiator installed an iterator for me" from "nested under a broadcast that did not".
d Test intent preserved / new tests added? Yes. 03850_nested_cluster_table_function_task_iterator keeps the nested crash cases and the top-level distribution check, and adds an INSERT INTO distributed SELECT FROM urlCluster(...) case asserting each task is read exactly once (guards against the depth-based regression the review flagged). No existing test weakened.
e Both directions demonstrated? Yes. Unpatched: nested query aborts; depth==0 attempt duplicates insert-select rows (9/6 vs 3). Patched: nested queries complete with no Distributed task iterator errors and server stays alive; insert-select reads each task once (3) on single-shard, 2-replica and 3-replica destinations; top-level urlCluster reads the source exactly once. Re-verified after rebasing onto current master (build id d8146ff4).
f Fix is general, not a narrow patch? Yes. The signal is set centrally in RemoteQueryExecutor::sendQuery and consumed via one Context helper used by all three cluster table functions (urlCluster, fileCluster, object-storage *Cluster), so every nested-cluster-function variant is covered, not just the fuzzed urlCluster path. Protocol-versioned with a back-compat fallback for older initiators (no mixed-version regression).

Session id: cron:clickhouse-worker-slot-25:20260611-020400

Comment thread src/Interpreters/ClientInfo.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up commit 9d6111a)

# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='ClientInfoSerialization.ClusterFunctionFlagExcludedFromPersistedHeader' deterministically reproduces the header shift when the field is not gated on with_client_agent.
b Root cause explained? The flag was gated only on protocol revision 54486, so it was appended inside the embedded ClientInfo of the persisted async Distributed queue header, which DistributedSink writes with with_client_agent=false and immediately follows with rows/bytes. An older binary records revision 54486 but has no branch to consume field 54486, so after ClientInfo::read it reads the flag byte as rows and shifts the rest of the header.
c Fix matches root cause? Yes. Gate the field on with_client_agent in both ClientInfo::write and ClientInfo::read, matching the client_agent precedent (PR #106619). The persisted header no longer carries the field; the live TCP path (with_client_agent=true by default) is unchanged.
d Test intent preserved / new tests added? New gtest gtest_client_info_serialization.cpp: ClusterFunctionFlagRoundTripsOnTcp (flag round-trips on TCP) and ClusterFunctionFlagExcludedFromPersistedHeader (older-revision reader still parses trailing rows/bytes).
e Both directions demonstrated? Yes. Without the fix the persisted-header test fails (rows reads 1 = the flag byte, bytes reads 1234 = the shifted rows). With the fix both tests pass.
f Fix is general, not a narrow patch? Both serialization directions (write + read) are gated symmetrically. The only with_client_agent=false call sites are DistributedSink (write) and DistributedAsyncInsertHeader (read); all live-TCP paths (Connection::sendQuery, TCPHandler) use the default true. No other persisted ClientInfo layout exists.

Session id: cron:clickhouse-worker-slot-9:20260611-035200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 1fd8548 — nested s3Cluster test coverage)

# Question Answer
a Deterministic repro? Yes. With the object-storage gate reverted to the pre-fix distributed_processing = true, clusterAllReplicas('test_cluster_one_shard_three_replicas_localhost', s3Cluster('test_cluster_two_shards', <minio object>, 'TSV', 'x UInt8')) SETTINGS prefer_localhost_replica = 0 aborts the server every time with Distributed task iterator is not initialized.
b Root cause explained? The object-storage *Cluster stack reaches the read-task iterator via StorageObjectStorageSource::createFileIterator -> ReadTaskIterator, gated only in TableFunctionObjectStorageCluster. On a worker running the inner s3Cluster as a secondary query, the pre-fix code enabled distributed_processing whenever collaborate_with_initiator was set, so it sent a ReadTaskRequest back to an initiator (the outer clusterAllReplicas broadcast) that installed no task_iterator -> RemoteQueryExecutor::processReadTaskRequest throws. prefer_localhost_replica = 0 is required so the outer broadcast actually ships the inner query as a secondary query (otherwise it runs locally and the path is never reached).
c Fix matches root cause? This commit is test-only. The code fix (gating on context->canUseClusterFunctionDistributedRead()) already landed in ada72e6; this adds the missing object-storage coverage the bot identified.
d Test intent preserved / new tests added? New case added to the existing regression test. The url/file cases are unchanged; the s3 case exercises the otherwise-uncovered TableFunctionObjectStorageCluster branch.
e Both directions demonstrated? Yes. Reverted object-storage gate -> server aborts with the LOGICAL_ERROR. Fix restored (build id 284f81a7) -> 8/8 passes, server alive. Builds verified by changing Build ID across each rebuild.
f Fix is general, not a narrow patch? The three sibling gates (url/file/object-storage) all now route through canUseClusterFunctionDistributedRead(); this test closes the coverage gap so a future regression in the object-storage branch is caught, matching the url/file coverage already present.

Session id: cron:clickhouse-worker-slot-2:20260611-051300

Comment thread src/Interpreters/Context.cpp Outdated
return next_task_callback.has_value();
}

bool Context::canUseClusterFunctionDistributedRead() const

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 helper closes the false-positive signal for the changed table-function paths, but DatabaseDataLake::tryGetTableImpl still uses the old proxy directly: src/Databases/DataLake/DatabaseDataLake.cpp:709 sets object-storage distributed_processing from context_->getClientInfo().collaborate_with_initiator && can_use_parallel_replicas.

That leaves the same failure shape for DataLakeCatalog tables. An outer parallel-replicas or clusterAllReplicas read sends the secondary query with RemoteQueryExecutor::Extension{.parallel_reading_coordinator = ..., .task_iterator = nullptr}, so collaborate_with_initiator is true but the initiator has no cluster-function task iterator. If that secondary query reads a DataLakeCatalog table with parallel_replicas_for_cluster_engines and cluster_for_parallel_replicas enabled, the branch above enables StorageObjectStorage task reads, StorageObjectStorageSource::ReadTaskIterator sends a ReadTaskRequest, and the initiator still throws Distributed task iterator is not initialized.

Please route the DatabaseDataLake branch through this explicit signal too, e.g. require context_->canUseClusterFunctionDistributedRead() (alongside the existing can_use_parallel_replicas gate) before enabling object-storage distributed_processing.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, fixed in fd9d391. Routed the DatabaseDataLake::tryGetTableImpl branch through canUseClusterFunctionDistributedRead() (alongside the existing can_use_parallel_replicas gate), so the DataLakeCatalog path now keys object-storage distributed_processing on the explicit initiator signal instead of the old collaborate_with_initiator proxy. This was the last remaining consumer of that proxy for cluster reads.

Reproduced and verified the exact failure shape you described, in tests/integration/test_database_iceberg/test.py::test_cluster_select_nested: an outer parallel-replicas read distributes a local MergeTree table and reads a DataLakeCatalog table on each replica (parallel_replicas_for_cluster_engines + cluster_for_parallel_replicas). The secondary query carries a parallel_reading_coordinator but task_iterator = nullptr.

  • Without the fix the server aborts with Logical error: 'Distributed task iterator is not initialized' (confirmed in the worker fatal log).
  • With the fix the read falls back to a local read and returns correctly.

The legitimate parallel-replicas path is unaffected: the initiator builds a StorageObjectStorageCluster whose IStorageCluster::read passes a non-null task_iterator, so RemoteQueryExecutor sets is_cluster_function_distributed_read on the secondary query and the worker keeps distributed_processing enabled. The existing test_cluster_select still passes alongside the new nested case.

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 looks reintroduced in the current code. src/Databases/DataLake/DatabaseDataLake.cpp:711-713 still enables distributed_processing from collaborate_with_initiator && can_use_parallel_replicas; for a DataLakeCatalog table evaluated inside a parallel-replicas secondary query, the initiator has parallel_reading_coordinator but no task_iterator, so the DataLake StorageObjectStorage source still sends a cluster-function ReadTaskRequest and now hits the new BAD_ARGUMENTS branch at src/QueryPipeline/RemoteQueryExecutor.cpp:815-819 instead of using the local-read behavior restored by #100146.

Please keep the DataLake path on task-based object-storage reads only when the initiator actually installed a cluster-function task_iterator, or disable it for the nested parallel-replicas secondary query.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

You are right that the nested DataLake-under-parallel-replicas read reaches this gate. But on master today it does not local-read here: processReadTaskRequest throws LOGICAL_ERROR "Distributed task iterator is not initialized" and aborts the server. This PR turns that abort into a normal BAD_ARGUMENTS, so for the DataLake path it is strictly an improvement (crash to clean error), not a regression.

Two corrections on the framing:

  • #100146 set distributed_processing=false only for the plain non-cluster table functions (TableFunctionURL, TableFunctionObjectStorage); that is the local-read it restored. It did not change the DataLake catalog gate: DatabaseDataLake::tryGetTableImpl still computes distributed_processing = collaborate_with_initiator && can_use_parallel_replicas, byte-identical on master and on this PR. This PR does not modify DatabaseDataLake.cpp or Context.cpp.
  • canUseClusterFunctionDistributedRead is not in the current code. It only existed in an earlier prototype of this PR that was dropped per your "no new flag/setting" guidance, so there is nothing reintroduced.

On "keep task-based reads only when the initiator installed a task_iterator": that is exactly what the gate does, just expressed as the error. The worker cannot tell the legitimate top-level cluster dispatch from the nested case, because both run as a secondary query with collaborate_with_initiator=true and can_use_parallel_replicas=true, so both set distributed_processing=true and send a ReadTaskRequest. The only place the distinction is known is the initiator's processReadTaskRequest: it serves the read when it installed a task_iterator (the legit StorageObjectStorageCluster dispatch) and rejects it otherwise (the nested case). Making the worker local-read instead would need a worker-side signal up front, which is the ClientInfo flag we removed.

So the two realizable options are: (A) keep the clean BAD_ARGUMENTS for the nested DataLake case, consistent with the url/file/s3 nested cases this PR already rejects; or (B) reinstate the dropped initiator-to-worker flag so the worker local-reads here like #100146 did for plain url/s3. I lean to (A): it avoids silent per-replica duplication and needs no new flag. The DataLake catalog path needs an Iceberg REST catalog, so it is integration-only and not coverable in 03850.

@nickitat which do you prefer, A or B?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit fd9d391)

# Question Answer
a Deterministic repro? Yes. test_database_iceberg/test.py::test_cluster_select_nested fails 100% on the pre-fix binary with <Fatal> Logical error: 'Distributed task iterator is not initialized'. An outer parallel-replicas read distributes a local MergeTree table and reads the DataLakeCatalog table on each replica (allow_experimental_parallel_reading_from_replicas=2, cluster_for_parallel_replicas, parallel_replicas_for_cluster_engines=1, prefer_localhost_replica=0).
b Root cause explained? DatabaseDataLake::tryGetTableImpl set object-storage distributed_processing from collaborate_with_initiator && can_use_parallel_replicas. A plain parallel-replicas / clusterAllReplicas broadcast sets collaborate_with_initiator on the secondary query but installs no cluster-function task_iterator (Extension has parallel_reading_coordinator only). The worker then enabled distributed_processing, StorageObjectStorageSource::createFileIterator sent a ReadTaskRequest, and the initiator (no iterator) raised the LOGICAL_ERROR.
c Fix matches root cause? Yes. Gate the branch on Context::canUseClusterFunctionDistributedRead() (alongside can_use_parallel_replicas) — the explicit is_cluster_function_distributed_read signal the initiator sets only when it actually passes a task_iterator. Same precedent already applied to the url/file/object-storage *Cluster table functions earlier in this PR.
d Test intent preserved / new tests added? New test_cluster_select_nested added covering the nested DataLake case (different gate/iterator path than the *Cluster table functions). The existing test_cluster_select (legitimate top-level cluster path) is unchanged and still passes.
e Both directions demonstrated? Yes, on Build-ID-verified debug binaries. No-fix (7dd9bfb1...): test FAILS with the fatal LOGICAL_ERROR. With-fix (9fd42703...): test PASSES (25s); test_cluster_select + test_cluster_select_nested pass together (2 passed).
f Fix is general, not a narrow patch? Yes. Grepped all collaborate_with_initiator consumers — DatabaseDataLake.cpp:709 was the last cluster-read site still using the old proxy; the three *Cluster table functions were already routed through canUseClusterFunctionDistributedRead() earlier in this PR. No further sibling paths enable object-storage distributed_processing from the old proxy. The fix is at the gate (the explicit signal), not a defensive guard at the crash site.

Session id: cron:clickhouse-worker-slot-5:20260611-064000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 6827ece — old-analyzer test fix)

Fixes the PR-caused failure on Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) in 03850_nested_cluster_table_function_task_iterator (3/3 reruns, isolated to this PR).

# Question Answer
a Deterministic repro? Yes. Server with allow_experimental_analyzer=0 (old-analyzer job profile) + test clusters: the WHERE case ... FROM clusterAllReplicas('...', urlCluster(...)) AS t WHERE t.x = 1 deterministically raises Code: 47 Missing columns: 't.x' (UNKNOWN_IDENTIFIER). The shipped secondary query is SELECT count() >= 1 FROM urlCluster(...) WHERE t.x = 1 — exactly the CIDB failure.
b Root cause explained? clusterAllReplicas(inner) AS t ships only the inner SELECT to the replicas as a secondary query; the outer table alias t is NOT shipped. So on the replica the query is ... FROM urlCluster(...) WHERE t.x = 1, where t is undefined. The new analyzer tolerates the dangling qualifier (resolves t.x to the sole table source); the old analyzer rejects it during name analysis with UNKNOWN_IDENTIFIER (code 47). The LOGICAL_ERROR this test guards (Distributed task iterator) is analyzer-agnostic, so the test must run under both analyzers.
c Fix matches root cause? Yes. Reference the inner column directly (WHERE x = 1) instead of via the un-shipped outer alias (WHERE t.x). The filter now resolves in the shipped secondary query under both analyzers. No tags, no settings pins, no assertion weakening.
d Test intent preserved / new tests added? Preserved. The case still exercises a filtered nested-cluster read (clusterAllReplicas(urlCluster(...)) WHERE <col>); the AS t alias served no purpose beyond qualifying x and was never shipped. .reference unchanged (output is still 1).
e Both directions demonstrated? Yes, on the old analyzer end-to-end (test clusters repointed to a single local server): OLD form (AS t WHERE t.x = 1) → Code: 47 Missing columns: 't.x'; NEW form (WHERE x = 1) → 1. Also verified the other cases pass under the old analyzer (case 1 1, fileCluster 1, top-level urlCluster 1, INSERT-each-task-once 3, server alive 1); s3Cluster nested case passes name analysis under the old analyzer (EXPLAIN SYNTAX clean, no code 47).
f Fix is general, not a narrow patch? This is a test-only fix (no source change). The only t.-qualified-via-outer-alias reference in the test was this WHERE case; the other nested cases use bare columns and are analyzer-agnostic (verified). No sibling code paths to widen.

Session id: cron:clickhouse-worker-slot-0:20260611-115600

@nickitat

Copy link
Copy Markdown
Member

@groeneai, is there a real use case for a cluster function inside clusterAllReplicas? Maybe we can just disable parallel replicas in the inner contexts of the clusterAllReplicas?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat thanks for looking.

Real use case? No deliberate one. The nesting (clusterAllReplicas(..., urlCluster(...)), s3Cluster under parallel replicas, etc.) was found by the BuzzHouse fuzzer, not reported by a user. The goal isn't to make nested cluster functions useful; it's only to stop a parseable query from aborting the server with LOGICAL_ERROR: Distributed task iterator is not initialized. The intended behavior is to degrade to a plain local read of the inner function.

"Just disable parallel replicas in the inner contexts": that is exactly the intent here. In the nested/inner context the *Cluster function must not do a task-based distributed read. The open question is how the worker detects it is in that context, and a literal "clear the parallel-replica settings on the inner query" turns out not to be enough:

  1. urlCluster/fileCluster turn on distributed_processing purely from query_kind == SECONDARY_QUERY (TableFunctionURLCluster::getStorage), not from parallel_replicas_for_cluster_engines / cluster_for_parallel_replicas. Only the object-storage and DataLake paths read those settings, so clearing them fixes s3/DataLake but leaves url/file still crashing.
  2. Both the legitimate top-level SELECT ... FROM urlCluster(...) dispatch and the nested broadcast reach the worker as SECONDARY_QUERY with the read-task callback installed (TCPHandler installs it for every secondary query). The only thing that differs is whether the initiator actually installed a task iterator, and that fact lives on the initiator's Extension, not on the wire. So the worker needs some signal from the initiator; is_cluster_function_distributed_read = (extension && extension->task_iterator != nullptr) is the minimal form of it: true for a top-level *Cluster read and for INSERT INTO distributed SELECT FROM *Cluster, false for the nested broadcast.
  3. A distributed_depth-based gate with no new field was my first attempt, but depth alone can't separate "top-level cluster dispatch" from "nested in a broadcast", so it regressed those legitimate paths.

If you would rather keep this fully initiator-side and avoid the protocol bump, the natural spot is ClusterProxy::updateSettingsAndClientInfoForCluster (it already adjusts the inner query's settings, e.g. sets allow_experimental_parallel_reading_from_replicas = 0), but it would still need a per-query signal to reach the url/file paths since those consult no setting. I'm happy to take that route if you think it is cleaner. Which would you prefer?

@nickitat

Copy link
Copy Markdown
Member

Only the object-storage and DataLake paths read those settings, so clearing them fixes s3/DataLake but leaves url/file still crashing.

@groeneai, I don't see any good reason for the URL or file functions to behave differently from S3 in this regard. In general, I'd like you to explore ways to ensure all these functions behave properly when parallel replica settings are disabled.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat you're right, and my earlier comment was misleading. After this PR url, file and s3 do not behave differently: all four paths (urlCluster, fileCluster, s3Cluster/object-storage, DataLake) gate the secondary-query distributed read uniformly on Context::canUseClusterFunctionDistributedRead(). My "url/file ignore the settings" remark described the pre-fix code, where url/file hard-coded distributed_processing = true while object-storage gated on collaborate_with_initiator. Making them uniform is what this PR does. Sorry for the noise.

On "just disable parallel replicas in the inner contexts", the subtlety is which layer the setting lives at:

  • parallel_replicas_for_cluster_engines / cluster_for_parallel_replicas today govern only the auto-promotion of a plain engine to its Cluster variant (url to urlCluster, s3 to s3Cluster, DataLake to StorageObjectStorageCluster), and only when query_kind != SECONDARY_QUERY (TableFunctionURL.cpp:118, TableFunctionObjectStorage.cpp:247, DatabaseDataLake.cpp:670). url and s3 already read them identically. (file is the only real asymmetry: there is no file to fileCluster auto-promotion, fileCluster is explicit-only. Orthogonal to this crash.)
  • The crash is on an explicit urlCluster(...) / s3Cluster(...) nested in clusterAllReplicas. Explicit *Cluster functions deliberately do not read parallel_replicas_for_cluster_engines (you already asked for the cluster variant), so setting it to 0 on the inner query does not stop them today. That is why "disable parallel replicas in the inner context" needs a second half: making the explicit *Cluster worker execution honor that setting.

So your proposal is implementable as: in the Distributed/clusterAllReplicas ship path (ClusterProxy::updateSettingsAndClientInfoForCluster) disable cluster-engine parallel replicas on the inner secondary query, and have the explicit *Cluster worker execution skip the task read when it is off. That drops the protocol bump and the ClientInfo flag. Two things worth settling first:

  1. Semantic change: today SELECT FROM urlCluster(...) SETTINGS parallel_replicas_for_cluster_engines=0 still distributes; under this model it becomes a local read. The top-level path stays safe from the broadcast's clearing (IStorageCluster::read does not route through updateSettingsAndClientInfoForCluster, it only sets skip_unavailable_shards), but the setting gains a new meaning at execution time. OK with that?
  2. INSERT INTO distributed SELECT FROM *Cluster must keep task-based reads, otherwise every remote re-reads the whole glob (the 01099_parallel_distributed_insert_select regression that killed my first depth-based attempt). The clearing has to be scoped to the broadcast-wrapping-a-function case and not this one; I need to confirm updateSettingsAndClientInfoForCluster can be scoped that precisely, since several Distributed paths share it. The current flag sidesteps this by being computed from "did the initiator install a task iterator", which is true only for the three legit sites (IStorageCluster, StorageDistributed insert-select, InterpreterInsertQuery) and false for the broadcast.

If (1) is acceptable to you, I'll prototype the settings-based version, confirm (2) via 01099, and remove the protocol bump. Otherwise I'll keep the current flag. Which do you prefer?

@nickitat

Copy link
Copy Markdown
Member

@groeneai, I want you to prototype the setting path. ATST, it is not ok to change the semantics of parallel_replicas_for_cluster_engines. Do we have a more suitable setting that we can rely on to disable PRs in our cases without also flipping its semantics upside down?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat done. Prototyped the setting path as a draft so we can compare side by side: #107572 (do not merge, alternative to this PR).

A more suitable setting than parallel_replicas_for_cluster_engines: a new internal Bool cluster_function_distributed_read (default true). It does not change the meaning of any user-facing setting. The initiator clears it on the inner secondary query of a broadcast, in two places:

  • ClusterProxy::updateSettingsAndClientInfoForCluster (Distributed / remote / clusterAllReplicas)
  • updateContextForParallelReplicas (parallel-replicas-from-MergeTree)

The worker gate canUseClusterFunctionDistributedRead() just returns the setting (after the read-task-callback check), so every *Cluster function (url/file/s3/object-storage/DataLake) skips the inner distributed read uniformly. This drops the ClientInfo field and the protocol bump from this PR.

Two properties make it safe:

  • The legitimate paths build their own secondary-query context that does not route through either function above, so they keep the setting at true: top-level *Cluster (IStorageCluster::read, sets only skip_unavailable_shards) and INSERT INTO distributed SELECT FROM *Cluster (StorageDistributed / InterpreterInsertQuery, which install the iterator). So disabling the inner read does not touch them.
  • An older worker that does not know the setting leaves it at its default true; a non-IMPORTANT setting is tolerated on read (warn and skip), and the async Distributed insert header layout is unchanged, so the mixed-version concern that motivated gating the field disappears.

Verified locally (debug), both directions, single server with the test clusters on one loopback so the inner query runs as a real secondary query:

  • without the clears: clusterAllReplicas('...', urlCluster(...)) aborts with Distributed task iterator is not initialized
  • with the fix: nested url/file/s3 complete, server stays alive, top-level urlCluster still distributes, and INSERT INTO distributed SELECT FROM urlCluster(...) SETTINGS parallel_distributed_insert_select = 2 reads each task once (3 rows, the 01099 shape, not regressed)

Which do you prefer: keep this PR (the explicit ClientInfo flag) or switch to #107572 (the setting)? I will close the other one.

@nickitat

Copy link
Copy Markdown
Member

@groeneai, I prefer the setting approach. But the following

so every *Cluster function (url/file/s3/object-storage/DataLake) skips the inner distributed read uniformly

begs the question: wouldn't it be better to just throw an exception if one cluster function is nested within another?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat thanks. Agreed, the setting PR (#107572) is the one to carry forward; I will close #107107 (the ClientInfo-flag PR) once #107572 is green and reviewed, so we are not left with two competing PRs.

On throw vs fallback I think throwing is the better behavior, for one concrete reason beyond simplicity. The "fall back to a local read" path does not degrade cleanly. clusterAllReplicas('c', urlCluster(...)) makes the inner function run as a secondary query on every node of c, and each node then reads the full url/glob locally, so the result is the data multiplied by the number of replicas. That is consistent with how clusterAllReplicas treats any non-distributed table, but it is almost never what someone writing a nested cluster function wants. So the fallback turns today's server abort into a silently duplicated result, whereas a throw turns it into an explicit, explainable error.

Scope of the throw is precise and matches the fallback gate exactly: throw only when an explicit *Cluster function finds the read-task callback installed but cluster_function_distributed_read cleared. That condition is reached only inside the inner secondary query of a Distributed / clusterAllReplicas / parallel-replicas broadcast. The three paths that legitimately install a task iterator (top-level IStorageCluster::read, INSERT INTO distributed SELECT FROM *Cluster, and parallel replicas over a DataLake table) build their own secondary context that does not clear the setting, so they keep distributing and are unaffected. 01099_parallel_distributed_insert_select stays green for the same reason.

Backward compatibility: nothing currently working breaks, since the nested case aborts the server today. An older initiator that does not clear the setting still aborts as before until it upgrades; a current one gives the clean throw.

I would raise it as NOT_IMPLEMENTED ("Cluster table function '...' cannot be nested inside a distributed query"), but I am happy to use BAD_ARGUMENTS if you read it as user error. One small consequence: the 03850 test currently asserts the nested case succeeds (local read, returns 1); under throw it would assert the error instead.

If you confirm the throw direction and the error class, I will implement it in #107572 and update the test.

@nickitat

Copy link
Copy Markdown
Member

@groeneai, use BAD_ARGUMENTS. Is there a way to implement the throwing approach without adding a new setting?

@nickitat nickitat self-assigned this Jun 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat BAD_ARGUMENTS it is, and yes, the throw can be done with no new setting.

The initiator already detects the exact condition. A worker only sends a ReadTaskRequest when it is running a *Cluster function with distributed reads enabled; the initiator handles that packet in RemoteQueryExecutor::processReadTaskRequest (RemoteQueryExecutor.cpp:804), which today throws LOGICAL_ERROR "Distributed task iterator is not initialized" when extension->task_iterator is null. The only initiator paths that install a task_iterator are the legitimate ones (top-level IStorageCluster::read and INSERT INTO distributed SELECT FROM *Cluster). A plain Distributed / clusterAllReplicas / parallel-replicas broadcast installs no task_iterator (parallel replicas installs only a parallel_reading_coordinator). So "a ReadTaskRequest arrived but I have no task_iterator" is, by construction, the nested case. Relabeling that single throw to BAD_ARGUMENTS with a clear message rejects the nested config without a setting, a ClientInfo flag, or a protocol bump, and lets me revert all the worker-side gating this PR added. It also fixes the actual symptom: today the crash is the debug/sanitizer abort on LOGICAL_ERROR; BAD_ARGUMENTS is a normal query error and never aborts.

I checked whether a worker-side throw could instead name the specific function, since the initiator-side message can only be generic. None of the existing worker state separates the nested case: distributed_depth is 1 for top-level, insert-select and nested alike; query_kind is SECONDARY_QUERY for all; and collaborate_with_initiator is true even for parallel replicas (it is set whenever an Extension is present, with or without a task_iterator). So a function-specific worker-side throw is exactly the thing that would need a per-query signal. The initiator-side relabel is the no-setting answer, at the cost of a generic message.

One case to confirm before I implement: the same check also fires for parallel-replicas-over-DataLake with parallel_replicas_for_cluster_engines + cluster_for_parallel_replicas enabled (the path flagged earlier in this PR). It reaches the same point with no task_iterator, so it would also get BAD_ARGUMENTS rather than the silent local-read fallback the current fix gives it. Throwing there too is consistent with rejecting "distributed cluster-function read requested where the initiator installed no iterator" uniformly, and that combination crashes today anyway, so nothing working regresses. OK to throw there as well, or do you want the DataLake-under-parallel-replicas path to keep distributing?

If you are good with the uniform throw, I will relabel processReadTaskRequest to BAD_ARGUMENTS, drop the setting / flag machinery, and update 03850 to assert the error instead of a successful local read.

@nickitat

Copy link
Copy Markdown
Member

@groeneai, sounds good.

@groeneai
groeneai force-pushed the fix-nested-cluster-table-function-task-iterator branch from 6827ece to 9b60b55 Compare June 16, 2026 14:01
@groeneai groeneai changed the title Fix "Distributed task iterator is not initialized" for nested cluster table functions Reject nested cluster table functions with a clear error instead of crashing Jun 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT count() FROM clusterAllReplicas('test_cluster_one_shard_three_replicas_localhost', urlCluster('test_cluster_two_shards', 'http://localhost:PORT/?query=SELECT+1', 'TSV', 'x UInt8')) SETTINGS prefer_localhost_replica=0 aborts the server every time on a debug build (test clusters repointed at one loopback so the inner query runs as a real secondary query).
b Root cause explained? The outer clusterAllReplicas ships the inner cluster function to a replica as a secondary query. The inner function enables distributed reads and sends a read-task request back to the initiator, which is a plain broadcast that installed no cluster-function task iterator. RemoteQueryExecutor::processReadTaskRequest finds extension->task_iterator == nullptr and throws LOGICAL_ERROR, which aborts the server in debug.
c Fix matches root cause? Yes. A read-task request reaches that gate only from a worker running a cluster function with distributed reads enabled, and only the legitimate top-level paths install a task iterator, so task_iterator == nullptr there is exactly the unsupported nested case. The fix rejects it with BAD_ARGUMENTS (normal query error, server stays alive) at that single shared gate. No new setting or protocol change.
d Test intent preserved / new tests added? New regression test 03850_nested_cluster_table_function_task_iterator: nested urlCluster/fileCluster now return BAD_ARGUMENTS; nested s3Cluster does not abort the server; legitimate top-level urlCluster and INSERT INTO distributed SELECT FROM urlCluster still distribute (each task read once, same shape as 01099).
e Both directions demonstrated? Yes. Without the fix (build FCE992A6): the nested query logs <Fatal> Logical error: 'Distributed task iterator is not initialized' and the server aborts (connection reset). With the fix (build 9D67E20C): the query returns BAD_ARGUMENTS, server alive; test passes 5/5 plus the old-analyzer variant.
f Fix is general, not a narrow patch? Yes. The fix is at the single shared chokepoint (RemoteQueryExecutor::processReadTaskRequest) that every cluster function funnels through, so url/file/s3/object-storage are covered uniformly without per-function changes. It is not a defensive nullptr guard masking an upstream bug: the unsupported nested configuration legitimately has no iterator, and the correct user-facing outcome is to reject it rather than abort.

Session id: cron:clickhouse-worker-slot-1:20260616-125600

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat done. #107107 now throws BAD_ARGUMENTS at RemoteQueryExecutor::processReadTaskRequest when a cluster function is nested inside another distributed query, with no new setting and no protocol change. Dropped the ClientInfo flag and the setting prototype; the diff is one source change plus the regression test.

Verified both directions on a debug build: without the change the nested clusterAllReplicas(urlCluster(...)) aborts the server with the Distributed task iterator is not initialized logical error; with it the query returns BAD_ARGUMENTS and the server stays alive. Test 03850 covers url/file (rejected), s3 (no abort), and the legitimate top-level and INSERT-SELECT paths (still distribute, each task read once). Passes on both analyzers.

Closing the setting prototype #107572 in favor of this.

@@ -800,8 +801,14 @@ bool RemoteQueryExecutor::setPartUUIDs(const UUIDs & uuids)

void RemoteQueryExecutor::processReadTaskRequest()
{
/// No task_iterator here means a cluster table function was nested inside another distributed
/// query (e.g. clusterAllReplicas(..., urlCluster(...))): the initiator installs an iterator
/// only for the legitimate top-level dispatch paths. Reject it instead of aborting the server.
if (!extension || !extension->task_iterator)

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.

@groeneai, I'm sure there can be many ways to enter this branch due to a bug. We need a better detection of "cluster table function was nested inside another distributed query"; otherwise, we can just hallucinate this error message.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@nickitat, you are right that the bare !task_iterator test reads as a catch-all, so let me share what actually reaches this branch and a way to make the detection positive.

Protocol::Server::ReadTaskRequest is cluster-function-only. It is written in exactly one place (TCPHandler::sendReadTaskRequest, via the cluster read-task callback at TCPHandler.cpp:739), and that callback is invoked only by the three cluster-function source iterators (StorageURL glob, StorageFile glob, StorageObjectStorageSource). Parallel replicas and plain Distributed use a different packet (MergeTreeReadTaskRequest). So once we are inside processReadTaskRequest, a cluster function is definitely running on the worker. All three legitimate dispatch sites (IStorageCluster, INSERT-SELECT FROM *Cluster, distributedWriteFromClusterStorage) install a non-null task_iterator unconditionally, so a legit dispatch can never reach the null branch. That part is not a guess.

Where you are right: two query shapes reach the null-iterator branch, and only one is a literal nested function, so the message can over-claim:

  1. clusterAllReplicas('c', urlCluster(...)) - the initiator executor has no extension at all (extension == nullptr).
  2. an object-storage / DataLake table read nested under an outer parallel-replicas read - the initiator executor has parallel_reading_coordinator set but no task_iterator (DatabaseDataLake.cpp enables the worker-side distributed read from collaborate_with_initiator && can_use_parallel_replicas). No literal cluster function here, so "cannot be nested" is misleading.

Both are genuinely unsupported and crash today, so throwing in both is correct; only the wording is too specific for case 2.

Proposed positive detection (no new setting, no flag): split the branch on the extension shape we already have.

  • extension && extension->parallel_reading_coordinator -> parallel-replica read that tried to drive a cluster-function task iterator without one being installed. Throw BAD_ARGUMENTS with a message about that case ("reading this table with parallel replicas requires a cluster-function task iterator that was not provided").
  • otherwise (no extension, the nested clusterAllReplicas(..., <fn>Cluster(...)) shape) -> the BAD_ARGUMENTS "cannot be nested" message.

This keeps it to existing fields, makes each message describe only the shape it fires on, and never mislabels an unrelated bug, since reaching here at all already proves a cluster-function read is in flight. If you prefer one uniform BAD_ARGUMENTS message for both shapes (simpler, slightly less specific), I am happy to do that instead. Which do you want before I push?

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.

Let's split into two cases, each with its own exception message. Also pls make sure tests cover both of them.

A cluster table function (urlCluster, fileCluster, s3Cluster, ...) nested
inside another distributed query, e.g. clusterAllReplicas(..., urlCluster(...)),
ran as a secondary query, enabled distributed reads and sent a read-task
request back to an initiator that installed no cluster-function task iterator.
That hit a LOGICAL_ERROR "Distributed task iterator is not initialized" in
RemoteQueryExecutor::processReadTaskRequest, which aborts the server in debug
builds (found by the BuzzHouse fuzzer, STID 4662-3e65 / 4662-4342).

A read-task request reaches this gate only from a worker running a cluster
table function or object storage source with distributed reads enabled, and the
initiator installs a task iterator only for the legitimate dispatch paths
(top-level *Cluster read, INSERT INTO distributed SELECT FROM *Cluster). A
missing iterator therefore means the source was reached through an outer
distribution, which is unsupported. Two distinct shapes reach it, so each gets
its own BAD_ARGUMENTS message (a normal query error that leaves the server
alive) rather than the LOGICAL_ERROR:

  - no extension at all: the function is nested directly inside an outer
    clusterAllReplicas / Distributed broadcast;
  - an extension with a parallel-reading coordinator but no task iterator: the
    function is reached inside a query that runs with parallel replicas.

The residual case (an extension with neither a task iterator nor a coordinator)
is not produced by any normal query path and keeps a LOGICAL_ERROR so a genuine
internal bug is not mislabeled as a nested cluster function. No new setting or
protocol change is needed.

Closes: ClickHouse#91736

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-nested-cluster-table-function-task-iterator branch from 9b60b55 to 159048a Compare June 16, 2026 21:11
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Two shapes, each on demand on a single server with the standard test clusters and prefer_localhost_replica=0 so the inner query ships as a real secondary query. Shape 1: SELECT count() FROM clusterAllReplicas('test_cluster_one_shard_three_replicas_localhost', urlCluster('test_cluster_two_shards', 'http://localhost:HTTP/?query=SELECT+1', 'TSV', 'x UInt8')). Shape 2: SELECT count() FROM mt WHERE x IN (SELECT toUInt32(x) FROM urlCluster(...)) SETTINGS enable_analyzer=1, enable_parallel_replicas=1, max_parallel_replicas=3, cluster_for_parallel_replicas='test_cluster_one_shard_three_replicas_localhost', parallel_replicas_for_non_replicated_merge_tree=1, parallel_replicas_local_plan=0.
b Root cause explained? A ReadTaskRequest reaches processReadTaskRequest on the initiator only from a worker running a cluster table function or object storage source with distributed reads enabled. Serving it needs a task iterator, installed only on the legitimate dispatch paths. When the source is reached through an outer distribution no iterator is present, so the old single LOGICAL_ERROR "Distributed task iterator is not initialized" fired and aborted the server in debug builds.
c Fix matches root cause? Yes. The branch is split by the executor state that distinguishes the two unsupported shapes: no extension (nested directly in a broadcast) vs an extension with a parallel-reading coordinator but no task iterator (reached under parallel replicas). Each throws BAD_ARGUMENTS with its own message; the never-produced residual (neither field set) keeps LOGICAL_ERROR so a genuine internal bug is not mislabeled as a nested cluster function.
d Test intent preserved / new tests added? Test 03850_nested_cluster_table_function_task_iterator.sh updated to cover BOTH shapes by their distinct messages (url + file for shape 1, urlCluster under parallel replicas for shape 2) and to keep the legitimate top-level urlCluster (returns 1) and INSERT INTO distributed SELECT FROM urlCluster (each task read once, 3 rows) distribution cases.
e Both directions demonstrated? Yes. Without the fix (reverted to the single LOGICAL_ERROR, rebuilt) both shapes abort the server (<Fatal> BaseDaemon stack, then Connection refused: the CIDB crash). With the fix both shapes return their BAD_ARGUMENTS message and the server stays alive. Test passes 20/20 with full randomization and 5/5 under each of enable_analyzer=0 and enable_analyzer=1.
f Fix is general, not a narrow patch? Yes. The fix is at the single shared chokepoint every cluster function funnels through, so url/file/s3/object-storage are covered uniformly with no per-function changes. The split keys on existing Extension fields (no new setting, no protocol change); the residual branch keeps LOGICAL_ERROR so unknown bugs are not silently relabeled.

Session id: cron:clickhouse-worker-slot-0:20260616-202500

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat done, pushed the two-case split.

processReadTaskRequest now branches on the executor state, each case its own BAD_ARGUMENTS message:

  • no extension (nested directly in a clusterAllReplicas/Distributed broadcast): "cannot be nested inside another distributed query";
  • extension with a parallel-reading coordinator but no task iterator (reached inside a query running with parallel replicas): "cannot use distributed processing inside a query that runs with parallel replicas".

On the "don't hallucinate" worry: the residual case (an extension with neither a task iterator nor a coordinator) is not produced by any normal query path, so it keeps LOGICAL_ERROR rather than claiming a nested cluster function. No new setting or protocol change.

03850 now covers both shapes by their distinct messages, plus the legitimate top-level urlCluster and INSERT INTO distributed SELECT FROM urlCluster cases. Verified both directions locally (without fix: server abort with the old LOGICAL_ERROR; with fix: the two BAD_ARGUMENTS, server alive), 20/20 with randomization and 5/5 under each analyzer.

@nickitat

Copy link
Copy Markdown
Member

@groeneai, check that the changes in this PR are compatible with #100146

An explicit object storage cluster function (s3Cluster, azureBlobStorageCluster,
hdfsCluster, ...) nested inside an outer distributed query did not reach the
nested-cluster-function gate: on the secondary query it gated distributed reads
on collaborate_with_initiator, which is false under clusterAllReplicas, so it
silently read the whole object on every outer replica and multiplied the row
count instead of being rejected. urlCluster and fileCluster always request a
distributed read on a secondary query and are correctly rejected.

Make the object storage cluster functions request a distributed read on a
secondary query too, so they reach RemoteQueryExecutor::processReadTaskRequest
and the initiator decides uniformly for every *Cluster function: it serves the
read task when it installed an iterator (the legitimate top-level and
INSERT INTO distributed SELECT FROM *Cluster dispatch) and rejects it with
BAD_ARGUMENTS otherwise (the nested shapes). This supersedes the earlier
defensive gate that avoided the LOGICAL_ERROR by skipping distributed reads,
now that the gate raises a normal query error instead of aborting.

03850 now also covers nested clusterAllReplicas(..., s3Cluster(...)).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 05b9dbb, object-storage uniform rejection)

# Question Answer
a Deterministic repro? Yes. SELECT count() FROM clusterAllReplicas('test_cluster_one_shard_three_replicas_localhost', s3Cluster('test_cluster_two_shards', '<minio object>', 'TSV', 'x UInt8')) SETTINGS prefer_localhost_replica = 0 returns the row count times the replica count (3 for a 1-row object, 9 for a 3-row object) on the pre-fix binary, every run, under both analyzers.
b Root cause explained? clusterAllReplicas ships the inner query with no RemoteQueryExecutor::Extension, so collaborate_with_initiator is false on the secondary query. TableFunctionObjectStorageCluster::executeImpl gated distributed_processing on collaborate_with_initiator && hasClusterFunctionReadTaskCallback(), so it built a local glob iterator instead of a ReadTaskIterator, never sent a ReadTaskRequest, and read the whole object on every outer replica. url/file hard-code distributed_processing = true on a secondary query, so only they reached the rejection gate.
c Fix matches root cause? Yes. Object storage cluster functions now also request the distributed read on a secondary query, so they reach RemoteQueryExecutor::processReadTaskRequest and the initiator rejects the nested case (no iterator) with BAD_ARGUMENTS, exactly like url/file. This removes the asymmetry rather than masking it.
d Test intent preserved / new tests added? Yes. 03850 gains a nested clusterAllReplicas(..., s3Cluster(...)) case asserting the shape-1 rejection message. Existing shapes and the legitimate top-level / INSERT-SELECT cases are unchanged.
e Both directions demonstrated? Yes. Pre-fix: returns 3 / 9 (silent duplication). Post-fix: BAD_ARGUMENTS "cannot be nested inside another distributed query" under both analyzers, server alive. Legitimate top-level s3Cluster returns the correct 3 and INSERT INTO distributed SELECT FROM s3Cluster reads each task once (3).
f Fix is general, not a narrow patch? Yes. The change is at the shared object-storage secondary-query branch, so it covers s3Cluster, azureBlobStorageCluster, hdfsCluster and the iceberg cluster variants uniformly. The DataLake path (DatabaseDataLake.cpp) is a separate gate and is untouched. #100146's scenarios were re-verified on this build with no Distributed task iterator is not initialized.

Session id: cron:clickhouse-worker-slot-0:20260617-115200

@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 22/25 (88.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@nickitat

Copy link
Copy Markdown
Member

@groeneai, the automated review claims there is a regression:

[src/Databases/DataLake/DatabaseDataLake.cpp:711] DataLakeCatalog still uses collaborate_with_initiator && can_use_parallel_replicas as the signal to enable object-storage task reads. In a parallel-replicas secondary query this signal is also true when the initiator has only parallel_reading_coordinator and no cluster-function task_iterator; the DataLake StorageObjectStorage source then sends ReadTaskRequest and hits the new BAD_ARGUMENTS branch in RemoteQueryExecutor::processReadTaskRequest instead of the local-read behavior restored by #100146. That regresses supported DataLakeCatalog queries evaluated inside a parallel-replicas query, even though they are not explicit nested *Cluster table functions.
Suggested fix: make the DataLake path enable distributed_processing only when the initiator actually installed a cluster-function task_iterator, or explicitly disable it for nested parallel-replicas secondary queries.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat full analysis is inline at #107107 (comment); recap since you raised it at top level. This is not a regression: on master that path crashes the server, and the PR turns the crash into a clean error.

Three checkable facts:

  1. On master, processReadTaskRequest throws LOGICAL_ERROR "Distributed task iterator is not initialized" and aborts the server when there is no task_iterator (

    void RemoteQueryExecutor::processReadTaskRequest()
    {
    if (!extension || !extension->task_iterator)
    throw Exception(ErrorCodes::LOGICAL_ERROR, "Distributed task iterator is not initialized");
    ). It does not local-read. The nested DataLake-under-parallel-replicas read hits exactly that throw on master today.

  2. Fix distributed task iterator not initialized exception with parallel replicas #100146 restored local-read only for the plain s3/url table functions, by hard-coding distributed_processing = false in TableFunctionObjectStorage. Its only change to DatabaseDataLake.cpp was renaming can_use_distributed_iterator to distributed_processing; the gate collaborate_with_initiator && can_use_parallel_replicas was unchanged. It did not make the DataLake catalog path local-read.

  3. This PR does not modify DatabaseDataLake.cpp. That gate is byte-identical to master (

    const bool distributed_processing =
    context_->getClientInfo().collaborate_with_initiator
    && can_use_parallel_replicas;
    ). The PR changes only the initiator throw (LOGICAL_ERROR to BAD_ARGUMENTS) and the object-storage cluster secondary-query branch.

So for the DataLake path the PR is strictly crash to clean error; nothing that works today regresses.

On the suggested fix "enable distributed_processing only when the initiator installed a task_iterator": that is what the gate already does, expressed as the initiator-side check. The worker cannot know whether an iterator was installed, because the legitimate top-level DataLake cluster dispatch and the nested case both run as secondary queries with collaborate_with_initiator=true and can_use_parallel_replicas=true, both set distributed_processing=true, and both send a ReadTaskRequest. The distinction exists only on the initiator, which is where the rejection lives. Local-read on the worker instead would need the initiator-to-worker flag we dropped per your no-new-flag guidance.

I lean to keeping the clean BAD_ARGUMENTS here, matching the url/file/s3 nested cases. If you want it to local-read rather than error, that needs the dropped flag reinstated. Your call.

@nickitat nickitat left a comment

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.

LGTM

@nickitat

nickitat commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

@devcrafter, this patch looks reasonable to me, but I'd appreciate your opinion.
One thing worth considering is a new, more specific error code for this case. WDYT?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nickitat thanks. On a more specific code: this is really "an unsupported query shape" rather than malformed arguments, and the codebase already has a convention for that class:

  • SUPPORT_IS_DISABLED for "X not supported with parallel replicas": IN-with-subquery (Planner.cpp, GlobalSubqueriesVisitor.cpp), FINAL (Planner.cpp, InterpreterSelectQuery.cpp), STREAM (MergeTreeDataSelectExecutor.cpp).
  • NOT_IMPLEMENTED for distributed-shape rejections: "Distributed execution is not supported for such DDL queries" (executeDDLQueryOnCluster.cpp), EXPLAIN ... distributed=1 with serialize_query_plan/json/graph (ReadFromRemote.cpp, InterpreterExplainQuery.cpp).

There is no existing dedicated code for cluster-function nesting, so the options are:

  1. keep BAD_ARGUMENTS (minimal surface);
  2. reuse SUPPORT_IS_DISABLED (closest sibling) or NOT_IMPLEMENTED;
  3. add a new ErrorCodes entry.

I'd lean to (2) with SUPPORT_IS_DISABLED: it matches the established convention and is semantically accurate without adding a new entry for a narrow case. The change is small either way, the 03850 test matches on the message text rather than the code, so no test change is needed. Happy to push whichever you and @ devcrafter prefer.

/// A ReadTaskRequest arrives only from a worker running a cluster table function or object storage
/// source with distributed reads. Serving it needs a task iterator, which only the legitimate
/// dispatch paths install; its absence means the source was reached through an outer distribution.
if (!extension)

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.

It looks to me as obscure way to fix the issue. I wonder why we do such implicit conclusion and in some internals, - imo, the cluster functions nesting should be detected more explicitly

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for looking. The detection is more principled than the single diff line suggests, so let me lay out why this gate is a precise signal rather than an implicit guess.

processReadTaskRequest is reachable only through the cluster-function ReadTaskRequest packet. That packet is sent in exactly one place (TCPHandler::sendReadTaskRequest), driven only by the ClusterFunctionReadTaskCallback, which is invoked only by the three cluster-function source iterators (StorageURL glob, StorageFile glob, StorageObjectStorageSource). Parallel replicas and MergeTree use a different packet (MergeTreeReadTaskRequest). So arriving in this method at all is positive proof that a cluster table function is executing on this worker; it is not deduced from unrelated internal state.

The throw also does not key on "iterator absent" as a catch-all. It keys on positive evidence that the executor is not a legitimate cluster dispatch:

  • !extension: the cluster function ran as a secondary query of a plain Distributed / clusterAllReplicas broadcast (those build the executor with no Extension).
  • parallel_reading_coordinator present but no task_iterator: it ran as a parallel-replicas secondary query.

The three legitimate dispatch sites (top-level IStorageCluster::read, StorageDistributed::distributedWriteFromClusterStorage, InterpreterInsertQuery) all build the Extension from getTaskIteratorExtension(), which always installs a non-null iterator, so they can never reach either branch. A genuine internal bug (a real cluster dispatch that lost its iterator) still hits the LOGICAL_ERROR, not the user-facing message, so the "nested" text fires only for the real nested case.

On detecting the nesting explicitly up-front: that was the original direction. An earlier revision carried an explicit ClientInfo::is_cluster_function_distributed_read flag (protocol-gated, set by the initiator only when it installs a cluster-function iterator), and a sibling PR prototyped a dedicated internal setting. Both were dropped at @ nickitat's request in favor of this single shared gate, because every cluster function funnels through processReadTaskRequest uniformly: no per-function plumbing, no protocol bump, and url / file / s3 / object-storage all behave the same. The earlier per-function detection also missed the DataLakeCatalog path until a follow-up caught it.

My recommendation is to keep the chokepoint detection. If you would still prefer explicit detection at analysis or planning time, I am glad to work it up, but since that reverses the design already signed off here I will leave the call to you and @nickitat.

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.

I don't like the code either, but beggars can't be choosers.

@nickitat
nickitat added this pull request to the merge queue Jun 30, 2026
Merged via the queue into ClickHouse:master with commit 3e22570 Jun 30, 2026
321 of 326 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 30, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-table-function-task-iterator

Reject nested cluster table functions with a clear error instead of crashing
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 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.

5 participants