Repository navigation
Fix input() read twice when the parallel-replicas row estimate builds an IN set - #121283
Conversation
Internal second-model review: adjudication log (click to expand)Four rounds by an independent model (engine: codex) plus my own cold read of the code each round:
Severity: ❌ blocker / Also measured and deliberately not raised as separate work: join runtime filters do not trip the new Session id: cron:clickhouse-review-slot-9:20260921-062200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260921-035600 |
|
Workflow [PR], commit [9960dc6] Summary: ✅
AI ReviewSummaryPR #121283 skips the advisory parallel-replica row estimate when its filter contains an unbuilt set, including sets inside nested Missing context / blind spots
Final VerdictStatus: ✅ Approve. No code changes requested; await the normal CI checks before merging. |
Build profile diff (arm_release)Commit See the job log for details. |
946f7d1 to
659c1b2
Compare
Flaky check on 946f7d1: the test's own
|
659c1b2 to
afeb59e
Compare
An INSERT SELECT whose filter references input() failed with INVALID_USAGE_OF_INPUT when parallel replicas were enabled together with a non-zero parallel_replicas_min_number_of_rows_per_replica. With that setting, collectFiltersForAnalysis runs in the Planner constructor over a throwaway planner that owns its own PreparedSets, so the filter DAG handed to the real read carries a ColumnSet for a FutureSetFromSubquery that planner will never build. The advisory replica-count estimate then called selectRangesToRead() purely to read selected_rows; index analysis reached KeyCondition::tryPrepareSetIndexForIn, which built that set and so executed the IN subquery. For input(), a one-shot stream from the client, that was the first read, and the query's own set then read it a second time. Gating the estimate is sufficient for this read because nothing else builds the escaped set on a ReadFromMergeTree step: applyFilters rebuilds filter_actions_dag from the real plan's pushed-down nodes and overwrites query_info.filter_actions_dag with it, and every other selectRangesToRead() caller runs after that. The estimate now declines when the filter DAG references a set that is not built yet, reusing QueryPlanOptimizations::dagContainsNonReadySet, which convertAnyJoinToSemiOrAntiJoin and Optimizations/Utils already use to make a plan-time decision decline rather than force a build. Both routes that reach this call site are covered: the direct planner path and the automatic-parallel-replicas probe plan. One consequence beyond the bug: the estimate no longer prunes with an IN (subquery) set, so it can use more replicas, never fewer for the same data, and, where index analysis would have built that set, it no longer runs the subquery an extra time while planning. The guard is coarser on purpose: it declines for any unbuilt set, while KeyCondition builds only key-column ones. Rejected alternatives. Disabling parallel replicas for any tree that reads input(): GLOBAL IN, a GLOBAL JOIN's materialized side, a reused MATERIALIZED CTE and every plain join are all materialized on the initiator, work today, and would lose the route; the exact predicate is only available after buildQueryTreeForShard, which executes the GLOBAL subqueries and so cannot be evaluated speculatively. Overriding parallel_replicas_min_number_of_rows_per_replica for such trees: silently changes a user setting and still leaves every other query executing its IN subquery twice. Buffering the client stream in StorageInput: a memory regression, and it guards the symptom rather than the cause. Running the estimate with KeyCondition's require_ready_sets instead of declining it: both entry points this call site can take pass the step's own `indexes` member by reference (ReadFromMergeTree.cpp:2735, :2763), so an estimate analysed that way memoizes a set-less KeyCondition on the step; the whole body of ReadFromMergeTree::applyFilters is then guarded by `if (!indexes)` and does nothing, and the executed read inherits that weaker analysis, losing IN-set primary-key pruning at read time. Declining leaves `indexes` empty, so applyFilters runs in full and the executed read analyses against the query's own set. Not addressed here, all of it outside the estimate this change gates. A plain IN (subquery) is re-executed on every follower, since parallel_replicas_allow_in_with_subquery defaults to 1, and a follower has no client input stream, so it throws INVALID_USAGE_OF_INPUT there; the initiator usually answers from its local plan first and discards that error, which makes the client seeing it a race. GLOBAL IN evaluates the subquery on the initiator and ships a temporary table, so the test uses that spelling for the two cases that read from a replica; without this change they still fail on the double read described above. With parallel_replicas_mode = custom_key_sampling a follower can still be asked to read input() and fails with "Input stream is not initialized", identically without this change. And collectFiltersForAnalysis collects the same unbuilt-set DAG for IStorageCluster irrespective of this setting (Planner.cpp:284), where ReadFromCluster::applyFilters falls back to query_info.filter_actions_dag and the task iterators build sets from it through VirtualColumnUtils::buildSetsForDAG. I traced that last one by reading and have not run it. Related: ClickHouse#71028 (comment) Co-Authored-By: Claude Opus 5 <[email protected]>
afeb59e to
8d6d483
Compare
|
|
||
| /// Answering the row estimate below runs index analysis, which builds any | ||
| /// `IN` set whose left argument maps to key columns and so executes its | ||
| /// subquery; `input()` is a one-shot client stream, and cannot be read twice. |
There was a problem hiding this comment.
ok, but we need to at least leave a log message that we've skipped the threshold application
There was a problem hiding this comment.
Added in dbd8b48: a LOG_DEBUG line, Skipping parallel_replicas_min_number_of_rows_per_replica, the filter has a set that is not built yet, emitted only when the threshold would otherwise have been applied (a single ReadFromMergeTree and parallel_replicas_min_number_of_rows_per_replica > 0).
|
|
||
| /// Answering the row estimate below runs index analysis, which builds any | ||
| /// `IN` set whose left argument maps to key columns and so executes its | ||
| /// subquery; `input()` is a one-shot client stream, and cannot be read twice. |
There was a problem hiding this comment.
and what is the problem exactly? we will read those rows now and build the set. afaiu, it should be preserved and later we can use it one more time, but we won't re-build it and thus we won't read the input again.
There was a problem hiding this comment.
The set the estimate builds is a different object from the one the query uses. query_info.filter_actions_dag here is the filter collected by collectFiltersForAnalysis, which plans the query with its own Planner (Planner.cpp:353 on master), so its IN node points to a FutureSetFromSubquery owned by that planner's PreparedSets (PlannerContext.h:237). The estimate builds that copy; the main planner's set for the same subquery is still unbuilt, and the query builds it again. Within one FutureSetFromSubquery it works as you describe: the in-place build publishes the set, and build() then returns early on isCreated().
Measured on master eef0f17166df and on this branch: SELECT count() FROM src WHERE k IN (SELECT n FROM sub), src 20000 rows ORDER BY k, sub 50 rows, the initiator's system.text_log in order:
parallel_replicas_min_number_of_rows_per_replica |
master | this PR |
|---|---|---|
1 |
Created Set with 50 entries, Estimated 352 rows to read, Created Set with 50 entries; SelectedRows 452 |
Skipping parallel_replicas_min_number_of_rows_per_replica ..., one Created Set; SelectedRows 402 |
0 (control) |
one Created Set; SelectedRows 402 |
the same |
1, IN (SELECT n FROM input('n UInt64')) |
Created Set with 3 entries, Estimated 48 rows to read, then Code: 477 from ReadFromMergeTree::applyFilters -> buildIndexes -> FutureSetFromSubquery::buildOrderedSetInplace -> ReadFromInput::initializePipeline |
3 rows inserted |
So an ordinary subquery runs twice (the extra 50 rows), and input() cannot be read the second time. I reworded the comment in dbd8b48 to say this. The other way to fix it is to let the query adopt the set the estimate already built; that is a bigger change, so I kept this PR to skipping the estimate.
Emit a debug line when `parallel_replicas_min_number_of_rows_per_replica` is not applied because the filter references a set that is not built yet, and say in the comment why such a set would be built twice: the filter comes from the `collectFiltersForAnalysis` plan, whose sets are not the ones the query builds later. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… estimate
`indexHint` keeps its arguments in a DAG of its own (`FunctionIndexHint::getActions`),
so `dagContainsNonReadySet` scanning only the outer nodes missed an unbuilt `IN` set
there. Index analysis still descends into that DAG, so the estimate built a throwaway
copy of the set: `WHERE indexHint(k GLOBAL IN (SELECT n FROM input('n UInt64')))` with
`parallel_replicas_min_number_of_rows_per_replica = 1` still failed with
`INVALID_USAGE_OF_INPUT`, and `indexHint(k IN (SELECT ...))` ran its subquery twice.
Collect the filter's sets with `appendSetsFromActionsDAG`, which already recurses into
(nested) hints, and decline when any of them is not built. `dagContainsNonReadySet` is
left as is: its other callers evaluate the filter, and `indexHint` evaluates to 1
without its arguments.
The test gains an `indexHint` case. It bounds the inserted rows, because the hint passes
every row of the granules it selects, so only that bound shows the read still pruned by
the set. The automatic-mode case is dropped: since ClickHouse#126815 the automatic mode's probe
plan never runs the estimate, so the case passed with this PR's change reverted.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 2d64602Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261022-083003 |
|
Fixing PR for the |
On top of ClickHouse#121283 the parallel-replicas row estimate declines when its filter references a set that is not built yet, which is the filter whose built sets appendBuiltSetsFromActionsDAG collected for reuseBuiltSets in createLocalPlanForParallelReplicas. Nothing is ever collected there any more, so the adoption is dead code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…plan With parallel_replicas_min_number_of_rows_per_replica > 0, collectFiltersForAnalysis plans a clone of the query in which only the join-tree tables are replaced by dummies, and it disabled parallel replicas only in the clone's top context. An IN subquery keeps its real table and shares its context with the original tree, so that throwaway planner planned the subquery with parallel replicas: a row estimate (one index analysis of the subquery's read), a coordinator and a local replica plan, none of which is ever executed since ClickHouse#121283 made the outer estimate decline on an unbuilt set. The real execution then analyzes the subquery read again. Copy the context of every QueryNode/UnionNode of the clone and disable parallel replicas there, the way the local replica plan, the remote plan and scalar subqueries already do. Copies are assigned to the clone's nodes only, so the original query tree keeps its settings. Related: ClickHouse#71028 Related: ClickHouse#118275 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed the parallel-replicas row estimate running an
IN (subquery)while planning, which made anINSERT ... SELECTwhose filter readsinput()fail withINVALID_USAGE_OF_INPUTwhenparallel_replicas_min_number_of_rows_per_replicawas not zero.Description
Related: #71028 (comment)
Not introduced by #71028. The same test failed with
477on v25.11.1.1 in the CI database; that PR's randomizer only makes it visible.Root cause. With that setting a throwaway planner with its own
PreparedSetscollects the filters in thePlannerconstructor, so the real read's DAG carries aColumnSetnobody will build. The replica-count estimate inbuildQueryPlanForTableExpressioncallsselectRangesToRead()just to readselected_rows; index analysis then reachesKeyCondition::tryPrepareSetIndexForIn, builds that set and runs theINsubquery: read one. The query's own set readsinput()again.The fix. That estimate declines when the filter references a set that is not built yet, including one inside an
indexHintargument (a DAG of its own); the sets are collected withappendSetsFromActionsDAG, which already walks nested hints. For aReadFromMergeTreestep it is the only index analysis before filter push-down: every otherselectRangesToRead()caller runs afterapplyFilterspopulated the step'sindexes. Cost: such a query no longer refines its replica count, so it can use more replicas, never fewer.Not fixed here. A plain
IN (subquery)is re-executed on every follower, which has no client input stream, so whether the client sees that error is a race. Withparallel_replicas_mode = custom_key_samplinga follower can still be asked to readinput(). AndcollectFiltersForAnalysishands the same unbuilt-set DAG to cluster storages irrespective of this setting, whose task iterators build sets from it (traced by reading only).Validation. New
05237_parallel_replicas_input_table_function.shcovers both client transports (asGLOBAL IN) andindexHint, asserting per case that the route was taken; eachinput()case fails with477when the change is reverted. The automatic mode is left out: since #126815 its probe plan skips this estimate. 500 randomized runs left no followerINVALID_USAGE_OF_INPUTbehind; 90 more with theindexHintcase are stable.Workflow [PR]
Sync PR [sync-upstream/pr/121283]
Version info
26.11.1.1459-master(included in26.11and later)