Repository navigation
Conversation
|
Workflow [PR], commit [f9f2caf] Summary: ❌
AI ReviewSummaryThis PR adds a new query-plan optimization that pushes Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: Minimum required actions:
|
3ed749e to
3a32017
Compare
|
rebased |
687f430 to
339f7ac
Compare
|
Right now, what I'm working on is replicating the issue since some of these tests are actually passing locally I'm speculating here, but the ones I couldn't run easily due to the test setup might be the culprit for the failure through some side effects. |
1f4f187 to
a27a571
Compare
5e77ae3 to
da6d876
Compare
da6d876 to
df1ab4a
Compare
novikd
left a comment
There was a problem hiding this comment.
The implementation is currently overcomplicated. It would be much simpler and less code if only 2 query plan steps were analyzed at a time.
| {"os_threads_nice_value_query", 0, 0, "New setting."}, | ||
| {"os_threads_nice_value_materialized_view", 0, 0, "New setting."}, | ||
| {"os_thread_priority", 0, 0, "Obsolete setting."}, | ||
| {"query_plan_push_down_volume_reducing_functions", false, false, "A new setting"}, |
There was a problem hiding this comment.
| {"query_plan_push_down_volume_reducing_functions", false, false, "A new setting"}, | |
| {"query_plan_push_down_volume_reducing_functions", false, true, "A new setting"}, |
| } | ||
| LimitStep * limit_step = typeid_cast<LimitStep *>(node->step.get()); | ||
| // for non limit steps, we may move the max push down point | ||
| if (!limit_step) |
There was a problem hiding this comment.
This means that expression will be pushed through every step except LimitStep, but it is not correct. For example, you can't always push through AggregationStep.
SELECT sum(length(s)) FROM test_table GROUP BY s;There was a problem hiding this comment.
Yes, we do the opposite. As the limit doesn't transform, we can push through. For other steps like aggregation, we set the max pushdown point so we don't touch the column until after that step.
| struct ColumnCandidate | ||
| { | ||
| /// This represents how far back functions using this node can be pushed down | ||
| QueryPlan::Node * max_pushdown_point; |
There was a problem hiding this comment.
You don't need to find the end point of the pushdown process. You can just handle pair parent -> child and push expression from parent through child. It then can be done in cycle. See tryPushDownFilter in filterPushDown.cpp.
There was a problem hiding this comment.
That was the initial plan, but I wanted to cover more cases, such as the below, which wouldn't be possible if you are only looking at 2 steps.
https://fiddle.clickhouse.com/c1d8816f-7327-4614-ada1-5ba1be6c293c

There was a problem hiding this comment.
I think what we can do is handle cases like the join case attached above with a separate optimization, wdyt?
| }; | ||
|
|
||
| /// Represents a request to push down a volume-reducing function | ||
| struct PushdownRequest |
|
|
||
| void pushDownVolumeReducingFunctions(QueryPlan::Node * root_node, const QueryPlanOptimizationSettings & optimization_settings) | ||
| { | ||
| if (!optimization_settings.push_down_volume_reducing_functions) |
There was a problem hiding this comment.
We usually check settings outside of optimization function
| NodeToParentsMap direct_parent_nodes_map = buildDirectParentNodesMap(root_node); | ||
| processNodeDFS(node, {}, direct_parent_nodes_map); |
There was a problem hiding this comment.
You won't need it if you push expression only through one expression at a time
| /** Indicates whether this function is suitable for being pushed down before a filter operation. | ||
| * Functions that reduce data volume (e.g., aggregations) may benefit from early evaluation. | ||
| */ | ||
| virtual bool isSuitableForPushDownBeforeFilter() const { return false; } |
There was a problem hiding this comment.
Let's rename to something like isVolumeReducing, because this optimization is unrelated to filters.
|
Thanks for the review @novikd
I think we could limit the scope of the optimization and accept that some cases may not be covered |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 4 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
| /// Process each non-INPUT, non-COLUMN node only once. | ||
| if (processed.contains(actual)) | ||
| continue; | ||
| processed.insert(actual); |
There was a problem hiding this comment.
Shared VR node causes incorrect pushdown with missing column
High Severity
When an ActionsDAG shares a VR function node between a direct output and an intermediate computation used by a non-VR function (e.g., length(s) appears both as an output and as a child of concat or >), the BFS processed set prevents re-processing the VR node from the non-VR path. The safety verification only checks immediate INPUT-type children of non-candidate functions, missing transitive dependencies through the shared VR node. This causes the source column to be removed from the data stream while still being needed by the non-VR function's path, resulting in a missing-column runtime error.
Additional Locations (1)
| {"os_threads_nice_value_query", 0, 0, "New setting."}, | ||
| {"os_threads_nice_value_materialized_view", 0, 0, "New setting."}, | ||
| {"os_thread_priority", 0, 0, "Obsolete setting."}, | ||
| {"query_plan_push_down_volume_reducing_functions", false, false, "A new setting"}, |
There was a problem hiding this comment.
Settings change history has wrong new default value
Medium Severity
The query_plan_push_down_volume_reducing_functions entry in the settings change history uses {false, false} but the actual default declared in Settings.cpp is true. The second value (new default) needs to be true to match. The reviewer also explicitly suggested {false, true} in a review comment that was not applied.
| {"evaluation_time", 0, 0, "Old setting which popped up here being renamed."}, | ||
| {"os_threads_nice_value_query", 0, 0, "New setting."}, | ||
| {"os_threads_nice_value_materialized_view", 0, 0, "New setting."}, | ||
| {"os_thread_priority", 0, 0, "Obsolete setting."}, |
There was a problem hiding this comment.
Duplicate os_thread_priority entry accidentally committed
Medium Severity
This PR adds a new os_thread_priority entry with description "Obsolete setting." on line 262, creating a duplicate of the existing entry on line 264 ("Alias for os_threads_nice_value_query."). This appears to be an unrelated change accidentally included during rebase, resulting in two entries for the same setting in the same version block.
|
|
||
| default: | ||
| break; | ||
| } |
There was a problem hiding this comment.
ANTI join pushdown sides logic is inverted
Low Severity
For JoinKind::Left with JoinStrictness::Anti, push_to_left is set to false while push_to_right stays true. This is inverted: LEFT ANTI JOIN outputs only left-side columns (rows without a match), so pushing to the left side is safe while the right side has no output columns. The symmetric issue exists for RIGHT ANTI. In practice this prevents a valid optimization rather than causing incorrect results, since no right-side candidates would exist for LEFT ANTI.
# Conflicts: # src/Processors/QueryPlan/Optimizations/Optimizations.h # src/Processors/QueryPlan/Optimizations/liftUpFunctions.cpp
The CI style check failed on two for-loops with `; )` — the check rejects whitespace before `)`. See ClickHouse#86139
…ons` Two issues called out by review feedback on PR ClickHouse#86139: - The actual default declared in `Settings.cpp` is `true`, but the changes-history entry recorded `{false, false}`. Fixed to `{false, true}` per @novikd's review suggestion. - A duplicate `os_thread_priority` entry was accidentally added during a rebase; the canonical entry "Alias for os_threads_nice_value_query." is preserved. See ClickHouse#86139
For `LEFT ANTI` / `RIGHT ANTI`, output rows are taken from the preserved side only (no columns from the eliminated side flow to the output), so pushdown should target the preserved side — the same side already used for non-`ANTI` `LEFT`/`RIGHT`. The previous logic flipped `push_to_left`/`push_to_right` for `ANTI`, which silently disabled the optimization on the side where it could actually fire. Reported by cursor bugbot on PR ClickHouse#86139.
The previous name suggested the property was tied to filter pushdown, but the optimization is about volume-reducing functions in general (it does not depend on the presence of a filter). Renamed to reflect the actual semantics, addressing review feedback from @novikd on PR ClickHouse#86139. The template parameter `is_suitable_for_push_down_before_filter` in `FunctionStringOrArrayToT` is renamed similarly to `is_volume_reducing`.
The previous commit (`isVolumeReducing` rename) accidentally bumped submodule pointers because the worktree had submodules at stale SHAs left over from before the merge. Restore them to the values introduced by the master merge. See ClickHouse#86139
| if (typeid_cast<const LimitStep *>(step)) | ||
| return false; | ||
|
|
||
| if (const auto * distinct = typeid_cast<const DistinctStep *>(step)) |
There was a problem hiding this comment.
DistinctStep::getColumnNames() being empty means DISTINCT keys are all input columns (see DistinctTransform: columns_.empty() ? header_->columns() : ...).
In this branch we return false when the list is empty, so pushdown can treat the source column as removable and rewrite the DISTINCT input from source to f(source). That changes dedup semantics for all-column DISTINCT.
Can we treat columns.empty() as "source is used" (or conservatively bail out) here?
|
|
||
| SELECT 'Test 1: Basic length function'; | ||
| (SELECT length(s), length('constant'), test_uint64 FROM test_data WHERE s != '' ORDER BY id SETTINGS query_plan_push_down_volume_reducing_functions = 0) | ||
| EXCEPT |
There was a problem hiding this comment.
These validations are one-way EXCEPT (setting=0 minus setting=1). That misses cases where the optimized plan returns extra rows or different multiplicities, because EXCEPT is distinct and non-symmetric.
Could we make this symmetric (both directions, or another equality check that preserves multiplicity) at least for the JOIN/UNION/DISTINCT-sensitive cases?
|
There's another PR with a simpler approach #106199. |
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Continued here: #106199 (comment) |


Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Optimize queries that use volume reducing functions like length and substr, closes #82378
Documentation entry for user-facing changes
Optimization Breakdown
The optimization conflicts with other optimizations of the 1st pass that do the opposite of function pushdown, so we run in the 2nd pass.
Helper functions
The results from the helper functions are passed to the
processNodeDFSfunction, which is the bulk of the optimization. Here's how it works generally in a step-by-step breakdown:Step 1 - Analysis
Step 2 - Request Creation
Step 3 - Pushdown
PR Todos:
Note
Medium Risk
Adds a new query plan optimization that rewrites
Expression/FilterDAGs and can insert newExpressionSteps (including aroundJOINs), which may affect correctness or performance in edge cases. Guarded by a new setting and includes functional/perf coverage, but touches core planner/optimizer behavior.Overview
Adds a new query-plan optimization, gated by
query_plan_push_down_volume_reducing_functions, that pushes “volume-reducing” functions (e.g.length,empty/notEmpty,substring-related search) closer to sources to reduce data movement before operations like sorting.Introduces
IFunction::isSuitableForPushDownBeforeFilter()and marks several string/array functions as pushdown-eligible; updatesliftUpFunctionsto avoid lifting these aboveSortingStepto prevent optimization ping-pong.Implements
tryPushDownVolumeReducingFunctions(including special handling forJoinStepLogicalvia a newaddPassThroughColumn) and adds stateless + performance tests validating identical results with the optimization on/off.Written by Cursor Bugbot for commit ff96f25. This will update automatically on new commits. Configure here.