Skip to content

Push down LIMIT in queries to external databases when suitable - #80070

Closed
the-devid wants to merge 18 commits into
ClickHouse:masterfrom
the-devid:push-limit-for-external-database
Closed

the-devid wants to merge 18 commits into
ClickHouse:masterfrom
the-devid:push-limit-for-external-database

Conversation

@the-devid

@the-devid the-devid commented May 11, 2025 •

Copy link
Copy Markdown

Add LIMIT clause in query for external database if it is correct for sure. Precisely, when all of the conditions are met:

  • There's no JOINs. Otherwisedata could be dropped on intersection, thus pre-limiting is unwanted
  • WHERE clause is fully compatible and added in rewritten query. Otherwise filtration after remote limiting would drop some data
  • When there's no other subexpression, which may break remote pre-limiting logic due to data reordering and filtration.

Changelog category (leave one):

  • Improvement

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

Add LIMIT clause in queries to external databases when possible.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@CLAassistant

CLAassistant commented May 11, 2025 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ alexey-milovidov
❌ the-devid
You have signed the CLA already but the status is still pending? Let us recheck it.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 13, 2025
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2025

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [959fb95]

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 13, 2025
@alexey-milovidov

Copy link
Copy Markdown
Member

Let's introduce a setting to turn the new logic on/off. This is required to avoid any compatibility issues.

@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2025

Copy link
Copy Markdown
Contributor

Dear @the-devid, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

5 similar comments
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2025

Copy link
Copy Markdown
Contributor

Dear @the-devid, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2025

Copy link
Copy Markdown
Contributor

Dear @the-devid, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh

clickhouse-gh Bot commented Jan 20, 2026

Copy link
Copy Markdown
Contributor

Dear @the-devid, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

Dear @the-devid, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

Dear @the-devid, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

alexey-milovidov and others added 2 commits July 3, 2026 04:18
…rnal-database

Resolved the 14-month-stale merge by taking current `master` for all files
and re-applying the PR's LIMIT push-down logic in
`transformQueryForExternalDatabase.cpp`, `transformQueryForExternalDatabaseAnalyzer.cpp`,
and its unit test, adapting to master's `make_intrusive` AST allocation.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the review request to make the new LIMIT push-down controllable to
avoid any compatibility issues. The setting is a `Bool` defaulting to `true`
(the optimization is active), and is registered in `SettingsChangesHistory.cpp`
so that `compatibility` with versions before 26.7 restores the previous behavior.

When disabled, both the analyzer path (`transformQueryForExternalDatabaseAnalyzer.cpp`)
and the legacy path (`transformQueryForExternalDatabase.cpp`) fall back to never
pushing the query's own `LIMIT` into the external query, matching the pre-existing
behavior. A unit test covers the disabled case.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e5babf]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Code Review ERROR
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

