Skip to content

Add function pushdown query plan optimization - #86139

Closed
talmawash wants to merge 32 commits into
ClickHouse:masterfrom
talmawash:add_function_pushdown
Closed

talmawash wants to merge 32 commits into
ClickHouse:masterfrom
talmawash:add_function_pushdown

Conversation

@talmawash

@talmawash talmawash commented Aug 25, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

  • Documentation is written (mandatory for new features)

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

  1. Build a map for child -> parent relations for the plan
  2. Find source/reading node

The results from the helper functions are passed to the processNodeDFS function, which is the bulk of the optimization. Here's how it works generally in a step-by-step breakdown:

Step 1 - Analysis

  • Analyze the inputs and outputs of each node
    • For columns/functions seen for the first time, we just create a new record
    • For existing columns, we update the input and output names for the particular node, and if the column is used in a way that affects push down (e.g., unsupported function, sorting, joins), we set the max pushdown point to the current node

Step 2 - Request Creation

  • Create pushdown requests for each column, grouping functions by column
    • Only suitable functions with a single input column (constants are fine) are added

Step 3 - Pushdown

  • If the current node is the max pushdown node, push down to it
    • Find the first expression/filter (inclusive) step node at or above to call the function
    • Remove the input column from outputs
    • Update input headers of the parent nodes

PR Todos:

  • Look into refactoring or applying a simpler approach (review feedback affects this)
  • Explain the approach
  • Validate any assumptions
  • Ensure order is consistent and queries don't break when using the optimization
  • Support more functions
  • Add functional and performance tests

Note

Medium Risk
Adds a new query plan optimization that rewrites Expression/Filter DAGs and can insert new ExpressionSteps (including around JOINs), 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; updates liftUpFunctions to avoid lifting these above SortingStep to prevent optimization ping-pong.

Implements tryPushDownVolumeReducingFunctions (including special handling for JoinStepLogical via a new addPassThroughColumn) 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.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Aug 26, 2025
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9f2caf]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
03199_merge_filters_bug FAIL cidb
02993_lazy_index_loading FAIL cidb
04061_storage_generate_args_order FAIL cidb
03127_system_unload_primary_key_table FAIL cidb
03447_analyzer_correlated_subqueries_tpc_h FAIL cidb
04095_lazy_final_with_lazy_materialization FAIL cidb
03711_read_in_order_through_join FAIL cidb
02995_new_settings_history FAIL cidb
03602_volume_reducing_function_push_down FAIL cidb
01095_tpch_like_smoke FAIL cidb
Docs check DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

This PR adds a new query-plan optimization that pushes isVolumeReducing scalar functions (for example length, empty, substring family) closer to data sources, including join-aware rewrites and a new setting gate. The direction is useful, but there are still unresolved correctness risks in the current implementation, so this should not merge yet.

Missing context / blind spots
  • ⚠️ I could not validate CI performance deltas with .claude/tools/fetch_perf_report.py in this environment because clickhouse is not available in PATH; a before/after measurement from CI performance runs is still needed for a Performance Improvement PR.
Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/pushDownVolumeReducingFunctions.cpp:108] Shared VR-node classification is still unsound: the processed set is keyed only by node pointer, so a isVolumeReducing node shared between an output path and a non-VR parent path can be processed only once as VR. The later NON_VR path is dropped, and the source column can be pushed down even though non-VR expressions still depend on it transitively. This can produce missing-column exceptions or wrong rewrites.
    Suggested fix: include incoming path kind in traversal state (or merge states per node with NON_VR dominance), and make safety validation check transitive dependencies, not only direct INPUT children of non-candidate functions.
  • [src/Processors/QueryPlan/Optimizations/pushDownVolumeReducingFunctions.cpp:230] DistinctStep handling treats empty getColumnNames() as “no key uses this column”, but empty means DISTINCT keys are all input columns. Allowing pushdown here can replace DISTINCT keying from source to f(source), changing dedup semantics.
    Suggested fix: in the DistinctStep branch, treat columns.empty() as used (or conservatively bail out on DISTINCT with empty key list).
Tests
  • ⚠️ tests/queries/0_stateless/03602_volume_reducing_function_push_down.sql:49 (and similar checks in this file) use one-way EXCEPT comparisons. This misses regressions where the optimized plan returns extra rows or different multiplicities because EXCEPT is distinct and non-symmetric. Add symmetric equivalence checks (both directions or a multiplicity-preserving comparison) at least for JOIN/UNION/DISTINCT-sensitive cases.
  • ⚠️ For the declared Performance Improvement, include before/after numbers (CI perf shards or focused benchmark output) proving the gain and confirming no regressions.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Fix the shared-node VR classification issue and add a focused regression test that exercises a shared isVolumeReducing sub-expression used by both VR and non-VR paths.
  2. Fix the DISTINCT empty-key handling guard in isColumnUsedByStep.
  3. Strengthen equivalence tests to catch extra rows/multiplicity differences, and provide performance evidence for the changelog claim.

@talmawash
talmawash force-pushed the add_function_pushdown branch from 3ed749e to 3a32017 Compare August 26, 2025 09:44
@talmawash

Copy link
Copy Markdown
Contributor Author

rebased

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 26, 2025
@novikd novikd self-assigned this Aug 29, 2025
@talmawash
talmawash force-pushed the add_function_pushdown branch from 687f430 to 339f7ac Compare September 6, 2025 23:09
@talmawash

Copy link
Copy Markdown
Contributor Author

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.

@talmawash
talmawash force-pushed the add_function_pushdown branch from 1f4f187 to a27a571 Compare September 13, 2025 23:07
@talmawash
talmawash force-pushed the add_function_pushdown branch from 5e77ae3 to da6d876 Compare September 21, 2025 14:24
@talmawash
talmawash force-pushed the add_function_pushdown branch from da6d876 to df1ab4a Compare September 21, 2025 16:12

@novikd novikd 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.

The implementation is currently overcomplicated. It would be much simpler and less code if only 2 query plan steps were analyzed at a time.

Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{"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"},

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.

Suggested change
{"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)

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.

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;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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;

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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
image

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

This is also not needed.


void pushDownVolumeReducingFunctions(QueryPlan::Node * root_node, const QueryPlanOptimizationSettings & optimization_settings)
{
if (!optimization_settings.push_down_volume_reducing_functions)

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.

We usually check settings outside of optimization function

Comment on lines +776 to +777
NodeToParentsMap direct_parent_nodes_map = buildDirectParentNodesMap(root_node);
processNodeDFS(node, {}, direct_parent_nodes_map);

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.

You won't need it if you push expression only through one expression at a time

Comment thread src/Functions/IFunction.h Outdated
/** 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; }

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 rename to something like isVolumeReducing, because this optimization is unrelated to filters.

@talmawash

Copy link
Copy Markdown
Contributor Author

Thanks for the review @novikd

The implementation is currently overcomplicated. It would be much simpler and less code if only 2 query plan steps were analyzed at a time.

I think we could limit the scope of the optimization and accept that some cases may not be covered

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Feb 27, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 4 potential issues.

Fix All in Cursor

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)
Fix in Cursor Fix in Web

Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{"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"},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Fix in Cursor Fix in Web

Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{"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."},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Fix in Cursor Fix in Web


default:
break;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Fix in Cursor Fix in Web

# 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))

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.

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

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.

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?

@novikd

novikd commented Jul 9, 2026

Copy link
Copy Markdown
Member

There's another PR with a simpler approach #106199.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

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.

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Aug 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Continued here: #106199 (comment)

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 hold Skip for auto-updating. manual approve Manual approve required to run CI pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Certain functions can be pushed up in the query pipeline into WHERE if they reduce data size

4 participants