Skip to content

In case of trivial views, push whole outer query to shards. - #101791

Merged
alexey-milovidov merged 60 commits into
ClickHouse:masterfrom
simonmichal:issue-51645
Aug 14, 2026
Merged

alexey-milovidov merged 60 commits into
ClickHouse:masterfrom
simonmichal:issue-51645

Conversation

@simonmichal

@simonmichal simonmichal commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category:

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

For views whose body is a plain SELECT over a single Distributed table, the whole outer query is now pushed to the shards (new setting optimize_trivial_view_pushdown_to_distributed, enabled by default). This changes observable behaviour for such views: FINAL and SAMPLE written on the view reference are now propagated to the shard-local table instead of being ignored, and extremes is not reported on single-shard clusters. Set optimize_trivial_view_pushdown_to_distributed = 0 to restore the previous behaviour.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Description / Proposed Solution

When a VIEW is defined over a Distributed table, ClickHouse traditionally executes it on the shards without enclosing outer query. This means filters and expressions declared in the outer query are evaluated on the coordinator after pulling raw data from shards.

For views whose body is a plain SELECT (column references, *, or arbitrary expressions — but no aggregation, grouping, ordering, joins, window functions, or scalar subqueries) over a single Distributed table, we can do better: inline the view body as a subquery and hand the whole thing to StorageDistributed. Each shard then receives the full outer query with the view body inlined, evaluates it against its local table, and only ships the result back.

A view qualifies as "trivial" if its inner query:

  • Has a single SELECT (no UNION)
  • Selects only column references, *, or expressions — but no window functions (require the full dataset) and no scalar subqueries in the SELECT list
  • Has no WITH, PREWHERE, GROUP BY, HAVING, QUALIFY, ORDER BY, LIMIT, LIMIT BY, DISTINCT, or ARRAY JOIN
  • Has no subqueries in the WHERE clause
  • Reads from exactly one table with no joins, no table functions, no FINAL, no SAMPLE
  • Is not a parameterized view and does not use SQL SECURITY DEFINER

The optimization can be disbaled by setting (enabled by default):

SET optimize_trivial_view_pushdown_to_distributed = 0;

Example:

Env setup:

create table x engine = MergeTree ORDER BY tuple() AS SELECT intDiv(number,100000) as a, number as b FROM numbers(1000000000);
SET prefer_localhost_replica = 0;
CREATE TABLE x_dist AS x ENGINE = Distributed(test_cluster_two_shards_localhost, currentDatabase(), x);
CREATE VIEW v_computed AS SELECT a + 1 AS x, b AS y FROM x_dist WHERE a != 0;

Performance:

:) SELECT a + 1, sum(b) FROM x_dist WHERE a != 0 GROUP BY a + 1 ORDER BY sum(b) DESC LIMIT 1;

SELECT
    a + 1,
    sum(b)
FROM x_dist
WHERE a != 0
GROUP BY a + 1
ORDER BY sum(b) DESC
LIMIT 1

Query id: 6baedc55-c8e7-4b2b-9946-b0d828abaf25

   ┌─plus(a, 1)─┬──────────sum(b)─┐
1. │      10000 │ 199989999900000 │ -- 199.99 trillion
   └────────────┴─────────────────┘

1 row in set. Elapsed: 17.199 sec. Processed 2.00 billion rows, 32.00 GB (116.29 million rows/s., 1.86 GB/s.)
Peak memory usage: 38.58 MiB.

:) SELECT x, sum(y) FROM v_computed GROUP BY x ORDER BY sum(y) DESC LIMIT 1;

SELECT
    x,
    sum(y)
FROM v_computed
GROUP BY x
ORDER BY sum(y) DESC
LIMIT 1

Query id: 7c4f2854-3de2-4d40-b960-efcc44a7b26d

   ┌─────x─┬──────────sum(y)─┐
1. │ 10000 │ 199989999900000 │ -- 199.99 trillion
   └───────┴─────────────────┘

1 row in set. Elapsed: 16.497 sec. Processed 2.00 billion rows, 32.00 GB (121.24 million rows/s., 1.94 GB/s.)
Peak memory usage: 38.82 MiB.

Plan:

:) explain SELECT a + 1, sum(b) FROM x_dist WHERE a != 0 GROUP BY a + 1 ORDER BY sum(b) DESC LIMIT 1;

EXPLAIN
SELECT
    a + 1,
    sum(b)
FROM x_dist
WHERE a != 0
GROUP BY a + 1
ORDER BY sum(b) DESC
LIMIT 1

