Skip to content

Push GROUP BY key predicate to remote shards for aggregating views over Distributed - #109052

Open
groeneai wants to merge 54 commits into
ClickHouse:masterfrom
groeneai:fix-108284-distributed-aggregating-view-predicate-pushdown
Open

groeneai wants to merge 54 commits into
ClickHouse:masterfrom
groeneai:fix-108284-distributed-aggregating-view-predicate-pushdown

Conversation

@groeneai

@groeneai groeneai commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

When a query over a Distributed table is processed on a shard only up to WithMergeableState, the shard does not execute HAVING: the initiator applies it after merging the aggregation states. Under the analyzer, a predicate on a GROUP BY key that reached the shard as HAVING was therefore never used on the shard for partition pruning or primary key analysis, and every shard read and aggregated all of its local data. This happens for a filter over an aggregating view or subquery over a Distributed table, because the pushed-down filter is added to the shard query as HAVING, and also for a plain HAVING on a grouping key. The old analyzer avoided it with PredicateExpressionsOptimizer, which moved such conjuncts to WHERE.

CREATE VIEW v AS SELECT date, login, sum(x) AS s FROM t GROUP BY date, login;  -- t is Distributed
SELECT date, sum(s) FROM v WHERE date = '2024-01-05' GROUP BY date;            -- shard read all partitions

The fix is in Planner: for a query processed up to WithMergeableState, the HAVING conjuncts that do not depend on the aggregation result are moved to WHERE, on the resolved query tree. The classification is shared with the existing analyzer_compatibility_allow_non_aggregate_in_having rewrite in QueryAnalyzer (new moveNonAggregateHavingConjunctsToWhere). Conjuncts with aggregate functions, grouping, arrayJoin or non-deterministic functions stay in HAVING. Window or stateful functions disable the rewrite. WITH CUBE/ROLLUP/TOTALS/GROUPING SETS are skipped. Results are unchanged; only pruning on shards changes.

The serialize_query_plan = 1 path is not covered.

Closes: #108284

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a performance regression of the analyzer: a filter on a GROUP BY key of an aggregating query over a Distributed table (for example, a filter over an aggregating view, or HAVING on a grouping key) is applied on shards before aggregation, so shards can prune partitions and use the primary key. Previously each shard read all of its data, which could lead to MEMORY_LIMIT_EXCEEDED.

🤖 Generated with Claude Code


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

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 2-shard cluster over 2M rows / 10 partitions: SELECT date, sum(s) FROM v WHERE date='2024-01-05' GROUP BY date (v = aggregating view over Distributed t). Remote shard reads 2,000,000 (all partitions) under the new analyzer vs 200,000 (1 partition) under the old one, every run.
b Root cause explained? ReadFromRemote::addFilters pushes the plan-level filter into the shard subquery via PredicateRewriteVisitor::rewriteSubquery, which always inserts it as HAVING and relies on the receiver to move grouping-key conjuncts to WHERE. That move is done by PredicateExpressionsOptimizer, which runs only under the old analyzer. Under the new analyzer the shard keeps the HAVING; since it stops at WithMergeableState (pre-aggregate only, initiator merges), the HAVING is deferred to the initiator and never prunes on the shard.
c Fix matches root cause? Yes. After rewriteSubquery, move the non-aggregate (grouping-key) conjuncts of the pushed HAVING to WHERE on the shard AST, reusing the exact PredicateExpressionsOptimizer split the old analyzer uses. The shard then receives a pre-aggregation WHERE and prunes. Not a band-aid (no widened bounds, no data reduction).
d Test intent preserved / new tests added? New test 04402_analyzer_distributed_aggregating_view_filter_pushdown asserts the shard secondary query carries a pre-aggregation WHERE on the grouping key and no deferred HAVING. Existing HAVING/predicate tests unchanged and passing.
e Both directions demonstrated? Yes. Built both binaries: unfixed → shard query ... GROUP BY date, login HAVING equals(date, ...), reads 2,000,000, test asserts 0 1 (FAIL); fixed → ... WHERE equals(date, ...) GROUP BY date, login, reads 200,000, test asserts 1 0 (PASS).
f Fix is general across code paths? addFilters is the single site that pushes AST predicates into distributed shard subqueries; the fix covers it. The predicate is fixed at the point it is emitted (in the shard AST), not guarded downstream. The separate serialize_query_plan=1 and parallel-replicas mechanisms use plan serialization (not AST pushdown) and are out of scope for this issue (noted in the description).
g Fix generalizes across inputs? Verified old-vs-new results identical for: equality, IN, range (>), non-partition-key grouping key, compound AND, and count(). An aggregate-result predicate (HAVING sum(s) > 0) is correctly left as HAVING (not pushed as WHERE), results identical. argMax nested latest-state view prunes to 200K.
h Backward compatible? Yes. No setting default changed (no SettingsChangesHistory.cpp entry needed), no on-disk/wire/metadata format change. Behavior is result-identical; it only enables shard-side pruning that the old analyzer already did.
i Invariants and contracts preserved? Yes. The WHERE↔HAVING move is only valid, and only applied, when the predicate references pure grouping keys with no aggregate/window function — enforced by the reused is_aggregate_function/is_window_function checks. It is guarded against WITH CUBE/ROLLUP/TOTALS/GROUPING SETS, where a grouping key can be NULL in super-aggregate rows and WHERE != HAVING. ROLLUP results verified identical between analyzers.

Session id: cron:clickhouse-worker-slot-1:20260701-113900

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir — could you review this? Under the new analyzer, ReadFromRemote::addFilters pushes a distributed subquery predicate as HAVING, relying on PredicateExpressionsOptimizer (old-analyzer only) to move grouping-key conjuncts to WHERE. For an aggregating view/subquery over a Distributed table the shard therefore keeps a deferred HAVING and, running only to WithMergeableState, never prunes; this moves the grouping-key predicate to WHERE right after rewriteSubquery (guarded against CUBE/ROLLUP/TOTALS/GROUPING SETS). Fixes #108284.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c05bd84]

Summary: ✅


AI Review

Summary

Restores partition and primary-key pruning for grouping-key predicates on aggregating queries over Distributed tables by moving eligible HAVING conjuncts to shard-side WHERE. No actionable findings remain in the current diff or prior discussion. Current-head Fast test passes the affected regression tests. Focused checks on two servers preserved results and reduced the pruning reproducer from 10 parts to 1 per shard.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 1, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor

That move is performed by PredicateExpressionsOptimizer, which only runs under the old analyzer.

Is this an optimization the new analyzer should have? Not saying this fix is incorrect or not straightforwardly good, but I wonder if there are even user-provided queries with HAVING that could have it promoted to WHERE.

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Good question. The general optimization already exists for local queries, just at the plan level instead of as an AST HAVING->WHERE rewrite: filterPushDown (Optimizations/filterPushDown.cpp, the AggregatingStep/MergingAggregatedStep case) pushes a filter below aggregation when it references only grouping keys, so a plain ... GROUP BY k HAVING k = X already becomes a pre-aggregation filter and prunes. No general rule is missing for the local case.

The regression is specific to the distributed AST round-trip. addFilters does not ship a serialized plan (that is the serialize_query_plan=1 path); it converts the pushed-down filter back to an AST predicate and rewriteSubquery injects it into the shard subquery as HAVING. A shard runs only to WithMergeableState, so HAVING is a deferred initiator-side step that never enters the shard plan, and plan-level filterPushDown on the shard has nothing to act on. WHERE is pre-aggregation, enters the shard plan, and is pushed into the scan. The old analyzer bridged this by running PredicateExpressionsOptimizer on the received query; the new analyzer does not. This PR restores that move where the shard subquery is built, guarded against CUBE/ROLLUP/TOTALS/GROUPING SETS.

On your HAVING hypothesis: a plain SELECT k, sum(x) FROM dist GROUP BY k HAVING k = X likely hits the same shard-side gap for the same reason (shipped to shards, stops at WithMergeableState, no AST HAVING->WHERE move under the new analyzer), and it does not go through addFilters, so this PR does not cover it. The clean general fix would be a plan-level transform that represents grouping-key HAVING conjuncts as a pre-aggregation filter whenever a query executes only to WithMergeableState (covering both paths), but that is a larger surface with its own validation. I would prefer to land this targeted #108284 fix and open a follow-up; I can verify the user-HAVING-over-Distributed case and file it if it reproduces.

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from 3f18a78 to 9f7a607 Compare July 1, 2026 13:55
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the CI failures on the previous push (Fast test + Style check):

Root cause of the Fast-test regressions. The first version ran the HAVING->WHERE move in the shared ReadFromRemote::addFilters for every pushed predicate. That path also serves non-aggregating distributed and parallel-replica reads, whose shard subquery has no GROUP BY and whose own planner already turns the pushed HAVING into a WHERE. Rewriting those unnecessarily changed the sent query text and broke 03302, 03620, and 03733 (the last detects remote pushdown by grepping the sent query for HAVING).

Fix. Gated the move on the shard subquery actually having a GROUP BY (shard_select_query.groupBy() && ...). Only aggregating shard subqueries stop at WithMergeableState and defer the HAVING, so only they need the move. Non-aggregating reads are now byte-identical to before, so 03620 and 03733 pass unchanged; 03302's reference updates only in the #69472 aggregating case, where the shard now prunes (Granules: 123/123 -> 1/123, pre-aggregation Prewhere on x).

Style check. 04402 filtered system.query_log by initial_query_id only; the linter wants a database predicate. The secondary query runs with current_database=default but its databases array contains the test database, so switched the filter to has(databases, currentDatabase()) (also satisfies the linter) rather than current_database = currentDatabase(), which would have dropped the exact secondary row the test checks.

Verified locally on a 2-shard setup (debug build, matching CI): all four tests pass (03302/03620/03733/04402, 3 runs each); old vs new analyzer results identical across eq/IN/range/aggregate-column predicates; shard-side read_rows drops from full-table to a single partition (20000 of 200000), matching the old analyzer.

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch 2 times, most recently from 28300bb to 73cc64d Compare July 1, 2026 14:47
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 73cc64d: fixed the remaining Style check failure. various_checks.sh:186 forbids a bare SYSTEM FLUSH LOGS; qualified it to SYSTEM FLUSH LOGS query_log in 04402_...sh (flushes exactly the query_log the test then reads). No C++ change. Ran various_checks.sh locally (0 findings) and the test 3/3 (1\t0).

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from 73cc64d to eb19d34 Compare July 1, 2026 16:03
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the automated review blocker in eb19d34 (gate the shard-side HAVING->WHERE move on enable_optimize_predicate_expression, plus the = 0 regression variant in 04402).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT date, sum(s) FROM v_agg WHERE date = '2024-01-05' GROUP BY date SETTINGS enable_analyzer = 1, enable_optimize_predicate_expression = 0 over test_cluster_two_shards: before the gate the secondary query got a shard-side WHERE (pruned); the switch could no longer disable pushdown.
b Root cause explained? The new tryMovePredicatesFromHavingToWhere call in ReadFromRemote::addFilters ran unconditionally. That function is the optimizer behind enable_optimize_predicate_expression; the old analyzer only reaches it via PredicateExpressionsOptimizer::optimize, which returns early when the setting is 0. The new call site skipped that gate, so = 0 no longer disabled predicate pushdown for the distributed path.
c Fix matches root cause? Yes. Gated the call on settings[Setting::enable_optimize_predicate_expression], restoring exact old-analyzer semantics (the setting is the documented disable switch for this optimizer).
d Test intent preserved / new tests added? Yes. 04402 now asserts both directions on the secondary query: = 1 -> pre-aggregation WHERE (1 0), = 0 -> deferred HAVING (0 1). The original = 1 assertion is unchanged; the = 0 variant locks the disable-switch contract the bot asked for.
e Both directions demonstrated? Yes (2-shard debug build, Build ID ea6b8a00). = 1: secondary WHERE equals(date, ...), read_rows 10000/100000 (prunes). = 0: secondary GROUP BY ... HAVING equals(date, ...), read_rows 100000 (no pruning). Results identical (60002). 04402 + siblings 03302/03620/03733 all pass.
f Fix is general across code paths? Yes. The gate is added to the single call site that does this move; addFilters is the only place the new-analyzer distributed path performs the AST HAVING->WHERE rewrite. Non-aggregating distributed / parallel-replica reads were already excluded by the groupBy() guard and stay byte-identical.
g Fix generalizes across inputs? Yes for the setting contract (the gate is a boolean check independent of predicate datatype/wrapper). The pushdown itself is still guarded against WITH CUBE/ROLLUP/TOTALS/GROUPING SETS (grouping key may be NULL). No new input-type surface is introduced by this change.
h Backward compatible? Yes, and this change specifically restores backward compatibility: enable_optimize_predicate_expression = 0 again reproduces the pre-PR behavior (predicate stays in HAVING, no shard pruning). No setting default or on-disk/wire format changed.
i Invariants and contracts preserved? Yes. tryMovePredicatesFromHavingToWhere is only invoked when the shard subquery has GROUP BY + HAVING and no super-aggregate constructs, and now only when the setting permits pushdown, matching the contract enforced by PredicateExpressionsOptimizer::optimize. Query results are unchanged in both settings.

Session id: cron:clickhouse-worker-slot-10:20260701-155100

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from eb19d34 to 4ee964a Compare July 1, 2026 18:09
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up push 4ee964a fixes two PR-caused flaky-check failures introduced by this PR's changes (04402 and 03302). Pre-PR validation gate for that follow-up below.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04402 fails on demand with --client-option prefer_localhost_replica=0 (10/10 FAIL before fix): both shards emit a secondary query, so countIf(query LIKE '%HAVING%date%') read 2 not 1 -> 0 2, the exact CI diff. 03302 fails on demand with --client-option enable_optimize_predicate_expression=0 (10/10 FAIL before fix): the aggregating EXPLAIN reverts to the unpruned plan.
b Root cause explained? 04402: the two placement checks were asymmetric. predicate_in_where was boolean (> 0) but grouping_key_in_having was a raw count, and CI randomizes prefer_localhost_replica; when 0, both of the two shards log a secondary query so the raw HAVING count is 2. Also the secondary query_log rows are written asynchronously, so a single flush can miss them. 03302: this PR makes the aggregating shard subquery prune only when enable_optimize_predicate_expression = 1 (the new gate); the test never pinned that setting, so a randomized 0 reverted the plan to the unpruned form and mismatched the reference.
c Fix matches root cause? Yes. 04402: make grouping_key_in_having a boolean (> 0) so the result is independent of shard count, and wait for the secondary rows in a flush-and-retry loop. 03302: pin enable_optimize_predicate_expression = 1 alongside the other plan-shaping settings the test already pins, so it deterministically exercises the pushdown-enabled path its reference now verifies.
d Test intent preserved / new tests added? Yes. 04402 still asserts WHERE placement when the setting is on and HAVING placement when off (1 0 / 0 1), unchanged reference; the boolean just tolerates 1-or-2 shard rows. 03302 still verifies the pruned distributed plan; the pin removes randomization noise without weakening any assertion.
e Both directions demonstrated? Yes. 04402: old raw-count test 10/10 FAIL (0 2) vs fixed 30/30 PASS under forced prefer_localhost_replica=0; 50/50 PASS under full randomization. 03302: 10/10 FAIL under forced enable_optimize_predicate_expression=0 before the pin vs PASS after; 40/40 PASS under randomization and 10/10 PASS even when the client forces the setting to 0 (query-level SET wins).
f Fix is general across code paths? N/A (test-only determinism fix; the source fix and its scope were validated earlier in this PR). Confirmed the sibling distributed-pushdown tests 03620 and 03733 are unmodified by this PR and still pass 40/40 under randomization.
g Fix generalizes across inputs? N/A (flaky-test setting/assertion fix, not a code bug).
h Backward compatible? N/A (test-only change).
i Invariants and contracts preserved? N/A (test-only change; no code invariants touched).

Session id: cron:clickhouse-worker-slot-4:20260701-174200

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from 4ee964a to 193fb97 Compare July 1, 2026 21:21
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

The distributed plan job hung 04402 for the full 600s. Root cause is the test method, not the fix: 04402 scraped system.query_log for the remote-shard query text, and that job runs with serialize_query_plan = 1 (installed server-wide by --distributed-plan), so the shard receives a serialized plan rather than SQL and no matching query_log row is ever written. The flush-and-retry loop's exit condition never fired, so it looped over an ever-growing parallel query_log until the timeout.

Rewrote 04402 to inspect the shard plan directly with EXPLAIN indexes = 1, distributed = 1 (the canonical pattern already used by sibling 03302), asserting the shard-side index Condition on the grouping key. This is deterministic, fast (0.2s), parallel-safe, and needs no query_log. It pins serialize_query_plan = 0 (so EXPLAIN can introspect shard index usage) and prefer_localhost_replica = 0 (so both shards go through the remote path). No source change; the enable_optimize_predicate_expression gate from the previous commit is unchanged.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Locally, with the server default serialize_query_plan = 1 (the --distributed-plan condition), the old query_log-based test's secondary-row count was always 0, so the 60x/0.5s loop ran to exhaustion; over CI's large parallel query_log each SELECT count() scan is slow, cumulatively hitting the 600s per-test timeout. Confirmed by CIDB: a single stuck SELECT count() FROM system.query_log client left in the process group.
b Root cause explained? --distributed-plan installs serialize_query_plan = 1 (users.d/distributed_plan.xml). The remote shard then receives a serialized plan, not SQL text, so no is_initial_query = 0 row with query LIKE '%t_local_04402%' is ever logged (verified locally: 0 secondary rows under sqp=1 vs 1-2 under sqp=0). The loop's secondary >= 1 exit is never satisfied -> 60 iterations x (FLUSH LOGS + full query_log scan) -> timeout.
c Fix matches root cause? Yes. Replaced the query_log-scraping method with EXPLAIN indexes=1, distributed=1, which introspects the shard plan directly and does not depend on secondary-query logging. Pinning serialize_query_plan = 0 is required because under sqp=1 the distributed EXPLAIN only shows ReadFromTable (no index introspection).
d Test intent preserved / new tests added? Preserved and strengthened. The test still asserts the exact behavior it was written for: predicate pushed to a pre-aggregation shard WHERE (index pruning: Condition: (date in ...)) when enable_optimize_predicate_expression = 1, and left as a deferred HAVING (no shard pruning: Condition: true) when 0. It also asserts results are identical (60002) in both cases.
e Both directions demonstrated? Yes. opt=1 -> predicate_pushed_to_shard=1, shard_reads_all_partitions=0; opt=0 -> 0, 1. Verified end-to-end against a 2-shard local server; 30/30 passes under randomized settings (incl. serialize_query_plan on/off, both prefer_localhost_replica values, group_by_two_level_threshold_bytes=1, distributed_aggregation_memory_efficient on/off) and 4/4 across index_granularity 1/8192/100000/113 and min_bytes_for_wide_part 0/1GB. Critically, passes with server default serialize_query_plan = 1 (the exact job that hung) because the test's own SET overrides it.
f Fix is general across code paths? N/A (test-determinism fix, not a code bug). The enable_optimize_predicate_expression + groupBy() + CUBE/ROLLUP/TOTALS gating on the source side is unchanged from the prior commit.
g Fix generalizes across inputs? N/A (test-determinism fix, not a code bug). Granule signature verified granularity-independent across index_granularity 1/8192/100000/113.
h Backward compatible? N/A (test-only change; no settings/format/behavior change).
i Invariants and contracts preserved? N/A (test-only change). The EXPLAIN-based assertion is a strict subset check on the shard plan text; it introduces no new invariants.

Session id: cron:clickhouse-worker-slot-0:20260701-205800

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from 193fb97 to 2604acf Compare July 1, 2026 22:38
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up push 2604acf7 addressing the pre-existing-HAVING coverage review comment. Test-only increment (no source change): extended 04402 to cover the carrier where the grouping-key predicate is in the aggregating view's own HAVING.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 2-shard cluster, a view ... GROUP BY date, login HAVING date = '2024-01-05' queried via SELECT date, sum(s) FROM v GROUP BY date deterministically prunes the shard (reads 10000/100000) with enable_optimize_predicate_expression = 1 and reads all 100000 with it = 0. Reproduced on demand.
b Root cause explained? The reviewer noted addFilters only handles pushed_down_filters, so a pre-existing inner HAVING would miss the move. In practice filterPushDown converts that plain HAVING into a filter pushed into ReadFromRemote, so addFilters does run and the move sweeps the whole shard HAVING (incl. the pre-existing conjunct) to WHERE. The only carrier where filterPushDown bails is TotalsHavingStep (WITH TOTALS); the old analyzer does not prune that either (moving to WHERE would change the TOTALS value).
c Fix matches root cause? No source change needed: the existing fix already covers the pre-existing-HAVING carrier. This push adds regression coverage locking that behavior, which is what the review asked for ("extend the regression coverage to that carrier too").
d Test intent preserved / new tests added? Yes. Added a second view (v_hav_04402) with an inner HAVING on the grouping key; asserts shard pruning with the setting on (1 0), no pruning with it off (0 1), results identical either way (60002). Existing assertions unchanged.
e Both directions demonstrated? Yes. setting=1 -> shard WHERE ... AND (date=...), reads 10000 (prunes); setting=0 -> shard keeps HAVING, reads 100000 (no pruning). Both measured via read_rows and asserted via EXPLAIN indexes=1, distributed=1 Condition.
f Fix is general across code paths? N/A (test-only increment; the source fix and its sibling-path scope were validated on the earlier commits).
g Fix generalizes across inputs? Verified the carrier matrix: outer-WHERE, inner-HAVING view, standalone SELECT * FROM v, direct GROUP BY ... HAVING, and WITH TOTALS. All prune under both analyzers except WITH TOTALS, which neither prunes (correct).
h Backward compatible? N/A (no behavior/setting/format change; test-only). The enable_optimize_predicate_expression = 0 disable switch is exercised for this carrier too.
i Invariants and contracts preserved? Yes. Results identical across setting on/off and vs the old analyzer (60002); only pruning changes, never correctness.

Session id: cron:clickhouse-worker-slot-7:20260701-221700

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from 2604acf to f03fe3a Compare July 1, 2026 23:58
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Test-only follow-up on f03fe3af507da: pin optimize_skip_unused_shards = 0 in 04402 to remove a randomized-setting confound that made the two enable_optimize_predicate_expression = 0 shard-pruning assertions fail (149/149 FAIL with randomization on the prior head). No source change; the fix from eb19d34 is unchanged.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN indexes=1, distributed=1 on the OFF-path with optimize_skip_unused_shards=1 returns 1 0 every time (should be 0 1); the CI minimizer named --optimize_skip_unused_shards True and a local --test-runs 30 gave 14 FAIL.
b Root cause explained? optimize_skip_unused_shards is an orthogonal initiator-side optimization that rewrites the shard query with a shard-selection index Condition on the sharding/partition key regardless of the predicate pushdown. So with enable_optimize_predicate_expression=0 (pushdown disabled, predicate stays in HAVING) the shard EXPLAIN still shows Condition: (date in ...), flipping the OFF assertion from 0 1 to 1 0.
c Fix matches root cause? Yes. Pins only the single confounding setting (optimize_skip_unused_shards = 0), isolated by auditing every distributed/shard-pruning randomized setting (optimize_skip_unused_shards_rewrite_in, optimize_distributed_group_by_sharding_key, parallel_replicas_local_plan do NOT flip the assertion). Not a blanket no-random-settings.
d Test intent preserved? Yes. The test still measures that the enable_optimize_predicate_expression pushdown drives shard-side index pruning (ON = pruned Condition, OFF = Condition: true). Pinning the orthogonal setting removes the confound without weakening any assertion.
e Both directions demonstrated? Yes. Without the pin: 14/30 FAIL under randomization. With the pin: 50/50 PASS under randomization; also PASS when the client forces --optimize_skip_unused_shards 1 (the SQL set ... = 0 wins). Siblings 03302/03620/03733 also 10/10 each (no regression).
f Fix is general across code paths? N/A (flaky test setting fix, not a code bug).
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (flaky test setting fix, not a code bug).
h Backward compatible? (maintainer-approved exception only) N/A (flaky test setting fix, not a code bug).
i Invariants and contracts preserved? N/A (flaky test setting fix, not a code bug).

Session id: cron:clickhouse-worker-slot-1:20260701-234100

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f03fe3a

CI fully finished. Every blocking check is green: all Stateless (incl. 04402 + 03302), Integration, Unit, Stress, AST fuzzer, BuzzHouse, and all five flaky-checks passed on this head. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64 + aarch64) transient infra: master binary Start ClickHouse Server exit-115 boot crash in setup (0 tests ran; non-blocking); same window hit 4 unrelated PRs (#108005, #108681, #109052, #109071) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Finish Workflow / Mergeable Check (Post Hooks) aggregators reflecting the non-blocking bugfix-validation red above same owner as above
CH Inc sync private fork-sync mirror CH Inc sync (private, not actionable)

No PR-caused failure. The source fix (predicate move to shard WHERE) is unchanged since @alexey-milovidov / @KochetovNicolai / @vdimir last reviewed; the earlier PR-caused reference and flaky-check items were resolved on prior heads.

Session id: cron:our-pr-ci-monitor:20260702-040000

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Bugfix-validation server-boot exit-115 infra failure on the CI finish ledger: #109115 (retry the transient initial clickhouse-server boot in functional-test setup). The failure on this PR (sha f03fe3a, Start ClickHouse Server exit-115, err.log never created) was a transient boot death, not a defect in this PR's binary — every other server-booting check passed on the same commit, and a sibling PR's same-SHA rerun passed.

@groeneai
groeneai force-pushed the fix-108284-distributed-aggregating-view-predicate-pushdown branch from f03fe3a to 527b0d0 Compare July 2, 2026 12:08
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a local 2-shard server, EXPLAIN indexes = 1, distributed = 1 of the aggregating view query shows Condition: true / Granules: 10/10 (no pruning) before the fix path runs, vs Condition: (date in [19727, 19727]) / Granules: 1/10 with it. Gated deterministically by enable_optimize_predicate_expression (1 = WHERE/prune, 0 = HAVING/no prune).
b Root cause explained? New analyzer: ReadFromRemote::addFilters pushes the plan filter into the shard subquery as HAVING via rewriteSubquery, then relied on PredicateExpressionsOptimizer (old-analyzer only) to move grouping-key conjuncts to WHERE. That optimizer never runs under the new analyzer; the aggregating shard stops at WithMergeableState so the HAVING is deferred to the initiator and never prunes.
c Fix matches root cause? Yes. The move is done inline right after rewriteSubquery with a self-contained AST helper, restoring the pre-aggregation WHERE on the shard. This rework (527b0d0) removes the old-analyzer PredicateExpressionsOptimizer dependency per the review, using only generic AST utilities.
d Test intent preserved / new tests added? Yes. New test 04402 asserts shard pruning for both the outer-WHERE and inner-HAVING carriers, both setting = 1 (WHERE, prunes) and = 0 (HAVING, no prune), results identical. 03302/03620/03733 unchanged behavior.
e Both directions demonstrated? Yes. setting = 0 -> Condition: true, Granules 10/10 (no prune); setting = 1 -> Condition: (date in ...), Granules 1/10 (prune). Results identical (60002) both ways. 04402+03302 pass 60/60 under randomization; all four tests pass.
f Fix is general across code paths? Yes. The move covers both carriers that reach addFilters: an outer-WHERE predicate and a view's own inner HAVING (filterPushDown turns the latter into a pushed filter into ReadFromRemote). WITH TOTALS is intentionally excluded (both analyzers do not prune it).
g Fix generalizes across inputs? N/A for datatype wrappers (the move classifies conjuncts structurally by aggregate/window/stateful, independent of column type). Covered: grouping-key predicate in outer WHERE and in inner HAVING; guarded against WITH CUBE/ROLLUP/TOTALS/GROUPING SETS.
h Backward compatible? Yes. enable_optimize_predicate_expression = 0 keeps the pre-PR behavior (predicate stays in HAVING, no shard pruning) for this distributed path. No setting default, format, or validation change.
i Invariants and contracts preserved? Yes. The helper only re-splits the shard subquery's own HAVING conjuncts between WHERE and HAVING (semantics-preserving for plain GROUP BY); aggregate/window/stateful conjuncts stay put; results verified identical. No old-analyzer infra invoked.

Session id: cron:clickhouse-worker-slot-1:20260702-112700

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (cc7ccc8). There were no conflicts, and the PR's translation units (moveNonAggregateHavingConjunctsToWhere.cpp, QueryAnalyzer.cpp, Planner.cpp) build. The remaining red checks on 0262c53 are not caused by this PR:

@groeneai, investigate the 00284_external_aggregation_2 failure in the private sync run of this PR (https://github.com/ClickHouse/clickhouse-private/pull/79316, job https://github.com/ClickHouse/clickhouse-private/actions/runs/40430348969/job/121952004416) and provide a fix in a separate PR. If the fix is already in progress, or already in the master that was just merged, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm investigating the 00284_external_aggregation_2 CANNOT_WRITE_AFTER_BUFFER_CANCELED failure and will follow up here with a fix PR, or with the existing fix if one is already in flight. I can't open the private job, and public CI has no occurrence of this signature in the last 30 days (0 failures in about 130k runs of the test), so if you can paste the exception's stack trace from that run, it would help me pin the spill site.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The CANNOT_WRITE_AFTER_BUFFER_CANCELED is most likely a secondary error. Since #123531 the adaptive aggregator writes its staged records to one spill stream per partition that all threads append to. When one thread's write throws, WriteBuffer::next cancels the stream, the next thread that appends to it gets 734, and the executor can report that thread's exception instead of the first one. I reproduced this locally by making the spill writes fail with max_temporary_data_on_disk_size_for_query (10 of 10 runs print 734).

Fix: #128016. A failed write is now kept and rethrown to the later appends, so the query reports the error that broke the stream.

I can't read the private log, so the original error of that run is not confirmed. If a failed write broke the stream there too, its next occurrence will report that error instead of 734. Public CI ran this test 3730 times since #123531 (1749 of them with s3 or azure storage), with no failure.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cc7ccc8

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything #126200 (mine, open)
Fast test (arm_darwin) / 05227_mutate_part_ahead_of_table_metadata_version_mergetree flaky, not from this PR (the test is not in its diff): the rewrite dropped the column: 1 instead of 0, failing on 55 PRs in the last 2 days #127925 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05339_decimal_wide_comparison_scale_overflow flaky, not from this PR: the replica rejected the Decimal(18, 18) constant sent to it with Decimal value is too big (ARGUMENT_OUT_OF_BOUND), the same failure on 8 other PRs in parallel replicas jobs in 30 days #126652 (mine, open)
Stress test (arm_asan_ubsan) / AddressSanitizer: heap-use-after-free (STID: 1938-332e) crash, not from this PR: the embedded client (LocalServerPty) finalized its output format in ClientBase::resetOutput after a failed initOutputFormat had freed the FlushCallbackWriteBuffer under it. Same STID on 7 other PRs and 4 times on master in 3 days #127912 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126200, #127925, #126652, #127912 (the owners of the rows above)
Sync - CH Inc sync (private, not actionable by me)

No job was dropped. Both Bugfix validation legs passed: their FAIL rows are the new tests failing on the master build, as expected. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261028-033006

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (1376595) without conflicts; moveNonAggregateHavingConjunctsToWhere.cpp, QueryAnalyzer.cpp and Planner.cpp build. The merge brings in the fixes for three of the unrelated failures on cc7ccc8: #127925 (05227_mutate_part_ahead_of_table_metadata_version_mergetree), #126652 (05339_decimal_wide_comparison_scale_overflow) and #127912 (ASan heap-use-after-free in LocalServerPty). Build profile diff (LogClusterNotReady) is CI infrastructure, still open in #126200.

@novikd, the change no longer touches ReadFromRemote.cpp. Your four comments from 2026-07-02 and 2026-08-19 are addressed: no old infrastructure is used, the rewrite works on the resolved query tree in Planner, the classification is shared with the analyzer_compatibility_allow_non_aggregate_in_having rewrite in QueryAnalyzer, and it runs once per query. Could you re-review when you have time? Your CHANGES_REQUESTED review is still blocking.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1376595

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
Fast test (arm_darwin) / 05397_clickhouse_local_locked_path_untouched not from this PR (the test is not in its diff): the new test holds the status lock with flock(1), which macOS does not ship, so the second clickhouse local never runs and Another server instance in same directory is already running is missing. It fails on every darwin run since it landed: 26 PRs today, no OK row #128088 (mine, open; its own Fast test (arm_darwin) runs the test OK)
Mergeable Check, PR praktika rollups of the row above #128088 (the owner of the row above)

Both Bugfix validation (functional tests) legs passed: their FAIL rows are the new tests failing on the master build, as expected. All five flaky check builds passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261028-230003

…NG` rewrite

The traversal of `moveNonAggregateHavingConjunctsToWhere` visited the arguments
listed in `TableFunctionNode::getUnresolvedArgumentIndexes`, like the query of
`view` or the arguments of a parameterized view. They are deliberately left
unresolved, so `getResultType` threw `Function node with name 'plus' is not
resolved` for queries over `Distributed` with such a subquery in `HAVING`.
Skip these arguments, as `InDepthQueryTreeVisitorWithContext` does.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109052&sha=latest&name_0=PR&name_1=Fast%20test%20(arm_darwin) (05397_clickhouse_local_locked_path_untouched on arm_darwin: the Another server instance in same directory is already running line is missing) 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

The fix is #128088 (mine), merged at 16:27 UTC. The test holds the status lock with util-linux flock(1), which macOS does not ship, so the second clickhouse local never runs and the expected line is missing. The test is now tagged no-darwin.

The run you linked is on 1376595 (2026-10-28), built before the fix. The CI now running on 4d828e0 checked out merge commit 0d88a14 on top of cbccce8 (the #128088 merge), so its Fast test (arm_darwin) will skip the test.

alexey-milovidov and others added 5 commits October 30, 2026 11:31
… on shards

`CAST([k] AS Array(Date))`, `CAST(tuple(k) AS Tuple(Date))` and
`CAST(map('a', k) AS Map(String, Date))` convert each nested number as a Unix
timestamp in the time zone of the executing server, but `dependsOnServerTimeZone`
checked only a scalar `Date`/`Date32` result with a numeric first argument, so
such conjuncts were moved to `WHERE` on the shards. Now the `CAST` family is
server-dependent when its result contains a `Date`/`Date32` and its argument
contains a number at any depth. `hasImplicitTimeZone` reuses the new
`containsType` helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ring in `HAVING` on shards

The `String` overloads of `toWeek`, `toYearWeek` and `toDayOfWeek` parse the
string in `CustomWeekTransformImpl` as a point in time in the time zone of the
executing server, unless the third (time zone) argument is given. There is no
`DateTime` node for `hasImplicitTimeZone` to catch, so a shard with a different
time zone could move such a conjunct to `WHERE` and drop its contribution.
Treat these calls as server-dependent when the time zone argument is omitted
or empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a string

An empty time zone argument is rejected by `toWeek`, `toYearWeek` and
`toDayOfWeek` with `ILLEGAL_TYPE_OF_ARGUMENT`, so only the omitted one
selects the time zone of the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Planner/Planner.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (c189bd9). There was one conflict in src/Planner/Planner.cpp: master added checkParallelReplicasImplementationOfSubqueries at the same place as this PR's moveNonAggregateHavingConjunctsToWhere call. I kept both. The HAVING rewrite runs first, then the new check, and both still run before collectSets. The binary builds. The PR's 11 new tests and 03302_analyzer_distributed_filter_push_down pass locally. CI on 58314ba had no failures. No review threads are unresolved. The blocking CHANGES_REQUESTED review from @novikd still needs a re-review (see the comment from 2026-10-28).

# Conflicts:
#	src/Planner/Planner.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (7b5f2bf). There was one conflict in src/Planner/Planner.cpp, in the includes only: master added Analyzer/traverseQueryTree.h next to this PR's Analyzer/moveNonAggregateHavingConjunctsToWhere.h; I kept both. moveNonAggregateHavingConjunctsToWhere.cpp, QueryAnalyzer.cpp and Planner.cpp build. The PR's file list is unchanged. All review threads are resolved; the blocking CHANGES_REQUESTED review from @novikd still needs a re-review.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0deab63

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
Upgrade check (amd_release) / Download script failed + Check failed infra, not from this PR: the previous-release .deb downloads from GitHub release assets got 504/503/read timeouts on all 10 attempts during the 2026-11-08 GitHub incident (10 unrelated PRs between 08:56Z and 10:29Z) #130181 (mine, open)
Mergeable Check, PR praktika rollups of the row above #130181

The Bugfix validation FAIL rows in CIDB are this PR's tests failing on master, as intended; both Bugfix validation checks passed.

Session id: cron:our-pr-ci-monitor:20261108-193008

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (f229367). The merge was clean, and the PR's file list and diff are unchanged. The binary builds. The PR's 11 new or changed tests, including 03302_analyzer_distributed_filter_push_down and 04402_analyzer_distributed_aggregating_view_filter_pushdown, pass locally. The only red check on 0deab63 was Upgrade check (amd_release): the release download timed out during the GitHub incident on 2026-11-08 (tracked in #130181). The merge triggers a fresh CI run. No review threads are unresolved. The blocking CHANGES_REQUESTED review from @novikd still needs a re-review.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (e8cb3be). The merge was clean, and the PR's file list and diff are unchanged. The binary builds. The PR's 11 new or changed tests and 03302_analyzer_distributed_filter_push_down pass locally. CI on the previous head had no failures, and no review threads are unresolved. The blocking CHANGES_REQUESTED review from @novikd still needs a re-review.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (521c4bc). The merge was clean, and the PR's file list and changed lines are unchanged. The binary builds, and the PR's 11 new or changed tests plus 03302_analyzer_distributed_filter_push_down pass locally.

The red on de54b7e was not a test failure: 32 jobs of that run were cancelled before any step ran (Mergeable Check: Failed: 0, Dropped: 32), and the Bugfix validation rows are this PR's tests failing on master, as intended. The merge triggers a fresh CI run.

No review threads are unresolved. The blocking CHANGES_REQUESTED review from @novikd still needs a re-review.

This branch has not been deployed

No deployments
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-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Analyzer regression: predicate on a GROUP BY key is not pushed to remote shards when reading through an aggregating view over a Distributed table

6 participants