alexey-milovidov and others added 3 commits July 10, 2026 09:42
…nalDatabase`

On macOS, `size_t` (`unsigned long`) and `UInt64` (`unsigned long long`) are
distinct types, so `std::min(limit.value(), limit_len)` failed template
argument deduction:

    transformQueryForExternalDatabase.cpp:453:25: error: no matching function for call to 'min'

On Linux both resolve to `unsigned long`, which is why the Linux builds
passed while `Build (amd_darwin)` and `Build (arm_darwin)` failed. Specify the
explicit template argument `std::min<size_t>` (`limit` is `std::optional<size_t>`)
to fix the cross-platform build.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=80070&sha=ac55a614c622921efc721362e4bb6f1302f8084d&name_0=PR

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rnal-database

# Conflicts:
#	ci/docker/fasttest/Dockerfile
#	ci/jobs/scripts/workflow_hooks/filter_job.py
#	ci/praktika/job.py
#	ci/praktika/workflow.py
#	contrib/corrosion-cmake/CMakeLists.txt
#	docs/en/engines/table-engines/integrations/iceberg.md
#	src/Analyzer/Utils.cpp
#	src/Client/IServerConnection.h
#	src/Client/LocalConnection.cpp
#	src/Common/Scheduler/createResourceManager.cpp
#	src/Interpreters/ClusterProxy/executeQuery.cpp
#	src/Interpreters/InterpreterSystemQuery.cpp
#	src/Processors/Executors/StreamingFormatExecutor.cpp
#	src/Processors/QueryPlan/IQueryPlanStep.h
#	src/Processors/QueryPlan/QueryPlan.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
#	src/Storages/ObjectStorage/DataLakes/DeltaLake/getSchemaFromSnapshot.cpp
#	src/Storages/StorageDistributed.cpp
#	src/Storages/System/StorageSystemTables.cpp
#	src/Storages/tests/gtest_transform_query_for_external_database.cpp
#	tests/integration/test_scheduler/test.py
… with an explicit allow-list

The previous guard compared `ASTSelectQuery::children.size()` with the number of
fully copied expressions, but some semantics-changing modifiers are flags on
`ASTSelectQuery` rather than children (`DISTINCT`, `GROUP BY ALL`, `WITH TIES`, ...)
and others hide inside the TABLES child (`SAMPLE`, `FINAL`, `ARRAY JOIN`), so e.g.
`SELECT DISTINCT column FROM ext LIMIT 10` pushed `LIMIT 10` remotely and could
return wrong results.

Now `isLimitPushDownSafe` explicitly allows only a plain single-table `SELECT`
(optionally with a `WHERE` clause, which must additionally be copied to the
external query unchanged, and a `SETTINGS` clause) and checks the flags and the
table expression modifiers explicitly. Added focused regression tests for
`DISTINCT`, `ORDER BY`, `WITH TIES`, `GROUP BY`, `GROUP BY ALL`, a partially
copied `WHERE`, and a `SETTINGS` clause.
…t row-preserving

`isLimitPushDownSafe` inspected the top-level clauses and modifiers of the
query, but never the `SELECT` list itself. The `SELECT` list is evaluated
locally and the query's `LIMIT` applies to its result, not to the rows read
from the external table, so an expression that does not map one source row to
one result row makes the remote pre-limiting wrong.

For example, `SELECT sum(column) FROM mysql(...) LIMIT 1` has only the
`SELECT`, `TABLES` and `LIMIT` children and no flags set, so it passed the
allow-list; the external query became `SELECT column FROM remote LIMIT 1` and
`sum` was then computed over a single source row. Window functions (computed
over a whole partition of the source rows) and `arrayJoin` (it multiplies the
rows) have the same shape and the same problem.

Reject such queries: every expression of the `SELECT` list must be free of
aggregate functions, window functions and `arrayJoin`. Plain projections such
as `SELECT column + 1 FROM table LIMIT 10` are still pushed down.

Added regressions for `sum`, `sum(...) + 1`, `sum(...) OVER ()`, `arrayJoin`
and for the plain projection that must keep the push-down.
…rnal-database

# Conflicts:
#	.github/workflows/create_release.yml
#	ci/jobs/collect_statistics.py
#	ci/jobs/scripts/clickhouse_proc.py
#	ci/praktika/docker.py
#	docker/keeper/Dockerfile
#	docker/server/Dockerfile.alpine
#	docker/server/Dockerfile.ubuntu
#	src/Core/ServerSettings.cpp
#	src/Databases/DataLake/DatabaseDataLakeSettings.cpp
#	src/Planner/PlannerJoinsLogical.cpp
#	src/Storages/tests/gtest_transform_query_for_external_database.cpp
#	tests/ci/create_release.py
#	utils/list-versions/version_date.tsv
- Restore `UnionStep::hasCorrelatedExpressions` - it was added on master and got
  lost in an earlier merge of this branch, which does not touch `UnionStep`.
- Move the `external_storage_push_down_limit` entry in `SettingsChangesHistory`
  from 26.7 to 26.8, the current development version.
- Rework the partial-`WHERE` regression: master's analyzer now prunes a
  redundant range conjunct implied by an equality on the same column
  (`uuid_col = X AND uuid_col > Y` becomes just `uuid_col = X`), so that
  `WHERE` really is copied in full and pushing the `LIMIT` down is correct
  there. Use two conjuncts on different columns instead, where only one of
  them is compatible with the external database, so the rest is still applied
  locally and the `LIMIT` must not be pushed down.
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 162/165 (98.18%) · Uncovered code

Full report · Diff report

`isLimitPushDownSafe` only inspected the `ASTSelectQuery` that is rewritten for the
external database, but not every filter of the query lives in that AST. An
`additional_table_filters` entry is carried in `SelectQueryInfo::additional_filter_ast`
(and `filter_asts`), and with the analyzer a row policy is resolved by the planner; both
are applied locally, on top of the rows read from the external table, and therefore before
the query's `LIMIT`. Pushing the `LIMIT` down truncated the remote result before such a
filter ran, so a query like

    SELECT column FROM mysql(...) LIMIT 10 SETTINGS additional_table_filters = {'table': 'column > 100'}

could return fewer rows than it should when the first 10 remote rows do not satisfy the
local filter. This mirrors the invariant the existing PostgreSQL step-level `limit`
push-down already encodes by only forwarding the limit when there is no `filter_actions_dag`.

`transformQueryForExternalDatabase` now rejects the push-down when `additional_filter_ast`,
`filter_asts`, `row_level_filter` or `prewhere_info` is set, or when an effective row policy
applies to the table expression. Added regressions for both analyzers.
`isRowPreservingExpression` rejected only the literal name `arrayJoin`,
but `unnest` is a case-insensitive alias of the same row-multiplying
function. `TreeRewriter` normalizes function names to their canonical
ones before `transformQueryForExternalDatabase` runs, so on the usual
path the alias was already rewritten - but not when
`normalize_function_names` is disabled, and not for a secondary query
of a distributed query. In those cases
`SELECT unnest(range(column)) FROM mysql(...) LIMIT 10` was treated as
row preserving, `LIMIT 10` was pushed into the remote query, and the
local `unnest` then expanded only the first 10 source rows.

The name is now canonicalized with `getFunctionCanonicalNameIfAny`
before the comparison. Added gtest regressions for the `unnest` and
`UNNEST` spellings, including with `normalize_function_names = 0`
(they fail without this change), and mentioned the alias in the
description of `external_storage_push_down_limit`.
…rnal-database

# Conflicts:
#	src/Storages/tests/gtest_transform_query_for_external_database.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #115238. I re-authored the current feature because the original PR contains a commit by an unsigned contributor; its resolved review feedback and safety fixes are included. Thank you, @the-devid.

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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants