Repository navigation
Conversation
…m key
An INSERT SELECT whose filter reads input() failed with INVALID_USAGE_OF_INPUT
("Input stream is not initialized") when parallel_replicas_mode was
custom_key_sampling or custom_key_range, and the destination table stayed empty.
input() is a one-shot stream from the client, so StorageInput only has a pipe on
the server the client is talking to. The custom-key arm of the planner
(PlannerJoinTree.cpp) throws away the local MergeTree plan and calls
ClusterProxy::executeQueryWithParallelReplicasCustomKey, which, unlike the
task-based route, does not call buildQueryTreeForShard: it only clones the tree
and runs createUniqueAliasesIfNecessary, so nothing is materialized on the
initiator and the whole query, IN (SELECT n FROM input(...)) included, is shipped
to every replica. The replica then sees a plain SELECT rather than an
INSERT SELECT, so executeQuery takes the else arm and calls resetInputCallbacks(),
StorageInput::readImpl leaves the source pipe empty, and
ReadFromInput::initializePipeline throws on !was_pipe_initialized. A follower's
own log records what it received:
SELECT `__table1`.`k`, `__table1`.`v` FROM t AS `__table1`
WHERE and((`__table1`.`k` IN (SELECT `n` FROM input('n UInt64'))),
`k` < 6148914691236517205)
the custom-key range predicate appended and the input() subquery intact. That
query cannot be satisfied anywhere but on the initiator: the client stream is
never sent over the inter-server connection, and because it is one-shot it cannot
be consumed by three replicas. Splitting it would make each replica's IN set a
fragment, i.e. wrong results instead of an error. So the only correct outcome is
not to ship such a query.
Decline custom-key parallel replicas in Planner::buildPlanForQueryNode when the
query tree reads input(), as a third sibling of the two declines already there
for parallel_replicas_allow_in_with_subquery and additional_table_filters
(prior art 30f689a). Clearing
allow_experimental_parallel_reading_from_replicas on the planner's mutable query
context covers the plain-MergeTree, Distributed and view-over-Distributed
custom-key entry points at once, because all of them re-read the same context
flag. The decline is silent at every enable_parallel_replicas level, the forced 2
included. Unlike the three other declines in this function, its trigger says
nothing about whether custom key would have been used:
canUseParallelReplicasCustomKey() reads settings only (Context.cpp:9003-9013),
while the custom-key read additionally requires parallelReplicasEnabledForStorage
(PlannerJoinTree.cpp:2607, false for every non-MergeTree storage), so a throw
there would also reject INSERT INTO t SELECT n FROM input('n UInt64'), which has
nothing to distribute and works today. The test pins both.
The predicate is tested on query_info.query_tree, which is exactly the object
ClusterProxy::executeQuery ships, so for this route it is neither over- nor
under-inclusive. The walk is explicit rather than `traverseQueryTree` or one of
the single-purpose helpers (`hasFunctionNode`, `hasAggregateFunctionNodes`): the
helpers refuse QUERY and UNION children, which would make the predicate always
false and ship nothing, and `traverseQueryTree` skips a table function's
unresolved arguments (`traverseQueryTree.h:58-70`) without routing that skip
through its `should_visit` predicate.
`TableFunctionView::skipAnalysisForArguments` marks the query `view()` takes
unresolved, so `IN (SELECT n FROM view(SELECT n FROM input(...)))` keeps an
`input()` node whose `getStorage()` is null; matching the table function name as
well as the storage catches it, and the test pins that shape.
parallel_replicas_mode = sampling_key is not covered, being excluded from
canUseParallelReplicasCustomKey(), and is measured unchanged.
Measured before and after on one debug server with three loopback replicas: both
custom-key modes, HTTP and native transports, IN on a key and on a non-key
column, GLOBAL IN and a Distributed source all go from 477 to the exact expected
rows; a GLOBAL JOIN and sampling_key mode are unchanged; serialize_query_plan no
longer reaches its NOT_IMPLEMENTED throw. A query that does not read input()
keeps its custom-key split, which the new test asserts so it cannot pass
vacuously.
The walk skips one child deliberately: a reused MATERIALIZED CTE's defining
subquery. Such a CTE is evaluated on the initiator and registered as an
external table, and TableNode::toASTImpl emits only its temporary table name,
so its input() is never part of what a replica receives. A CTE referenced once
is inlined instead (and with enable_materialized_cte off the MATERIALIZED
keyword is ignored altogether), so that shape still reaches the input() node
and is still declined. Without the skip the reused shape kept correct rows but
lost its custom-key split, 3 remote sub-queries to 0.
Compress the analyzer-resolution note to one bare invariant line, and state the reused-materialized-CTE property without citing TableNode::toASTImpl internals. The three domain-property comments (what input() is, what an unresolved table function node lacks, what custom-key mode sends) are kept.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 6 findings over 7 gate runs, plus my
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260921-172400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260921-035800, cron:clickhouse-impl-slot-4:20260921-055200, cron:clickhouse-impl-slot-7:20260921-071000, cron:clickhouse-impl-slot-7:20260921-094000, cron:clickhouse-impl-slot-7:20260921-161400 |
|
Workflow [PR], commit [b9d0d0c] Summary: ✅
AI ReviewSummaryThis PR fixes the follower-side Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage Report |
| /// `input()` is a one-shot stream from the client: the data arrives on the connection that carries | ||
| /// the query, so the storage is only readable on the server the client is talking to. | ||
| /// An unresolved table function node, such as one inside the query `view()` takes, has no storage, so only its name identifies it. | ||
| bool readsInputTableFunction(const QueryTreeNodePtr & root) |
There was a problem hiding this comment.
This helper only looks at the raw query tree, so it also matches GLOBAL IN subqueries that the analyzer path will materialize on the initiator and ship as an external table. In that shape the remote query is already globalIn(..., ?) and no replica executes input(), but the caller still disables custom-key parallel replicas because the original subquery remains in the tree here. Can we drive this from the prepared-set metadata produced by collectSets() instead of treating every input() occurrence as unsafe?
There was a problem hiding this comment.
I measured this before touching anything, because it turns on whether GLOBAL IN really is materialized on this route. It is not.
Custom-key dispatch goes through ClusterProxy::executeQueryWithParallelReplicasCustomKey (src/Interpreters/ClusterProxy/executeQuery.cpp:1288-1316), which renumbers __tableN aliases and does nothing else. Materializing a GLOBAL IN subquery into a temporary external table happens in buildQueryTreeForShard (src/Storages/buildQueryTreeForShard.cpp:615, create_for_global_subquery at :657-662), and this path never calls it. What a follower actually received on master (3-replica cluster, parallel_replicas_mode = 'custom_key_sampling'):
(in query: SELECT `__table1`.`k` AS `k`, `__table1`.`v` AS `v` FROM `c7min_e_s14base`.`t_pr_input` AS `__table1` WHERE and((`__table1`.`v` GLOBAL IN (SELECT `__table1`.`n` AS `n` FROM input('n UInt64') AS `__table1`)), positiveModulo(`k`, 3) = 1))
GLOBAL IN and its subquery verbatim, with the custom-key predicate appended. The globalIn(v, __set_...) form does appear in that log, but under the same three query ids as the three Code: 477 errors, so it is each replica's own prepared set for the subquery it was handed, not a set the initiator built and shipped.
Outcome on the same rig, build id asserted before every run:
INSERT INTO dst SELECT k, v FROM t WHERE v GLOBAL IN (SELECT n FROM input('n UInt64')) |
master ce4d387d |
this PR |
|---|---|---|
| inserted rows | Code: 477 from 127.0.0.2, destination empty |
(7,14),(19,38) |
| remote sub-queries | 3 | 0 (declined) |
control query without input() |
3 | 3 |
So a replica does read input() in that shape and the decline is what fixes it, rather than an over-fire.
For the construct where your reasoning does hold the helper already exempts it: a reused MATERIALIZED CTE is evaluated on the initiator and sent as an external table, so its defining subquery is skipped, and the test pins that such a query keeps its split. collectSets() runs just before this site, so its metadata is available, but what it records is that a set will be prepared, not whether the subquery reaches a replica.
| if (query_context->canUseParallelReplicasCustomKey() && readsInputTableFunction(query_tree)) | ||
| { | ||
| auto & mutable_context = planner_context->getMutableQueryContext(); | ||
| mutable_context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); |
There was a problem hiding this comment.
This unconditional setSetting(..., 0) changes enable_parallel_replicas = 2 from “throw if parallel replicas cannot be used” to a silent local fallback for queries that really do have a custom-key-eligible read, for example INSERT INTO dst SELECT ... FROM t WHERE k IN (SELECT n FROM input(...)). The setting docs and the other decline sites in this function both treat >= 2 as a hard failure. If we want to keep INSERT ... SELECT n FROM input(...) working, the refusal needs to move to the custom-key dispatch sites that know whether a real parallel read would have happened instead of clearing the setting here in the planner.
There was a problem hiding this comment.
Conceded on the fact: at enable_parallel_replicas = 2 this site clears the setting instead of throwing, and it is the only one of the five declines in this function that stays silent. The PR body says so.
The throw is what I shipped first, and it broke a query that works on master. Same rig, build id asserted before every run, enable_parallel_replicas = 2, custom_key_sampling, 3 replicas:
| insert | master ce4d387d |
this PR |
|---|---|---|
... SELECT k, v FROM t WHERE k IN (SELECT n FROM input('n UInt64')) |
Code: 477, destination empty |
(7,14),(19,38),(123,246) |
... SELECT n FROM input('n UInt64') |
7,19,123 |
7,19,123 |
control without input() |
3 remote sub-queries | 3 |
Row 1 is your eligible example. It already fails on master at level 2, with INVALID_USAGE_OF_INPUT rather than SUPPORT_IS_DISABLED, so no query that works today changes behaviour. Row 2 is master itself staying silent at level 2 when there is nothing to distribute, and a throw at this site is what turns it into SUPPORT_IS_DISABLED.
Moving the refusal to the dispatch sites is not an increment on top of this either. Storage eligibility is not known in the planner: parallelReplicasEnabledForStorage is defined in PlannerJoinTree.cpp:1538 with no header declaration, and the storages are resolved in collectTableExpressionData, which runs after this block. One clear here covers PlannerJoinTree.cpp:2018, :2026, :2381, :2618, StorageDistributed.cpp:484 and ClusterProxy/executeQuery.cpp:469-505 at once, so throwing at :2618 alone restores the 477 for a Distributed source.
If a maintainer wants level 2 to fail for custom-key-eligible reads, say the word and I will move the refusal to every dispatch arm in this PR.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units75 translation units recompiled, 133 s compile time in total, 75 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
INVALID_USAGE_OF_INPUT("Input stream is not initialized") for anINSERT ... SELECTreading theinput()table function whenparallel_replicas_modeiscustom_key_samplingorcustom_key_range: such a query is no longer distributed, sinceinput()is a one-shot client stream that only exists on the initiator.Description
Related: #71028 (comment) (class 7 mechanism (2)/(3); mechanism (1) is #121283)
On 26.3, 26.6 and 26.9,
INSERT INTO dst SELECT * FROM t WHERE k IN (SELECT n FROM input('n UInt64'))is rejected withINVALID_USAGE_OF_INPUTand leavesdstempty whenparallel_replicas_mode = 'custom_key_sampling', althoughenable_parallel_replicas = 1is documented to disable parallel replicas silently rather than fail. (Measured on 26.10; the path is present on all three.)Custom-key parallel replicas replace the local read with a cluster read of the whole query tree and materialize nothing on the initiator, so the
input()subquery ships verbatim andReadFromInputthrows on a replica that has no pipe. A follower's log shows:No replica can satisfy that, and splitting a one-shot stream would fragment each replica's
INset, so the planner declines custom-key parallel replicas for such a query, alongside the four declines already inPlanner::buildPlanForQueryNode.It is the only one of the five that stays silent at
enable_parallel_replicas = 2, and the reason is measured rather than stylistic: its trigger reads settings only, so throwing here also rejectsINSERT INTO t SELECT n FROM input('n UInt64'), which works today. An earlier revision of this PR did exactly that. Throwing only for the eligible case means moving the refusal to each custom-key dispatch site; say the word and I will.Measured before and after on both custom-key modes, both transports,
GLOBAL IN, aDistributedsource andserialize_query_plan. A query withoutinput()keeps its custom-key split, asserted in the test, as does a reusedMATERIALIZEDCTE, which ships as an external table.Workflow [PR]
Sync PR [sync-upstream/pr/121414]