Skip to content

Skip a group's key materialization when a HAVING count() bound already rejects it - #120510

Merged
alexey-milovidov merged 35 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregation-having-prefilter
Oct 2, 2026
Merged

alexey-milovidov merged 35 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregation-having-prefilter

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120458

Changelog category (leave one):

  • Performance Improvement

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, for HAVING count() <comparison> <constant> over a GROUP BY. While a two-level bucket of the aggregation result is converted to chunks, a group whose count() 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-cardinality GROUP BY with wide keys, where the discarded keys are most of the conversion. A skipped group is neither filtered nor finalized, so a HAVING conjunct 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. Setting query_plan_aggregation_having_prefilter = 0, or compatibility to a version below 26.10, keeps the previous behavior.

Description

HAVING over a final aggregation is planned as a plain FilterStep over AggregatingStep. The final conversion calls insertKeyIntoColumns for every cell, a deserialize of the arena blob per key column for the serialized method, 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 final AggregatingStep and records it on Aggregator::Params; the conversion tests it in its existing per-cell callback and returns early. The FilterStep stays 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:

  • Default true, following query_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 lone UInt64 key, every group kept. The performance test carries all four shapes.
  • An exception on a rejected group stops being reached, since a dropped group is neither filtered nor finalized. A throwing conjunct before the bound: HAVING intDiv(1, cnt - 3) > 0 AND count() > 3 raises 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 from insertResultInto, such as kolmogorovSmirnovTest on a rejected group whose second sample is empty - that one does not depend on conjunct order, but it is the same elision query_plan_aggregation_bucket_top_k already 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 pins throwIf and an arithmetic error in both orders, and the sibling aggregate next to the bucket_top_k precedent.

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

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

groeneai and others added 6 commits September 17, 2026 00:48
…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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
cold review, over 4 rounds; 3 fix rounds applied.

# Sev Finding Verdict Evidence / action
1 ⚠️ Only > was verified by anything a wrong per-group test would redden: the other four operators had EXPLAIN cells only, and the general-state conversion had no mechanism-sensitive case (05218_query_plan_aggregation_having_prefilter.sql) AGREE, fixed (round 1) new section asserts the exact AggregationHavingPrefilterGroupsSkipped per operator, both directions, on both conversion paths; every arm mutation-proved to move the counter and a returned value
2 ⚠️ The count's state offset inside the cell was only ever exercised as zero, so nothing caught the wrong aggregate state being read as the count (Aggregator.cpp) AGREE, fixed (round 1) two cases now list state-owning aggregates before the count(), so hard-coding the offset to 0 reddens both; the cell leads with uniqExact because groupArray's state starts with its value count, which equals the group's count here
3 ⚠️ The comparison switch was duplicated verbatim in the two conversion paths (Aggregator.cpp) AGREE, fixed (round 1) collapsed into one inline predicate on Aggregator, called from both sites; mutation-proved behaviour-neutral
4 ⚠️ Every map-aggregation conversion updated the new profile event even when nothing was skipped, and Counters::increment has no zero short-circuit (Aggregator.cpp) AGREE, fixed (round 1) both call sites guarded with if (skipped); behaviour-preserving and mutation-proved
5 ⚠️ Only one of the five reversed-operand mappings (4 < count() and friends) had a discriminating cell, so a wrong mapping would record a bound that is not the filter's and lose rows while the suite stayed green (aggregationHavingPrefilter.cpp) AGREE, fixed (round 2) four annotation cells for the uncovered arms plus one reversed-form value pair; a four-arm mutation build moves all four cells 1 -> 0 and collapses the reversed pair's rows to 0 0 (rows the retained filter would keep are lost, so the oracle catches wrong results and not just an accounting number), while the unmutated arm's cell does not move
6 ⚠️ Default true needs Release-build evidence of the non-selective per-group tax, or should default off DISAGREE the instrument asked for is in the PR and can only run here: tests/performance/aggregation_having_prefilter.xml queries 2 and 3 are exactly the two all-kept tax shapes, query 3 the tightest there is, measured on release by this PR's Performance Comparison. The merged query_plan_aggregation_bucket_top_k has the same shape-only admission, the same nothing-pruned tax and the same default, and the false -> true history entry means compatibility restores the old behaviour exactly. The debug win and tax numbers are in the description and the default is put to the owners; if query 3's release tax comes out materially worse than the debug +4.3%, I will propose default false with the CI numbers, unprompted
7 💡 The pass does not mirror the sibling's refusal of Nullable / LowCardinality group keys AGREE, noted not blocking not needed here: the ordinary conversion inserts the null-key row before any pre-filter test, so it is never skipped; both key shapes are pinned by value pairs in the test
8 💡 The rejected-group cleanup comment in convertToBlockImplFinal gave the opposite of the actual bucket lifetime: it said the bucket is not cleared after the conversion, but convertToBlockImpl ends with data.clearAndShrink() AGREE, fixed (round 3) wording only; the code was right and the comment understated its own necessity, since the destructor sweep visits only cells still present in the table, and mapped = nullptr is load-bearing for the sweep that does run if a later key materialization throws
9 💡 The count was read with an open-coded *reinterpret_cast<const UInt64 *>(mapped + count_offset) where Aggregator.h's getCountState() is the canonical accessor AGREE, fixed (round 3) switched to the existing accessor for consistency; identical read, no behavioural or aliasing difference
10 ❌ An exception during key materialization leaks the non-trivial aggregate states of the cells already accepted into places: each is nulled in the hash table as soon as its pointer is stored, places owns nothing, and the destructor sweep skips null cells (Aggregator.cpp) DISAGREE the mechanism is real but it is master's, not this change's, and this change can only shrink it: git show origin/master:src/Interpreters/Aggregator.cpp has the identical three statements in the identical order inside convertToBlockImplFinal, with insertResultsIntoColumns equally deferred and no try/catch in the loop, and the hunk only re-indents that body into a templated lambda with an early return ahead of it. The reject branch returns before touching out_cols or places and destroys its non-trivial states inline (destroy is noexcept), so for any bucket and any throw point the pending set with the pre-filter is a subset of the pending set without it

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Two residuals are disposed of here rather than turned into work: the pending-state cleanup gap row 10
describes exists on master today, independently of this change, and is unmeasured and out of scope; and
no -State-combinator aggregate is in the destroy-path coverage, which would not exercise a distinct
path because AggregateFunctionState::hasTrivialDestructor() delegates to the nested function, the same
predicate the skip path keys on.

