Skip to content

Push down LIMIT in external database queries - #115238

Merged
alexey-milovidov merged 44 commits into
masterfrom
continue-pr-80070-limit-pushdown-external
Oct 10, 2026
Merged

alexey-milovidov merged 44 commits into
masterfrom
continue-pr-80070-limit-pushdown-external

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Re-authors the feature from @the-devid because the original PR includes an unsigned contributor. Adds an opt-out setting and conservatively pushes a query LIMIT into external-database queries only when all preceding semantics are preserved remotely.

While making the rewriter refuse to push down a LIMIT whose limit + offset overflows UInt64, two pre-existing ways of computing that sum turned the overflow into a limit of zero rows, so this also fixes them:

  • NumbersLikeUtils::getLimitFromQueryInfo added the two values in plain UInt64 arithmetic and wrapped around, so SELECT * FROM numbers(10) LIMIT 18446744073709551615 OFFSET 1 returned nothing instead of nine rows. system.numbers, generate_series and system.primes were affected the same way.
  • LimitStep::getLimitForSorting returns 0 as its "unknown" sentinel, and optimizePrimaryKeyConditionAndLimit passed it to SourceStepWithFilterBase::setLimit, where it means an exact upper bound on the rows a source may produce. ReadFromPostgreSQL then sent a real remote LIMIT 0, turning "all rows except the first" into "no rows".

The same helper also handed the outer LIMIT to numbers-like sources of a joined query, where it counts joined rows: SELECT n.number FROM numbers(100) AS n INNER JOIN (SELECT 50 AS x) AS t ON n.number = t.x LIMIT 1 returned nothing instead of 50. The hint is now refused when the query has a join.

Related: #80070

Changelog category (leave one):

  • New Feature

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

Add the external_storage_push_down_limit setting to reduce data read from external databases for safe LIMIT queries. Also fix LIMIT with a huge value combined with OFFSET returning an empty result from numbers, system.numbers, generate_series, system.primes and the PostgreSQL table engine, and a LIMIT over a join with numbers-like sources returning too few rows.


Workflow [PR]
Sync PR [sync-upstream/pr/115238]

Version info

  • Merged into: 26.10.1.2083-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7cf613b]

Summary: ✅


AI Review

Summary