Query id: e2d32d5f-7024-4e6a-b686-45c7c0d5f2ef

    ┌─explain──────────────────────────────────────────────────────────────────────────┐
 1. │ Expression (Project names)                                                       │
 2. │   Limit (preliminary LIMIT)                                                      │
 3. │     Sorting (Sorting for ORDER BY)                                               │
 4. │       Expression ((Before ORDER BY + Projection))                                │
 5. │         MergingAggregated                                                        │
 6. │           Union                                                                  │
 7. │             Aggregating                                                          │
 8. │               Expression (Before GROUP BY)                                       │
 9. │                 Expression ((WHERE + Change column names to column identifiers)) │
10. │                   ReadFromMergeTree (default.x)                                  │
11. │             Aggregating                                                          │
12. │               Expression (Before GROUP BY)                                       │
13. │                 Expression ((WHERE + Change column names to column identifiers)) │
14. │                   ReadFromMergeTree (default.x)                                  │
    └──────────────────────────────────────────────────────────────────────────────────┘

:) explain SELECT x, sum(y) FROM v_computed GROUP BY x ORDER BY sum(y) DESC LIMIT 1;

EXPLAIN
SELECT
    x,
    sum(y)
FROM v_computed
GROUP BY x
ORDER BY sum(y) DESC
LIMIT 1

Query id: 88213305-46a5-493e-862c-a80c675c9452

    ┌─explain───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
 1. │ Expression (Project names)                                                                                                │
 2. │   Limit (preliminary LIMIT)                                                                                               │
 3. │     Sorting (Sorting for ORDER BY)                                                                                        │
 4. │       Expression ((Before ORDER BY + Projection))                                                                         │
 5. │         MergingAggregated                                                                                                 │
 6. │           Union                                                                                                           │
 7. │             Aggregating                                                                                                   │
 8. │               Expression ((Before GROUP BY + (Change column names to column identifiers + (Project names + Projection)))) │
 9. │                 Expression ((WHERE + Change column names to column identifiers))                                          │
10. │                   ReadFromMergeTree (default.x)                                                                           │
11. │             Aggregating                                                                                                   │
12. │               Expression ((Before GROUP BY + (Change column names to column identifiers + (Project names + Projection)))) │
13. │                 Expression ((WHERE + Change column names to column identifiers))                                          │
14. │                   ReadFromMergeTree (default.x)                                                                           │
    └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Note

Medium Risk
Changes query planning/execution for a subset of views over Distributed tables and touches access checks/row policy enforcement and SQL SECURITY semantics, which can affect correctness and security-sensitive behavior.

Overview
Adds a new default-on setting optimize_trivial_view_pushdown_to_distributed to inline trivial views over Distributed tables and push the full outer query down to shards, reducing coordinator-side filtering/processing and network transfer.

Implements planner rewrites to swap the view table expression with an analyzed subquery, merge FINAL/SAMPLE modifiers, and preserve semantics by suppressing pushdown when the outer query contains non-deterministic functions, while also explicitly handling SQL SECURITY modes, row-policy injection/logging, and column-pruned privilege checks.

Extends integration/stateless tests to cover modifier propagation, non-determinism suppression, row-policy enforcement, SQL SECURITY behavior, and interactions with max_rows_to_read_leaf.

Reviewed by Cursor Bugbot for commit 583e1e6. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.8.1.1380 (included in 26.8 and later)

@simonmichal

Copy link
Copy Markdown
Contributor Author

Hi team,
this is my take on #51645 , please let me know your thoughts!

If there are some better ideas on how to approach the problem I am happy to rework the PR.

@clickhouse-gh

clickhouse-gh Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9a26fca]

Summary: ✅


AI Review

Summary

This PR adds optimize_trivial_view_pushdown_to_distributed, rewrites eligible VIEW reads over Distributed tables to inline the view body into the shipped shard query, and adds broad regression coverage around SQL security, row policies, additional filters, virtual columns, serialize_query_plan, and limit-related edge cases. I reviewed the current PR head, the final diff, and the full prior thread history, and I did not find any remaining correctness, safety, or compatibility issues that still warrant an inline review comment.

Final Verdict