Fix round 3 was mergeability: master had advanced 187 commits and landed its own "26.10"
settings-history block at the same anchor, so the entry was folded into master's block (two
same-version blocks make addSettingsChanges throw for every reader of the history). Rows 8 and 9
rode along in that round. 05218 passes single and 50/50 randomized on the merged tree, and Gate B
re-ran on it.

Session id: cron:clickhouse-review-slot-11:20260917-043800

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [117179e]

Summary: ✅


AI Review

Summary

This PR adds a planner annotation plus aggregation-conversion fast path that skips key materialization for groups already rejected by a HAVING count() <op> <constant> bound, and it wires in the corresponding setting, runtime-statistics accounting, tests, and perf coverage. I reviewed the current PR head, the full inline-thread history, and the updated tests/docs, and I do not see any remaining correctness, safety, or performance issues beyond the items already addressed in the existing discussion.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 117179e.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.80% 79.80% +0.00%

Changed lines: Changed C/C++ lines covered: 375/408 (91.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. This is a performance change, so what is reproduced on demand is the cost: on a 30000-group fixture with HAVING count() > 3, ProfileEvents['AggregationHavingPrefilterGroupsSkipped'] is 0 with the setting off and exactly 20000 with it on (= 30000 - 10000 kept), 100% of runs. Not a rate.
b Root cause explained? HAVING over a final aggregation is a plain FilterStep over AggregatingStep. The final conversion calls insertKeyIntoColumns for every cell (for the serialized method a deserialize of the arena blob per key column) and only then does the filter discard the rejected groups, whose count was already in the state the conversion walked past.
c Fix matches root cause? Yes. The bound is tested where the cost is paid, in the existing per-cell callback, before insertKeyIntoColumns. No widened bound, no no-random-* tag, no reduced dataset, no guard masking anything upstream. The FilterStep stays and remains the authoritative filter.
d Test intent preserved / new tests added? New 05218_query_plan_aggregation_having_prefilter (16 applying + 22 refusing EXPLAIN cells, 13 result-equality pairs, 2 block-boundary pairs, 4 group-by-limit throws, the pinned exception-timing shape, the skip_merging refusal), 10 cells asserting the exact number of groups skipped per operator on both conversion paths, and tests/performance/aggregation_having_prefilter.xml (win + two tax shapes + a ClickBench guard). No existing test weakened.
e Both directions demonstrated? Three ways: the counter (0 vs 20000 groups skipped, rows byte-identical); EXPLAIN (the HAVING pre-filter line present with the setting on, absent with it off); timing (-13.9% mean, -16.3% best of 7 paired reps on the targeted shape). Eight mutation proofs: over-restricting any operator, reading the count from the wrong aggregate's offset, or mapping any reversed-operand arm to the wrong operator changes both the skipped count and the returned rows.
f Fix is general across code paths? Verified mechanically. convertToBlockImpl has exactly two call sites, only convertOneBucketToChunk passes the new flag; prepareChunkAndFillSingleLevel takes the = false default. convertToBlockImplFinal has one call site, which forwards it. So mergeBlocks, the serial and parallel single-level merges, the external spill and in-order aggregation are byte-identical to master. The sibling convertOneBucketToChunkTopK is untouched and mutually exclusive (the pass refuses top_k and bucket_top_k).
g Fix generalizes across inputs (params/datatypes/wrappers)? All five operators, each also in its reversed-operand (mirrored) form, and one reversed form end to end on the skipped-group count; Nullable (three keys, and a single key = one_key_nullable_optimization) and LowCardinality (which clears is_simple_count); a NULL-keyed group both passing and failing the bound (it lives outside the cells, so it is never pre-filtered and must be removed by the filter above); tautological, fractional and negative bounds refused; a bound keeping nothing; a second aggregate owning memory (uniqExact, groupArray) with the count() at index 0, 1 and 2 of the aggregate list, so the state-offset lookup is exercised and not only the zero case; group_by_use_nulls; external GROUP BY; single-level; merged and split filter shapes.
h Backward compatible? (maintainer-approved exception only) Yes. New setting, default true, recorded in SettingsChangesHistory.cpp under a new "26.10" block as false -> true, so compatibility with any earlier version restores the previous behaviour. No format, serialization or on-disk change; the Params fields are not serialized and the pass refuses serialize_query_plan / make_distributed_plan, so no follower can receive a plan whose annotation it would not honour.
i Invariants and contracts preserved? Statistics: never acts on a conversion being measured (topk_full_key_bytes == nullptr is part of the activation condition). Group-by row limit: full_group_count comes from the bucket table's size before any conversion branch, pinned by four cells that must still raise TOO_MANY_ROWS with the setting off and on. Block boundaries: one chunk per bucket regardless of survivors, pinned with rowNumberInBlock()/blockNumber() above the retained filter in both regimes; skip_merging, which re-packs per-bucket chunks, is refused at admission. State ownership: a rejected group's non-trivial states are destroyed inline and mapped nulled, so the sweep that runs if a later key materialization throws reads the cell as destroyed; the reject branch returns before touching the output columns. Inactive cost: the pre-filter is a bool template parameter selected outside forEachValue, so the ordinary conversion gains no per-cell branch.

Session id: cron:clickhouse-impl-slot-4:20260917-041700

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 17, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

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_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 52 -20.0% <0.0001 aggregation: Q1 groups by l_returnflag, l_linestatus into four groups and has no HAVING count() bound, so the new pre-filter never activates. The -20.0% shift also falls below master's current range and comes from very noisy runs.
⚠️ 7 not_sure 81 68 -16.0% <0.0001 aggregation: Q7 is a join-heavy query with a small GROUP BY and no HAVING count() bound, so it does not reach the new pre-filter path. The -16.0% shift is not backed by a matching CPU drop.

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
  • StressHouse run: 55e60c87-7549-4439-8c34-573605430f5e
  • MIRAI run: c0b6fdf4-5206-45a7-8ca1-fc947a301901
  • PR check IDs:
    • clickbench_2852359_1790919600
    • clickbench_2852365_1790919600
    • clickbench_2852377_1790919600
    • tpch_adapted_1_official_2852401_1790919600
    • tpch_adapted_1_official_2852415_1790919600
    • tpch_adapted_1_official_2852429_1790919600

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 117179ef7 with master 31d9e00c8 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

80 object files changed (+1.67 MiB total), 1 added.

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

Job report

@harikrishnan94 harikrishnan94 self-assigned this Sep 18, 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.

I like it. Good optimization, fairly good code.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
…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.
Comment thread src/Interpreters/Aggregator.cpp Resolved
alexey-milovidov and others added 2 commits September 20, 2026 09:38
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged origin/master (1048 commits behind, no conflicts) and pushed 18aac86296d8. All 10 changed translation units compile against the merged tree.

The only reds on 5f2d52d99a74 were three Performance Comparison shards: enum #4 (amd 3/6), array_first_last #7 (amd 6/6), and timeseries_to_grid_aggregation_functions #31/#24, lower_upper_utf8_mixed_ascii #4, set_index #1 (arm 5/6). None of these tests has a HAVING clause. The optimization in this PR only runs when a HAVING count() <op> <constant> bound sits above a GROUP BY, so these queries never reach the new code. The Cloud Performance Report on the same commit found no change, and the AI Review verdict is Approve.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Investigated. In master_head mode only the dashboard's confirmed_regression rows fail a shard, so the reds are the four rows below; set_index #1 and timeseries_to_grid_aggregation_functions #24 were in-tree slower only.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 About the Cloud Performance Report on 18aac86296d8 (ClickBench Q17 +11.6%, and Q16/18/32/33/34 marked not_sure): the public Performance Comparison for the same commit does not reproduce it. That job runs the same ClickBench queries A/B against the master reference on the same host, and it shows no slowdown (clickbench perf test, hits_100m_single, new vs old):

Query amd arm
Q16 (GROUP BY UserID, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10) -1.0% -1.3%
Q17 (GROUP BY UserID, SearchPhrase LIMIT 10) -2.2% -0.4%
Q18 (with the minute key) +0.6% +0.8%
Q32 -0.4% -0.7%
Q33 +2.5% (threshold 10%) -1.2%
Q34 +0.9% -4.1%

Across all 787 GROUP BY queries of that run, the median change is -0.2%. Just as many go over +5% (23) as under -5% (22).

This matches the code. When a query has no HAVING count() bound, allow_having_prefilter is false, so convertOneBucketToChunk passes untruncated_keys = nullptr to convertToBlockImpl. The MaterializedKeyBytesMeter is then never constructed. What remains on the default path of convertToBlockImplFinal is one per-row check on an empty std::optional, and it always predicts the same way. The bucket Top-K conversion (Q16/18/32/33/34) builds the meter only when the dataflow statistics ask for it, as master already did for its inline loop. The report also notes that two of its PR runs shared a host, so I'm treating it as noise.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened #122691 for array_first_last #7: nested_values gets 31 inner arrays per row instead of 32, so #6/#7 read it at every page offset rather than at the same few in every row.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened #122728 for lower_upper_utf8_mixed_ascii #4/#5: at 65536 rows per block the non-ASCII path of lowerUTF8/upperUTF8 reserves 16 MiB and the ASCII path 8 MiB, and mixed_01_clustered takes both, so the test now runs at the default block size 65409, where both get 8 MiB.

andybradshaw pushed a commit to andybradshaw/ClickHouse that referenced this pull request Sep 28, 2026
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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 1, 2026
groeneai and others added 2 commits October 1, 2026 18:11
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]>
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 57187208f1d2: a master merge plus a test-only fix for the merge-queue red (Fast test and the flaky check, 05218: array join in having expected 0, got 1).

