Repository navigation
Push down LIMIT in external database queries - #115238
Conversation
|
Workflow [PR], commit [7cf613b] Summary: ✅
AI ReviewSummaryThis PR adds safe Findings❌ Blockers
Final Verdict
LLVM Coverage Report |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes14 object files changed (+26.48 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units18 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. |
…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.
…imit-pushdown-external
… 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.
…imit-pushdown-external
… 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]>
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]>
… 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]>
|
🕵 Merged |
…_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]>
|
🕵 Pushed two commits:
The other failures ( |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Reviewed, all good.
| @@ -1,10 +1,18 @@ | |||
| #include <base/arithmeticOverflow.h> | |||
| #include <Common/checkStackSize.h> | |||
There was a problem hiding this comment.
As long as we have transformQueryForExternalDatabaseAnalyzer, why do we need this file?
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
…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]>
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
LIMITinto external-database queries only when all preceding semantics are preserved remotely.While making the rewriter refuse to push down a
LIMITwhoselimit + offsetoverflowsUInt64, two pre-existing ways of computing that sum turned the overflow into a limit of zero rows, so this also fixes them:NumbersLikeUtils::getLimitFromQueryInfoadded the two values in plainUInt64arithmetic and wrapped around, soSELECT * FROM numbers(10) LIMIT 18446744073709551615 OFFSET 1returned nothing instead of nine rows.system.numbers,generate_seriesandsystem.primeswere affected the same way.LimitStep::getLimitForSortingreturns0as its "unknown" sentinel, andoptimizePrimaryKeyConditionAndLimitpassed it toSourceStepWithFilterBase::setLimit, where it means an exact upper bound on the rows a source may produce.ReadFromPostgreSQLthen sent a real remoteLIMIT 0, turning "all rows except the first" into "no rows".The same helper also handed the outer
LIMITtonumbers-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 1returned nothing instead of50. The hint is now refused when the query has a join.Related: #80070
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add the
external_storage_push_down_limitsetting to reduce data read from external databases for safeLIMITqueries. Also fixLIMITwith a huge value combined withOFFSETreturning an empty result fromnumbers,system.numbers,generate_series,system.primesand thePostgreSQLtable engine, and aLIMITover a join withnumbers-like sources returning too few rows.Workflow [PR]
Sync PR [sync-upstream/pr/115238]
Version info
26.10.1.2083-master(included in26.10and later)