✅ No new actionable findings on the current PR head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 299/317 (94.32%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 5, 2026
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@simonmichal
simonmichal force-pushed the issue-51645 branch 4 times, most recently from b7949ee to f04444a Compare April 14, 2026 09:55
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@simonmichal
simonmichal force-pushed the issue-51645 branch 2 times, most recently from 7c40bc1 to 1ba5413 Compare April 14, 2026 18:28
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@simonmichal
simonmichal force-pushed the issue-51645 branch 3 times, most recently from 3a85fdd to f0ad9ed Compare April 15, 2026 16:20
Comment thread src/Storages/StorageView.cpp Resolved
@simonmichal

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov : all comments from AI Review are resolved, the failure in PR / Unit tests (msan) (pull_request) afaiu is unrelated to the PR

…ables

Master (c260811, hardened by 43718e2) now rejects a row policy
defined directly on a Distributed table with ILLEGAL_PREWHERE instead of
silently returning unfiltered rows: a Distributed table only ships the query
text to the remote servers, so the filter can never actually be applied
there. This is intentional, documented behavior, unrelated to the trivial-
view pushdown, and reproduces identically with no view involved at all
(confirmed with a plain `SELECT ... FROM dist` against a Distributed table
carrying such a policy).

04098's dist-level-policy scenario predates this change and asserted the
old behavior (pushdown suppressed, query still returns correct filtered
results via the standard path). Update it to assert the new expected error
instead.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
simonmichal and others added 2 commits August 5, 2026 14:24
…group_by

StorageView::readImpl fetches the view's raw rows and performs the outer
GROUP BY entirely on the initiator, so max_rows_to_group_by is enforced
once against the global key set. The pushdown ships the whole GROUP BY to
each shard instead, so each shard's Aggregator enforces the limit
independently against only its own local rows; for
group_by_overflow_mode = 'any'/'break' the merge phase does not re-apply
the cap globally (Aggregator::ensureLimitsFixedMapMerge), so shards could
each keep a different, locally-permitted set of keys and the initiator
would return more groups in total than the limit allows.

Confirmed empirically via system.query_log: with the pushdown off, the
query shipped to each shard has no GROUP BY at all (raw SELECT); with it
on, the full GROUP BY/aggregation is shipped and each shard aggregates
independently.

Suppress the pushdown whenever the outer query has a GROUP BY and
max_rows_to_group_by is non-zero, matching the precedent set by
AggregatingStep::canUseShardedAggregation and
useDataParallelAggregation, which disable independent aggregation for
the same reason.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@simonmichal

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov all builds green, no new concerns from AI reviewer (at least at the moment)

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9a26fca6d with master 97665d017 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 691.73 MiB 688.74 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

6 object files changed (+79.95 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/PlannerJoinTree.cpp.o 742.59 KiB 808.57 KiB +65.98 KiB (+8.89%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

27 translation units recompiled, 272 s compile time in total, 27 of them have a recent master baseline.

Job report

simonmichal and others added 3 commits August 12, 2026 17:57
tryGetTrivialViewUnderlyingStorage rejects a view whose own body's WHERE
contains a subquery, so such a view is never eligible for the trivial
pushdown regardless of the setting. Every existing
*trivial_view_pushdown* test places its subquery in the outer query, a
view-keyed additional_table_filter, or a row policy -- none defines the
view body itself with a subquery, so a regression in that guard would go
unnoticed. Confirmed empirically that the guard already suppresses the
pushdown correctly; no source change needed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…projection

tryGetTrivialViewUnderlyingStorage rejects a view whose own projection
contains an aggregate, a window function, or a scalar subquery, so such
a view is never eligible for the trivial pushdown. 04695 and 04372
cover an aggregating outer query, but no existing test defines a
non-trivial view body like this, so a regression in that guard would go
unnoticed and let each shard emit partial aggregate/window/subquery
results instead of a single value computed once on the initiator.
Confirmed empirically that the guard already suppresses the pushdown
correctly; no source change needed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@simonmichal

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov: green again :-) and no concerns from the AI reviewer :-)

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026

@alexey-milovidov alexey-milovidov 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.

Thanks! The implementation is complex as it checks a lot of corner cases. But it is well contained in just two files, so good to have.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit c3b0aa7 Aug 14, 2026
181 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@simonmichal @alexey-milovidov — this PR looks backward incompatible but is categorized as Performance Improvement.

Why: The setting defaults to true (src/Core/Settings.cpp, and {"optimize_trivial_view_pushdown_to_distributed", false, true, ...} in SettingsChangesHistory.cpp:89) and changes query results, not just speed: SELECT ... FROM view FINAL over a ReplacingMergeTree returns a different row set (verified: 3 rows -> 2 rows), SELECT count() FROM view FINAL over a plain MergeTree changes from returning a count to throwing ILLEGAL_FINAL, and SETTINGS extremes = 1 stops emitting the extremes block on a single-shard cluster. A Performance Improvement must not change results.

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

@clickgapai

Copy link
Copy Markdown
Contributor

@simonmichal @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@hshen3197

Copy link
Copy Markdown

I checked out the master branch on Aug 14, 2026 with this commit. ran the example. the issue still there. Please take a look at the attachments.
PrimaryExplainDistribute
PrimaryExplainView
PrimaryQuery
SecondaryQuery

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-performance Pull request with some performance improvements 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.

6 participants