Since #122240, query_plan_lower_array_join_function lowers the arrayJoin in HAVING cnt > 3 AND arrayJoin([1, 1]) = 1 into its own step, so the filter directly above the aggregation is only count() > 3 and the pre-filter now attaches to it. Results are unchanged: the same rows with the pre-filter on and off, lowered and not, and 4000 groups skipped on the lowered plan. The refusal cell now pins the lowering off, and the lowered shape has its own applied cell and an exact skipped-group cell. 05218 and 05234 pass on the merge-queue tree, plain and with randomized settings.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5718720

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Hung check failed, possible deadlock found not a deadlock: when the hung check started, the server was at its total memory limit (RSS 42.69 GiB of 42.59 GiB), so every probe got MEMORY_LIMIT_EXCEEDED. The memory goes to the unbounded Freeform structure search of test 05258 under a randomized old compatibility: two of its queries were still running at the end of the log and wrote 8.9M FreeformFieldMatcher lines. This PR does not touch any format code #123238 (mine, open)
Mergeable Check, PR rollups, red only because of the row above #123238 (mine, open)

146 of 146 check runs completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR test row on this head.

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

Copy link
Copy Markdown
Member

🕵 Merged origin/master and pushed 117179ef7f8. The PR was CONFLICTING. The only conflict was in QueryPlanOptimizationSettings.cpp: master removed query_plan_aggregation_in_order (it is now obsolete), and this PR declared query_plan_aggregation_having_prefilter beside it, so the merge keeps only the new declaration. clickhouse builds, and 05218_query_plan_aggregation_having_prefilter passes locally. I could not run 05234 here, because it needs the parallel_replicas cluster from the CI config.

The only red on the previous head was Stress test (amd_debug) / Hung check failed. Before the hung check started, the server had already hit its total memory limit. The same red appears on master in CIDB, and the ledger above assigns it to #123238.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit 1592ef9 Oct 2, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
vdimir pushed a commit that referenced this pull request Oct 7, 2026
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]>
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 comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants