Repository navigation
Skip a group's key materialization when a HAVING count() bound already rejects it - #120510
alexey-milovidov merged 35 commits into
Conversation
…s it HAVING over a final aggregation is planned as a plain FilterStep over AggregatingStep (Planner.cpp). The final conversion calls method.insertKeyIntoColumns for every cell - for the `serialized` method a deserialize of the arena blob into each key column - and only then does the filter discard the groups the bound rejects. The count the filter tests is already in the aggregate state the conversion walks past, so those keys are materialized purely to be thrown away. On the reported TPC-DS SF10 query_23 shape that materialization is 18.4% of CPU samples. A new plan optimization, `aggregationHavingPrefilter`, recognises a bound on the aggregation's own no-argument count() directly above a final AggregatingStep and records the operator, threshold and aggregate index on Aggregator::Params. The final conversion tests the bound inside its existing per-cell callback and returns early, so insertKeyIntoColumns is never reached for a rejected group. The FilterStep stays in the plan and remains the authoritative filter, which is the whole correctness argument: the pre-filter may drop only groups the filter would drop, and dropping fewer than it could is always sound. Every group the conversion does not reach - the null-key group, a single-level table, an unsupported method - is simply passed through and filtered above, exactly as before. The pass runs in the final traversal of optimizeTreeSecondPass, beside tryOptimizeGroupByTopK, rather than from getOptimizations(). An annotation placed in the first pass is a prediction about a plan that has not stopped changing, and each later rewrite that can void it then needs its own retraction: earlier drafts of this change grew a withdrawal hook in tryMergeFilters, a Cascades exclusion and a skipMerging() override. From the final traversal the shape read is the shape that executes - a merged, split or partially pushed-down filter is read as it will run, and skip_merging, Cascades, projections and parallel-replica conversion have all already happened - so those three hooks are unnecessary and mergeExpressions.cpp and Cascades/Rules/AggregationPushdown.cpp are not touched at all. Ordering the pass after tryOptimizeGroupByTopK makes the two mutually exclusive with no edit to the sibling: it sets params.top_k, which this pass refuses. Admission requires a final, non-grouping-sets, non-overflow_row, keyed aggregation that is not only_merge, in-order, skip_merging, or already carrying top_k / bucket_top_k, under a filter whose value does not depend on how many rows it is evaluated on, in a plan that is neither distributed nor serialized. The evaluation-count predicate is promoted out of optimizeJoin.cpp into Optimizations/Utils as isSensitiveToEvaluationCount() and shared, so `rand()` and `rowNumberInAllBlocks()` (including inside a lambda) refuse while `now()` and `today()` do not. skip_merging is refused because that path adds a SimpleSquashingChunksTransform which re-packs the per-bucket chunks by row and byte thresholds, and rowNumberInBlock above the retained filter can see that. At run time the bound is honoured from one call site only: convertOneBucketToChunk passes allow_having_prefilter to convertToBlockImpl, and the parameter defaults to false so no other conversion can acquire it by accident. It is withheld when a runtime dataflow statistics updater is attached, because those statistics require the untruncated output (RuntimeDataflowStatistics.h). The group-by row limit is unaffected: full_group_count is filled from the bucket table's size before any conversion branch. Block boundaries are unaffected: convertOneBucketToChunk hardcodes return_single_block = true, so one chunk per bucket however many groups survive. A rejected group's non-trivial aggregate states are destroyed inline and its mapped pointer nulled, because the bucket is not cleared after an ordinary conversion and retaining them would hold one state per rejected group until ~AggregatedDataVariants. The pre-filter is a bool template parameter whose instantiation is selected outside forEachValue, so an aggregation without a qualifying HAVING gains no per-cell branch. One behaviour change is deliberate and test-pinned rather than guarded: a throwing conjunct evaluated before the bound stops being reached, because dropping a group elides the filter expression on that group. ClickHouse already accepts this class for plan optimizations - 01655_plan_optimizations.sh:208-210 asserts that `select throwIf(number = 5) from (select * from numbers(10)) order by number limit 1` returns 0 although row 5 exists, and FilterStep splits an AND into sequential filters by default. The tree models "must not be skipped" as IFunction::hasObservableSideEffects(), which sleep declares and throwIf does not; throwIf instead opts into lazy skipping (isSuitableForShortCircuitArgumentsExecution), and its isSuitableForConstantFolding() == false exists to stop it being evaluated EARLY during DAG analysis, which is the opposite property. Guarding on that flag was offered and declined for those reasons. Alternatives rejected: a separate conversion function mirroring convertOneBucketToChunkTopK (~165 duplicated lines, and that structure is necessitated by top-K semantics, where the winners are not known until every cell has been seen, whereas a fixed threshold is decidable the moment the callback holds the cell); tolerating one intervening ExpressionStep between the filter and the aggregation, as optimizeGroupByTopK does (a step below the filter is evaluated on the pre-filtered input, which would re-introduce the obligation to check a second expression); expressing the bound through the sibling's bucket_top_k machinery (top-K keeps the n best cells, this keeps all cells past a threshold). Analysis and the TPC-DS SF10 measurement are @ snelheidai's. Related: ClickHouse#120458
The switch on Params::having_prefilter_op was written out twice, once in the is_simple_count conversion and once in convertToBlockImplFinal, so the code deciding which rows disappear had two copies and one covered operator. It is now a single inline Aggregator::havingPrefilterKeeps(UInt64), and the general path reads the count from mapped + count_offset at the call site. The test grew a section that reads ProfileEvents['AggregationHavingPrefilterGroupsSkipped'] back from system.query_log for each of the four operators the earlier cells did not cover, twice on the inline conversion and twice on the general one with a state-owning aggregate ahead of the count, so the offset lookup runs with a non-zero index. The fixture has 10000 groups of count 4 and 20000 of count 3, so each cell asserts an exact number: >= 4 skips 20000, < 4 skips 10000, <= 3 skips 10000, = 4 skips 20000, and every setting-off arm skips none. Four mutations were used to confirm the section can fail. Over-restricting any one operator changes that operator's cell and no other, and pinning count_offset to 0 changes both general cells - in each case both the skipped count and the returned rows, so a wrong bound is caught as wrong results and not merely as an accounting number. groupArray may not be the aggregate the offset is measured from: GroupArrayNumericData's first member is the number of values collected, which equals the group's count, so reading offset 0 there returns the right answer by coincidence and hides a wrong offset. uniqExact leads that cell instead, with groupArray second and the count third. ProfileEvents::increment is now guarded by if (skipped). Counters::increment reads the current CPU and walks the whole parent chain with no zero short-circuit, and the increment sat on every map-aggregation conversion, including those that never opt in. Removing the guard again leaves the test green, which is the proof the guard changes nothing else.
A bound written with the constant on the left reaches the conversion through mirror(), which maps the operator to the one the conversion will read. Only Less had a cell, so four of the five arms were unverified, and a wrong arm records a bound that is not the filter's: the conversion then skips groups the retained FilterStep would have kept, and those rows are lost. The applies section now has one cell per arm (4 >= count(), 4 <= count(), 4 > count(), 4 = count()), each asserting the mirrored operator in the annotation, and the skipped-group section gained one reversed-operand pair, so the composition "the reversed form records op X" plus "op X is honoured exactly" is demonstrated rather than argued: 4 <= cnt skips 20000 of 30000 groups and returns the same 10000 40000 either way. Mutating the four arms in one build turns all four new cells from 1 to 0 and takes the reversed pair from 20000 skipped and 10000 40000 rows to 30000 skipped and 0 0, while the untouched Less arm and every other row stay put.
Master added its own "26.10" settings-history block at the same anchor, carrying max_bytes_before_external_distinct and max_bytes_ratio_before_external_distinct. addSettingsChanges() throws LOGICAL_ERROR on a duplicate version key, so the two blocks cannot both stand: the entry for query_plan_aggregation_having_prefilter is folded into master's block, unchanged.
convertToBlockImplFinal open-coded a read that Aggregator.h's getCountState() already provides with the NOLINT that pun needs, while the sibling simple-count branch goes through its getInlineCountState() wrapper. The read is identical. The comment above the rejected-group cleanup stated the opposite of what happens: convertToBlockImpl ends in data.clearAndShrink(), so the bucket IS cleared once the conversion returns. That is exactly why the inline destroy is required - destroyImpl walks the table with forEachMapped, so it can only reach cells that are still in it, and without the inline destroy a rejected group's states would never be destroyed at all. It is also why the cell is nulled: if a later key materialization throws, the clear is skipped, that sweep does run, and an already destroyed cell has to read as destroyed. Co-Authored-By: Claude Opus 5 <[email protected]>
Delete comments narrating the change's own design, condense the rest to standalone invariants.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex): 6 gate findings plus 9 from my own
Severity: ❌ blocker / Two residuals are disposed of here rather than turned into work: the pending-state cleanup gap row 10 Fix round 3 was mergeability: master had advanced 187 commits and landed its own Session id: cron:clickhouse-review-slot-11:20260917-043800 |
|
Workflow [PR], commit [117179e] Summary: ✅
AI ReviewSummaryThis PR adds a planner annotation plus aggregation-conversion fast path that skips key materialization for groups already rejected by a Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 117179e.
Changed lines: Changed C/C++ lines covered: 375/408 (91.91%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260917-041700 |
collectConjuncts() and the conjunct loop both call node->function_base->getName(), but the translation unit only had the forward declaration of IFunctionBase that comes in from ActionsDAG.h. The full local build pulls the definition in transitively, so this compiled everywhere I built it; Fast test configures with ENABLE_LIBRARIES=0 and a pruned include graph where it does not arrive, and failed with "member access into incomplete type 'element_type' (aka 'const DB::IFunctionBase')" at lines 73 and 138. A forward declaration is not enough here because a member is called, not just a pointer held. Functions/IFunction.h is what the sibling passes in this directory include for the same call: actionsDAGUtils.cpp, fuseFilterIntoArrayJoin.cpp, pushDownVolumeReducingFunctions.cpp and updateQueryConditionCache.cpp. Reproduced the failure in the Fast test cmake configuration locally (identical two errors, identical lines), then built CI's target set clickhouse-bundle/clickhouse-stripped/lexer_test in that configuration: 7157/7157, no errors. Every .cpp this PR touches now compiles under a pruned include graph, with SessionSettings.cpp checked in a separate ENABLE_BUZZHOUSE=1 configuration because Fast test excludes BuzzHouse.
trueOrFalseSetting carries oracle_values {"0", "1"}, and every setting
with non-empty oracle_values is inserted into queryOracleSettings. That
oracle runs a query twice with the value flipped and reports
"failed with different success results" when one run raises and the other
does not.
This PR deliberately pins exactly that divergence: 05218 asserts that
HAVING throwIf(cnt = 3, 'boom') = 0 AND count() > 3 raises
FUNCTION_THROW_IF_VALUE_IS_NON_ZERO with the setting off and succeeds
with it on, because dropping a group before the filter runs elides the
filter's evaluation on that group. The divergence is intended and
precedented (01655_plan_optimizations.sh pins the same class for the
limit optimization), so the registration is what has to change, not the
semantics. Any conjunct that can raise for some group, not just
throwIf, reaches this.
trueOrFalseSettingNoOracle holds the same trueOrFalse generator with
empty oracle_values, so ordinary fuzzing still randomizes the setting
while the equivalence oracle stops asserting on it. Measured on the
built objects: oracle_values.size() is 2 for trueOrFalseSetting and 0
for trueOrFalseSettingNoOracle, and enrollment is exactly
!oracle_values.empty(). This matches query_plan_convert_join_to_in,
which is registered NoOracle for the same reason.
The automated review asked whether the candidate has to be restricted to
the left-most non-trivial AND atom, on the grounds that the current plan
surfaces exceptions this pass suppresses.
Measured on a master binary that has no knowledge of the setting: the
outcome of HAVING <throwing conjunct> AND count() > N already follows the
written order of the conjuncts, and in the bound-first order two
independently defaulted mechanisms elide the error already. Both have to
be off for that order to throw:
HAVING count() > 3 AND intDiv(1, cnt - 3) > 0
query_plan_merge_filters=1 short_circuit_function_evaluation=enable OK
query_plan_merge_filters=0 short_circuit_function_evaluation=enable OK
query_plan_merge_filters=1 short_circuit_function_evaluation=disable OK
query_plan_merge_filters=0 short_circuit_function_evaluation=disable ILLEGAL_DIVISION
HAVING intDiv(1, cnt - 3) > 0 AND count() > 3
ILLEGAL_DIVISION in all four
So the pass is not restricted to a position in the conjunction, which
would make it depend on the order the conjuncts happen to be written in.
What the review did expose is a coverage gap. The divergence was pinned
with throwIf alone, which opts into lazy argument execution via
isSuitableForShortCircuitArgumentsExecution, so the broader case of an
ordinary arithmetic error was not covered. Pin it in both orders.
The new setting-1 arm is not vacuous: with the annotation present but
single-level aggregation, where the bucket conversion never honours it,
the first arm returns ILLEGAL_DIVISION instead of 10000.
50 runs of 05218 pass with settings redrawn each run.
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a HAVING count() pre-filter to the conversion of two-level aggregation buckets. It turns on only for a final GROUP BY with a HAVING bound on its own count(). The flagged TPC-H improvements, Q1 (-20.0%) and Q7 (-16.0%), have no HAVING clause and produce only a few groups, so they never reach the changed path. With the pre-filter off, the refactored conversion loop runs the same per-row code as before. Both results are downgraded to not_sure because the PR cannot plausibly explain them. Both medians land below master's current range, the source runs for both benchmarks shared one machine, and both queries have noisy history. Run-environment variance explains these shifts better than the PR does. clickbench🟢 No significant changes tpch_adapted_1_officialFlagged queries (2 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o |
20.06 MiB | 21.68 MiB | +1.63 MiB (+8.11%) |
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/aggregationHavingPrefilter.cpp.o |
new | 37.23 KiB | +37.23 KiB |
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
175 translation units recompiled, 1612 s compile time in total, 174 of them have a recent master baseline.
Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +95.7 s (+6%) in total before that adjustment.
Translation units without a recent master baseline:
src/Processors/QueryPlan/Optimizations/aggregationHavingPrefilter.cpp: 6.1 s
alexey-milovidov
left a comment
There was a problem hiding this comment.
I like it. Good optimization, fairly good code.
…ected The pre-filter switched itself off whenever convertOneBucketToChunk received a non-null key-bytes counter, which is exactly when a RuntimeDataflowStatisticsCacheUpdater is attached to the aggregation. The automatic parallel replicas optimization attaches one when it has to (re)collect statistics for a plan: no statistics cached for it yet, the table's row count drifted by more than 2x since they were, or automatic_parallel_replicas_mode = 2 (considerEnablingParallelReplicas.cpp). So whether the pre-filter ran depended on the state of a process-global statistics cache that has no user-visible flush. The setting is allowed to change whether a throwing conjunct written before the bound is reached, and 05218 pins that. It is not allowed to make that depend on instrumentation state, which is what this was. Measured on this branch with automatic_parallel_replicas_mode = 1, one query, one settings set, three runs: run 1 (statistics recollected): Code: 395 FUNCTION_THROW_IF_VALUE_IS_NON_ZERO run 2, run 3: 10000 rows, 20000 groups skipped What the statistics need is the untruncated output, which the Top-K conversion already reports rather than switching itself off. The pre-filter now reports it too: while the bucket still holds every group, the keys are materialized into the columns the conversion would have produced and recorded from those, so the statistics see the same columns they saw before this change, and the pass runs only while statistics are being collected. On the 30000-group fixture of 05218 that is byte for byte what an un-pre-filtered run records: AggregationKeys bytes=1248890, sample_bytes=24261, compressed_bytes=3759, output bytes=223503 in both. Recording the truncated chunk's keys instead loses about half of the estimate, which is what the new estimate cell is there to catch. The new cells are not wrapped in a subquery: the optimization matches the plan node of the top-level aggregation and skips a plan whose aggregation is nested, attaching no updater, which would leave them measuring an ordinary run. They also assert that statistics were collected at all, for the same reason. Without this change the throwIf cell fails with Code: 395. A side-effecting conjunct is refused where it could see the truncation. sleep is the only function in the tree declaring observable side effects: written directly it is pushed below the aggregation before the pass looks, and inside a lambda that captures the aggregate, where it cannot be pushed, the pass refuses it. Measured, with a pure lambda over the aggregate admitted beside it as the control, and both pinned.
`recordUntruncatedKeySizes` learned the size the dataflow statistics need by materializing the whole bucket's keys into full-sized columns before the conversion, and kept them resident until the record returned. On the shape the pre-filter targets - a high-cardinality `GROUP BY` with wide keys, most of them rejected - that is another full-sized materialization of the output the optimization exists to avoid, paid only on the first, cold-cache execution, so `automatic_parallel_replicas_mode` could turn the win into a `max_memory_usage` failure or a one-off latency spike. Account for the keys the way the bucket Top-K conversion already does instead: `MaterializedKeyBytesMeter` materializes one key at a time onto a single reused row, adds `byteSizeAt` and pops it back, so the accounting is bounded whatever the bucket holds. The meter rides the conversion's existing pass over the cells rather than adding one of its own, and the resulting byte count reaches the statistics through the same `full_key_bytes` parameter the Top-K path uses, so `recordAggregationKeySizes` keeps seeing the untruncated size with the truncated chunk as the compression sample. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A rejected group is neither filtered nor finalized, so an aggregate that throws from `insertResultInto` on that group - `kolmogorovSmirnovTest` with one empty sample - stops raising, and unlike a throwing `HAVING` conjunct this does not depend on the order the conjuncts are written in. Pin it in both directions, next to a cell that pins the same elision already performed by default on master by the bucket Top-K conversion (`query_plan_aggregation_bucket_top_k`), which likewise destroys a rejected group's states without finalizing them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…n-having-prefilter
|
🕵 Merged The only reds on @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120510&sha=5f2d52d99a745fd8479d7ea2b4eac649c61337db&name_0=PR and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
Investigated. In
|
|
🕵 About the Cloud Performance Report on
Across all 787 This matches the code. When a query has no |
|
I opened #122691 for |
|
I opened #122728 for |
Query ClickHouse#7 of tests/performance/array_first_last.xml (arrayLast over Array(Array(UInt64))) takes a different time in each server process of the same build. In 14 days of Performance Comparison runs on amd it moved by more than 15% between the two servers in 50 of 633 runs, 36 of them master against master, while ClickHouse#6 (arrayFirst over the same column) moved in 0 of 641 and the tuple queries ClickHouse#4/ClickHouse#5 in 2 and 3; arm is quiet. Per run, ClickHouse#6 and ClickHouse#7 move in opposite directions (r = -0.53 over 524 amd runs; in 33 of the 37 runs where ClickHouse#7 moved by more than 15%, ClickHouse#6 moved the other way), while ClickHouse#4/ClickHouse#5 move together (r = +0.42). Each nested_values row holds 32 inner arrays of 2 UInt64, so rows are 256 bytes apart in the inner offsets and 512 bytes apart in the data. ClickHouse#6 and ClickHouse#7 read one inner array per row, so for the whole query every row is read at the same position modulo 256/512 bytes, i.e. at the same few offsets inside every memory page. Which offsets those are depends on where the column is allocated: jemalloc is built with cache_oblivious, which puts every large allocation at a random multiple of 64 bytes inside its first page, and the table is filled once per server. So each server reads the column at its own fixed page offsets. Fill nested_values with 31 inner arrays per row. Rows are then 248/496 bytes apart and the read position walks through every offset of the page within one query, so the timing no longer depends on the allocation. The query texts and the per-row work (one copy of a 2-element array per row, 250000 rows) are unchanged. Local check with the official master build 26.10.1.906 on a Xeon 6975P-C: 16 separately filled copies of the table per arm in one server, measured round-robin for 20 rounds. This machine does not show the spread with either layout (ClickHouse#7 across copies: 14.14-14.68 ms with 32 elements and random allocation offsets, 13.93-14.27 ms page-aligned with MALLOC_CONF=cache_oblivious:false, 13.95-14.32 ms with 31 elements), so it cannot confirm the mechanism and the change rests on the CI data. The level of ClickHouse#7 stays (31 vs 32 elements: 0.98x); ClickHouse#7/ClickHouse#6 goes from 1.11 to 1.03. Related: ClickHouse#120510 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n-having-prefilter
Since ClickHouse#122240, `query_plan_lower_array_join_function` also lowers an `arrayJoin` that sits next to other conjuncts in a HAVING filter: the plan becomes `ArrayJoin -> Filter(count() > 3) -> Aggregating`, so the filter directly above the aggregation no longer holds the `arrayJoin` and the pre-filter legitimately attaches to it. The `array join in having` cell then saw the annotation and failed in the merge queue (`0` expected, `1` observed). The cell exists to exercise the `hasArrayJoin` refusal, so it now pins the lowering off, which keeps the `arrayJoin` inside the filter the pass reads. The lowered shape gets its own applied cell and an exact skipped-group pair (4000 of 6000 groups skipped on the `on` arm, the same rows as the `off` arm and as the un-lowered plan). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Pushed Since #122240, |
CI finish ledger - 5718720Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
146 of 146 check runs completed, Session id: cron:our-pr-ci-monitor:20261002-023151 |
…n-having-prefilter Resolved a conflict in `QueryPlanOptimizationSettings.cpp`: master removed `query_plan_aggregation_in_order`, the PR added `query_plan_aggregation_having_prefilter` next to it; kept only the latter.
|
🕵 Merged The only red on the previous head was |
The previous commit declares `isSensitiveToEvaluationCount` in
`Optimizations/Utils.h`, but the file-static copy with the same body is
still in `optimizeJoin.cpp`, so that file does not compile ("static
declaration follows non-static declaration"). Remove the copy and keep
its comment for `canMergeExpressionIntoJoinGraph`, as #120510 does on
master.
Related: #123829
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #120458
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a query-plan optimization, controlled by the new setting
query_plan_aggregation_having_prefilter, forHAVING count() <comparison> <constant>over aGROUP BY. While a two-level bucket of the aggregation result is converted to chunks, a group whosecount()cannot satisfy the bound is now skipped before its key columns are materialized, instead of being materialized and then discarded by the filter above. This speeds up "groups above a threshold" queries over a high-cardinalityGROUP BYwith wide keys, where the discarded keys are most of the conversion. A skipped group is neither filtered nor finalized, so aHAVINGconjunct written before the bound, and a sibling aggregate's finalization, stop being evaluated on the groups the bound rejects: a query that raised an exception from one of those can now return rows instead. Settingquery_plan_aggregation_having_prefilter = 0, orcompatibilityto a version below26.10, keeps the previous behavior.Description
HAVINGover a final aggregation is planned as a plainFilterStepoverAggregatingStep. The final conversion callsinsertKeyIntoColumnsfor every cell, a deserialize of the arena blob per key column for theserializedmethod, and only then does the filter discard the rejected groups.A plan pass recognises a bound on the aggregation's own no-argument
count()directly above a finalAggregatingStepand records it onAggregator::Params; the conversion tests it in its existing per-cell callback and returns early. TheFilterStepstays and remains authoritative, so the pass may only drop groups the filter would drop, and dropping fewer is always sound.Validated: 20000 of 30000 groups skipped, identical rows, a new stateless test, 50/50 randomized runs.
Two questions for the aggregation owners:
true, followingquery_plan_aggregation_bucket_top_k. The pass fires on plan shape alone, so there is a tax as well as a win. Debug build, paired reps: -13.9% on the targeted shape (3.9M groups, 0.25% kept); no measurable tax with wide keys, every group kept; +4.3% on the tightest case, a loneUInt64key, every group kept. The performance test carries all four shapes.HAVING intDiv(1, cnt - 3) > 0 AND count() > 3raises with the setting off, returns rows with it on; written after the bound it is already elided on master, so that outcome follows conjunct order. Also a sibling aggregate throwing frominsertResultInto, such askolmogorovSmirnovTeston a rejected group whose second sample is empty - that one does not depend on conjunct order, but it is the same elisionquery_plan_aggregation_bucket_top_kalready performs by default on master, measured on the same fixture. The tree accepts the class for plan optimizations (01655_plan_optimizations.sh:208-210). The test pinsthrowIfand an arithmetic error in both orders, and the sibling aggregate next to thebucket_top_kprecedent.Analysis and the TPC-DS SF10
query_23-16.2% are @ snelheidai's, in #120458; not re-measured here.Workflow [PR]
Sync PR [sync-upstream/pr/120510]
Version info
26.10.1.1310-master(included in26.10and later)