Skip to content

Fix skip+unused_shards through Merge over Distributed in the analyzer - #106250

Merged
novikd merged 3 commits into
masterfrom
fix-skip-shards-in-merge
Jun 2, 2026
Merged

novikd merged 3 commits into
masterfrom
fix-skip-shards-in-merge

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Jun 1, 2026 •

Copy link
Copy Markdown
Member
Claude When a `Distributed` table is wrapped in a `Merge` (engine or `merge()` table function) and the predicate is applied above the `Merge`, the analyzer was pushing the filter past `Distributed` instead of into it. As a result, `optimize_skip_unused_shards` was silently ignored, both shards were queried, and `force_optimize_skip_unused_shards = 2` threw `UNABLE_TO_SKIP_UNUSED_SHARDS`.

collectFiltersForAnalysis only enabled the dummy-plan filter extraction when the top-level table expression was a StorageDistributed (or View / ObjectStorageCluster). For StorageMerge, no extraction happened and query_info.filter_actions_dag was empty by the time StorageMerge::getQueryProcessingStage forwarded it to each child's StorageDistributed::getQueryProcessingStage, so
skipUnusedShardsWithAnalyzer had nothing to evaluate.

Detect StorageMerge that wraps at least one Distributed child and run the filter collection in that case. The filter for the Merge table expression is then forwarded to children naturally via the existing query_info pass-through.

Adds a StorageMerge::hasDistributedTable helper and uses it from collectFiltersForAnalysis in Planner.cpp.

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):

Fix optimize_skip_unused_shards did not apply (and force_optimize_skip_unused_shards falsely failing) when
a Distributed table is queried through a Merge table or the merge table function, with the predicate applied above
it.

Version info

  • Merged into: 26.6.1.328 (included in 26.6 and later)
  • Backported to: 26.5.6.24, 26.4.5.111, 26.3.17.30

When a `Distributed` table is wrapped in a `Merge` (engine or `merge()` table
function) and the predicate is applied above the `Merge`, the analyzer was
pushing the filter past `Distributed` instead of into it. As a result,
`optimize_skip_unused_shards` was silently ignored, both shards were queried,
and `force_optimize_skip_unused_shards = 2` threw `UNABLE_TO_SKIP_UNUSED_SHARDS`.

`collectFiltersForAnalysis` only enabled the dummy-plan filter extraction when
the top-level table expression was a `StorageDistributed` (or `View` /
`ObjectStorageCluster`). For `StorageMerge`, no extraction happened and
`query_info.filter_actions_dag` was empty by the time
`StorageMerge::getQueryProcessingStage` forwarded it to each child's
`StorageDistributed::getQueryProcessingStage`, so
`skipUnusedShardsWithAnalyzer` had nothing to evaluate.

Detect `StorageMerge` that wraps at least one `Distributed` child and run
the filter collection in that case. The filter for the `Merge` table
expression is then forwarded to children naturally via the existing
`query_info` pass-through.

Adds a `StorageMerge::hasDistributedTable` helper and uses it from
`collectFiltersForAnalysis` in `Planner.cpp`.
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4364e2f]

Summary: ✅


AI Review

Summary

This PR makes analyzer filter collection run for Merge wrappers whose child tables need the filter DAG, fixing direct Distributed and View over Distributed cases for optimize_skip_unused_shards. The current implementation is still one Merge layer deep, so a supported nested Merge wrapper can keep the same missing-filter behavior. I posted one inline finding and recommend changes before merge.

Findings

⚠️ Majors

  • [src/Storages/StorageMerge.cpp:308] hasChildTable applies the predicate only to immediate child tables. For Merge -> Merge -> Distributed, the inner StorageMerge does not match storage_requires_filter_collection, so collectFiltersForAnalysis is skipped, StorageDistributed receives query_info.filter_actions_dag == nullptr, and force_optimize_skip_unused_shards = 2 can still raise UNABLE_TO_SKIP_UNUSED_SHARDS for a sharding-key predicate.
    Suggested fix: recurse into child StorageMerge instances, or make the planner predicate account for nested Merge wrappers, and add a focused regression query for Merge over Merge over Distributed.
Tests
  • ⚠️ The new stateless test covers direct Merge and Merge over View, but not nested Merge over Merge over Distributed; that is the smallest test that would prove the generalized wrapper invariant.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: handle nested Merge wrappers when deciding whether analyzer filter collection is required, and cover that shape with a regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 1, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
…tabase

The previous .sql version created objects in `currentDatabase()` which is
unique per test invocation, but concurrent runs of the same test were
indistinguishable in CI's flaky check. Convert to .sh and derive a
dedicated database name from `${CLICKHOUSE_DATABASE}` so that 50 parallel
runs at concurrency 16 pass cleanly.
…storages

The previous fix only enabled filter collection when a `Merge` had a direct
`StorageDistributed` child, missing the case where a `Merge` wraps a `View`
whose body reads from `Distributed`. Top-level `View` already triggers
filter collection unconditionally, so it was inconsistent to ignore it under
`Merge`: `SELECT ... FROM merge(..., '^view$') WHERE <sharding key> = ...`
returned doubled counts and threw `UNABLE_TO_SKIP_UNUSED_SHARDS` under
`force_optimize_skip_unused_shards = 2`.