This PR adds safe LIMIT pushdown for external-database table reads and fixes several existing LIMIT/OFFSET corner cases for numbers-like sources. The external-storage path looks solid now, but one wrong-result path remains in the numbers/primes limit-hint logic when plan optimizations are disabled, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/numbersLikeUtils.cpp:145] [dismissed by author -- https://github.com/Push down LIMIT in external database queries #115238#discussion_r4181340105] getLimitFromQueryInfo still caches an AST-derived row budget before the source-side filter is known to be fused. That assumption does not only depend on the obsolete query_plan_optimize_primary_key setting from the thread: optimizePrimaryKeyConditionAndLimit is skipped entirely when query_plan_enable_optimizations = 0 (src/Processors/QueryPlan/Optimizations/optimizeTree.cpp:118), so ReadFromSystemNumbersStep / ReadFromSystemPrimesStep keep filter_actions_dag == nullptr while still consuming the cached limit (src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp:431, src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp:518, src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp:561, src/Processors/QueryPlan/ReadFromSystemPrimesStep.cpp:144). A filtered query such as SELECT count() FROM (SELECT * FROM numbers(100) WHERE number > 50 LIMIT 1 SETTINGS query_plan_enable_optimizations = 0) can therefore truncate the generator before the filter and return 0 instead of 1. The author reply only rules out the obsolete knob; it does not make the still-user-visible query_plan_enable_optimizations = 0 path safe.
    Suggested fix: only honor this limit hint after applyFilters has materialized a source filter, or suppress the hint whenever that optimization pass is disabled; add a focused regression for numbers, generate_series, and system.primes / primes with query_plan_enable_optimizations = 0.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Make numbers-like limit pushdown independent of the optimizer-pass ordering, or explicitly disable it when the filter-fusion pass does not run.
    • Add a focused regression proving filtered LIMIT queries stay correct with query_plan_enable_optimizations = 0.

LLVM Coverage Report

⚠️ No coverage measurement for commit 7cf613b: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 18, 2026
Comment thread src/Core/Settings.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7cf613b82 with master ef037e60f (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

14 object files changed (+26.48 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/transformQueryForExternalDatabase.cpp.o 227.06 KiB 246.12 KiB +19.06 KiB (+8.40%)

719 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

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

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +5.3 s (+7%) in total before that adjustment.

Job report

Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
…down_limit`

`StorageXDBC::getReadPOSTDataCallback` passes `allow_limit_push_down = false`,
so the setting description must not promise the push-down for the generic
ODBC/JDBC bridges.
… drop a resurrected entry

The merge with `master` bumped the development version to 26.9, so the
compatibility entry for `external_storage_push_down_limit` belongs to the
topmost `26.9` block; `compatibility` below 26.9 now restores the previous
behavior.

Also drop the `query_plan_read_in_order_through_spilling_join` entry, which a
criss-cross merge resurrected on this branch after it had been reverted on
`master` together with the setting itself - the setting no longer exists, so
the entry dangles.
Resolve the stale merge conflict that prevented GitHub from computing the
merge ref, which in turn kept the `PR` workflow (and `CH Inc sync`) from
starting at all.
The AI review pointed out that the new contract disallowed `OFFSET`, while
`ReadFromPostgreSQL` still forwards the plan-level limit produced by
`LimitStep::getLimitForSorting` (which is `offset + length`), so a query like
`SELECT ... FROM postgresql(...) LIMIT 10 OFFSET 5` was sent as `LIMIT 15`
anyway. Instead of restricting that path, make the AST rewriter follow the same
rule: an `OFFSET` is applied locally, so the rows it skips have to be read from
the external table as well, and the limit pushed down is `offset + length`.

The push-down is skipped when the `OFFSET` is not a `UInt64` literal or when
`offset + length` overflows. The setting description and the tests are updated
accordingly.
The new recursive walk over the projection AST descends through
user-controlled depth, so without the guard a deeply nested `SELECT`
expression could exhaust the stack during analysis instead of failing
with `TOO_DEEP_RECURSION`, like the other recursive helpers in this file
already do.
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 27, 2026
… EXPLAIN or a subquery

A correlated subquery is planned with its own `GlobalPlannerContext`, and
`collectTableExpressionDataForCorrelatedColumns` stores raw pointers to the
enclosing query's `TableExpressionData` in it, without keeping the enclosing
`PlannerContext` alive. Every context derived from the subquery falls back to
that map when it looks up the correlated column's source.

`ReadFromMerge` plans its source tables lazily (from `applyFilters` during
`QueryPlan::optimize`, or from `initializePipeline`). For a non-empty source
table narrower than the `Merge` header, `convertAndFilterSourceStream` builds
the fan-out added in ClickHouse#119561 and names the correlated column through that map.
`EXPLAIN`, a subquery in `FROM`, a view and an `IN` subquery destroy the
enclosing `Planner` before that point, so the lookup reads freed memory
(AST fuzzer, arm_asan_ubsan, STID 4877-28b1).

`GlobalPlannerContext` now holds a `PlannerContextPtr` to every planner context
whose data it points into. It is the only writer of the map, so this covers all
readers and every place that drops the enclosing planner early, without
changing each of them. No reference cycle: the subquery's plan is united into
the enclosing `QueryPlan`, never stored in the enclosing `PlannerContext`
(correlated subqueries are neither `IN` set sources nor materialized CTEs).

Related: ClickHouse#115238 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 27, 2026
A view is planned by its own interpreter in `StorageView::readImpl`, which
destroys the enclosing `Planner` before `ReadFromMerge` plans its source
tables, like `EXPLAIN` and the `FROM` and `IN` subqueries the test already
covers.

CI report of the heap-use-after-free fixed in the previous commit:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115238&sha=28023e4bdf69d407d579274765a2573ac6baa9db&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
https://github.com/ClickHouse/ClickHouse/actions/runs/35807917921/job/107176161332

Related: ClickHouse#115238 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 5 commits September 28, 2026 01:29
… query

`NumbersLikeUtils::getLimitFromQueryInfo` gave `ReadFromSystemNumbersStep` and
`ReadFromSystemPrimesStep` the outer `LIMIT` as a row budget even when the query had a `JOIN`.
That `LIMIT` counts joined rows, so a join that drops the first rows of the source lost the rows
matching later: `SELECT n.number FROM numbers(100) AS n INNER JOIN (SELECT 50 AS x) AS t
ON n.number = t.x LIMIT 1` returned nothing instead of `50`, on either side of the join, with
comma joins, and for `system.numbers`, `generate_series` and `system.primes` alike, with both
analyzers. Reject the hint when the query has a join.

Addresses the AI review blocker on #115238

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
An infinite `system.numbers` or `system.primes` on the probe side of a join does not stop at
`LIMIT` even without the pushed-down hint, so bound them with a `WHERE` range, which still lets the
hint through, and also cover the `primes` table function.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The old query analysis is no longer supported since v26.9, and `enable_analyzer = 0` is rejected.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…imit-pushdown-external

Resolve conflicts with the `transformQueryForExternalDatabase` rework on master
(`source_storage_id`, `unsupported_functions`, `local_only_columns`,
`require_dialect_neutral_literals`, `PREWHERE` merged into the remote filter):
`allow_limit_push_down` is appended as the last parameter, and the `WHERE`
dump comparison now covers the combined `WHERE`/`PREWHERE` filter.
`00956_join_use_nulls_with_array_column` and `03360_any_join_parallel_hash_bug`
read the unbounded `system.numbers` as a side of a join and terminated only
because the outer `LIMIT` was pushed into the source as a row budget. This PR
stops doing that for joined queries (the `LIMIT` counts joined rows, so the hint
is incorrect there), so both tests now hit `max_rows_to_read` (`TOO_MANY_ROWS`).
Bound the sources explicitly; what the tests check is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115238&sha=ac3a029d0e369386d35d090fe19291afdaf08e93&name_0=PR&name_1=Fast%20test
PR: #115238

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (resolved conflicts with the transformQueryForExternalDatabase rework: allow_limit_push_down is now the last parameter, and the unchanged-filter check covers the combined WHERE/PREWHERE). Fast test failed in 00956_join_use_nulls_with_array_column and 03360_any_join_parallel_hash_bug with TOO_MANY_ROWS: both joined the unbounded system.numbers and only finished because of the outer-LIMIT hint that this PR now refuses for joined queries. Bounded their sources explicitly in 8182000; what they test is unchanged.

alexey-milovidov and others added 2 commits October 5, 2026 05:58
…_join`

The outer `LIMIT` counts joined rows, so it is no longer pushed into a
`numbers`-like source of a join. With a randomized join order
(`query_plan_optimize_join_order_randomize`) the unbounded left side
becomes the build side and the query reads until `max_rows_to_read`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115238&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel)
#115238

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imit-pushdown-external

Conflict in `transformQueryForExternalDatabaseAnalyzer.cpp`: master added
`removeConjunctsHoldingEnumConstants`, which keeps some `WHERE` conjuncts local.
It now reports whether it removed anything, and the `LIMIT` is not pushed down
in that case, because the external database returns rows the local filter drops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed two commits:

  • Bounded the left system.numbers side of the join in 00049_any_left_join. The outer LIMIT is no longer pushed into a numbers-like source of a join, so with query_plan_optimize_join_order_randomize the unbounded side became the build side and hit max_rows_to_read.
  • Merged master. It conflicted with the new removeConjunctsHoldingEnumConstants in transformQueryForExternalDatabaseAnalyzer.cpp. That function now reports whether it dropped a conjunct, and the LIMIT is not pushed down when it does, because the external result is then filtered further on the local side.

The other failures (05237_with_expression_alias_scope_descendant, 05213_timeseries_metric_families_target, 05257_sql_security_view_sealed, Build (amd_fuzzers)) hit hundreds of PRs on 2026-10-03 and 2026-10-04 and have already been fixed on master.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reviewed, all good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 10, 2026
@@ -1,10 +1,18 @@
#include <base/arithmeticOverflow.h>
#include <Common/checkStackSize.h>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

As long as we have transformQueryForExternalDatabaseAnalyzer, why do we need this file?

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 10, 2026
Merged via the queue into master with commit 8575850 Oct 10, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the continue-pr-80070-limit-pushdown-external branch October 10, 2026 23:18
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

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

Close anything that's wrong or already addressed.

yariks5s pushed a commit to bbrown-oai/ClickHouse that referenced this pull request Nov 19, 2026
…RRAY JOINs

`isLimitPushDownSafe` runs for every MySQL, PostgreSQL and SQLite read,
because `external_storage_push_down_limit` is on by default. It rejected
ARRAY JOIN through `ASTSelectQuery::arrayJoinExpressionList()`, whose
`getFirstArrayJoin()` throws NOT_IMPLEMENTED on a second ARRAY JOIN
instead of returning, so any query with two ARRAY JOINs over such a table
failed with "Support for more than one ARRAY JOIN in query is not
implemented" (since ClickHouse#115238, in 26.10).

Replace the `hasJoin()` and ARRAY JOIN conditions with a check that the
TABLES list has more than one element. The list is flat: the table
expression first, then one element per JOIN and one per ARRAY JOIN (both
for the AST built from the query tree and for the parser's), so the
condition is the same as before without the throw. It is also the check
`tryGetTrivialViewUnderlyingStorage` uses. Deleting the ARRAY JOIN
condition instead would push the LIMIT below the ARRAY JOIN: nothing else
on this path stops it.

The new test uses SQLite rows whose first two produce no output through
`ARRAY JOIN range(id)`, so a LIMIT pushed below an ARRAY JOIN would
return fewer rows than the LIMIT, and it checks the query sent to SQLite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). pr-feature Pull request with new product feature 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.

4 participants