Generalize the criterion: extract a `storage_requires_filter_collection`
lambda mirroring the top-level loop's checks (`Distributed`, `View`,
`ObjectStorageCluster`, MergeTreeData under parallel-replicas estimation)
and apply it both directly and via `StorageMerge::hasChildTable(predicate)`.

The new `hasChildTable` replaces the narrower `hasDistributedTable` helper
and takes a predicate so callers can stay in sync with the planner's notion
of "what storages need filter analysis" without `StorageMerge` having to
know about each type.

Extend the regression test to cover `Merge` engine and `merge()` function
wrappers over a `View` over `Distributed`.
{
return traverseTablesUntil([&predicate](const StoragePtr & table)
{
return table && predicate(table);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

hasChildTable only applies the predicate to the immediate tables matched by this Merge. If one of those tables is another StorageMerge, the predicate returns false before looking at that inner Merge's children, so a supported shape like Merge -> Merge -> Distributed still skips collectFiltersForAnalysis. Then the inner StorageDistributed receives query_info.filter_actions_dag == nullptr, and force_optimize_skip_unused_shards = 2 still raises UNABLE_TO_SKIP_UNUSED_SHARDS for a predicate on the sharding key. Please recurse into child StorageMerge instances, or otherwise make storage_requires_filter_collection account for nested Merge wrappers, and add a regression query for Merge over Merge over Distributed.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 29/29 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@novikd novikd self-assigned this Jun 2, 2026
@novikd
novikd added this pull request to the merge queue Jun 2, 2026
Merged via the queue into master with commit 9a65e49 Jun 2, 2026
327 of 328 checks passed
@novikd
novikd deleted the fix-skip-shards-in-merge branch June 2, 2026 14:59
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 2, 2026
@clickgapai

clickgapai commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix skip+unused_shards through Merge over Distributed in the analyzer

ClickGap verified: reproduced it with the script below on 26.5; tested 5 version(s) — 4 affected, 1 clean (see Affects); confirmed it predates the oldest available release (pre-existing).

Reproduction

-- optimize_skip_unused_shards / force_optimize_skip_unused_shards is ignored when a
-- Distributed table is queried through a Merge engine with the predicate applied above
-- the Merge (analyzer path). With force_optimize_skip_unused_shards = 2 the filter k = 5
-- must reach each Distributed child's sharding-key analysis. On a buggy build the filter
-- never reaches Distributed, so pruning cannot happen and the query throws
-- UNABLE_TO_SKIP_UNUSED_SHARDS (Code 507) at analysis time (before any network access).
-- Uses the built-in test_cluster_two_shards cluster.

CREATE TABLE data1 (k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k;
CREATE TABLE data2 (k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k;
INSERT INTO data1 SELECT number,        number * 10 FROM numbers(100);
INSERT INTO data2 SELECT number + 1000, number * 10 FROM numbers(100);

CREATE TABLE dist1 AS data1 ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), data1, k);
CREATE TABLE dist2 AS data2 ENGINE = Distributed(test_cluster_two_shards, currentDatabase(), data2, k);
CREATE TABLE merge_dist AS data1 ENGINE = Merge(currentDatabase(), '^dist[12]$');

SET enable_analyzer = 1;
SET optimize_skip_unused_shards = 1;

-- Buggy build: throws Code 507 UNABLE_TO_SKIP_UNUSED_SHARDS.
-- Fixed build: the predicate reaches Distributed, shards are pruned, no 507.
SELECT count() FROM merge_dist WHERE k = 5 SETTINGS force_optimize_skip_unused_shards = 2;

Bisect

  • Present since at least v24.8.14.39 — reproduces on every release line tested down to there; the introducer predates the oldest release with a downloadable binary, so a single commit isn't pinnable from release binaries (not a recent regression).

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 25.8
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 25.8

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-storage-merge
Severity: P2

cc fix PR author: @KochetovNicolai
cc fix PR reviewer: @novikd


ClickGap · Finding: phase_d_pr106250

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 6, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 6, 2026
novikd added a commit that referenced this pull request Jul 7, 2026
Backport #106250 to 26.3: Fix skip+unused_shards through `Merge` over `Distributed` in the analyzer
novikd added a commit that referenced this pull request Jul 7, 2026
Backport #106250 to 26.4: Fix skip+unused_shards through `Merge` over `Distributed` in the analyzer
novikd added a commit that referenced this pull request Jul 7, 2026
Backport #106250 to 26.5: Fix skip+unused_shards through `Merge` over `Distributed` in the analyzer
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jul 9, 2026
…cess

The client-side AST fuzzer loop swallowed every exception thrown during a
fuzzing step: the `catch (...)` handler recorded the error, the loop bottom
reset it, and fuzzing continued. When the failure mode is persistent - most
importantly a dead server, where the reconnection attempt inside
`processParsedSingleQuery` throws instantly - the client sprints through the
remaining corpus at hundreds of steps per second without contacting the
server and exits with code 0, which the job reports as "Fuzzer exited with
success".

Evidence from `AST fuzzer (amd_debug, targeted)` on PR ClickHouse#109061
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109061&sha=1419f6b7e95c81c812f945c06333998b92d56ad3&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29):
`fuzzer.log` records 68972 fuzzing steps, of which 52837 produced no outcome
(silent exception), while `server.log` shows the server received only 209
queries within a 47-second window before dying. On PR ClickHouse#106250
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106250&sha=latest&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29)
a 5-file corpus with ~20 SELECT statements (about 20000 fuzzing steps, over
an hour of work at the measured debug-build rate of 2-6 steps/s) "completed"
in 74 seconds and the job passed. Overall, 13-33% of targeted AST fuzzer
runs per month finish in under 8 minutes of their 30-minute budget.

Client fixes (`programs/client/FuzzLoop.cpp`):
- Print thrown exceptions in the fuzzing-step catch handlers instead of
  swallowing them silently, so `fuzzer.log` shows what actually happened.
- After a thrown exception, check the connection via `tryToReconnect` (the
  same check `processASTFuzzerStep` does for errors received without
  throwing) and stop fuzzing when the server is gone instead of uselessly
  sprinting through the rest of the corpus.
- Register query parameters generated by `QueryFuzzer` (from
  `getLastQueryParameters`) for client-side substitution, mirroring the
  server-side fuzzer in `executeASTFuzzerQueries`; previously any fuzzed
  query containing a substituted `{name:type}` parameter failed with
  "Substitution ... is not set" before reaching the server.

Job fix (`ci/jobs/scripts/fuzzer/run-fuzzer.sh`):
- When the AST fuzzer walks the whole corpus and exits 0 with a meaningful
  part of the FUZZ_TIME_LIMIT budget remaining, restart it (each pass uses a
  fresh random seed) instead of ending the job after a couple of minutes.
  This matters for the targeted variant, whose corpus is a handful of test
  files. The restart is gated on a server liveness probe so a dead server
  still terminates the job for classification.
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…erge` over `Distributed` in the analyzer
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…erge` over `Distributed` in the analyzer
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…erge` over `Distributed` in the analyzer
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…cess

The client-side AST fuzzer loop swallowed every exception thrown during a
fuzzing step: the `catch (...)` handler recorded the error, the loop bottom
reset it, and fuzzing continued. When the failure mode is persistent - most
importantly a dead server, where the reconnection attempt inside
`processParsedSingleQuery` throws instantly - the client sprints through the
remaining corpus at hundreds of steps per second without contacting the
server and exits with code 0, which the job reports as "Fuzzer exited with
success".

Evidence from `AST fuzzer (amd_debug, targeted)` on PR ClickHouse#109061
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109061&sha=1419f6b7e95c81c812f945c06333998b92d56ad3&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29):
`fuzzer.log` records 68972 fuzzing steps, of which 52837 produced no outcome
(silent exception), while `server.log` shows the server received only 209
queries within a 47-second window before dying. On PR ClickHouse#106250
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106250&sha=latest&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29)
a 5-file corpus with ~20 SELECT statements (about 20000 fuzzing steps, over
an hour of work at the measured debug-build rate of 2-6 steps/s) "completed"
in 74 seconds and the job passed. Overall, 13-33% of targeted AST fuzzer
runs per month finish in under 8 minutes of their 30-minute budget.

Client fixes (`programs/client/FuzzLoop.cpp`):
- Print thrown exceptions in the fuzzing-step catch handlers instead of
  swallowing them silently, so `fuzzer.log` shows what actually happened.
- After a thrown exception, check the connection via `tryToReconnect` (the
  same check `processASTFuzzerStep` does for errors received without
  throwing) and stop fuzzing when the server is gone instead of uselessly
  sprinting through the rest of the corpus.
- Register query parameters generated by `QueryFuzzer` (from
  `getLastQueryParameters`) for client-side substitution, mirroring the
  server-side fuzzer in `executeASTFuzzerQueries`; previously any fuzzed
  query containing a substituted `{name:type}` parameter failed with
  "Substitution ... is not set" before reaching the server.

Job fix (`ci/jobs/scripts/fuzzer/run-fuzzer.sh`):
- When the AST fuzzer walks the whole corpus and exits 0 with a meaningful
  part of the FUZZ_TIME_LIMIT budget remaining, restart it (each pass uses a
  fresh random seed) instead of ending the job after a couple of minutes.
  This matters for the targeted variant, whose corpus is a handful of test
  files. The restart is gated on a server liveness probe so a dead server
  still terminates the job for classification.
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
CTE/AN/QP: Distributed read through Merge/merge() with optimize_skip_unused_shards -> perf / false exc.
Effect in the production build a394e92: its upstream test(s) 04303_optimize_skip_unused_shards_in_merge fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04303_optimize_skip_unused_shards_in_merge.

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

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants