Skip to content

Fix logical error on const-folded sharding key in skipUnusedShards - #108737

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-distributed-sharding-key-const-fold
Jun 29, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-distributed-sharding-key-const-fold

Conversation

@groeneai

@groeneai groeneai commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

No related open issue found (searched "Cannot find sharding key column", "skipUnusedShardsWithAnalyzer", "sharding key column expression").

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 an exception (Cannot find sharding key column, and in debug/sanitizer builds a server abort) when a Distributed table's sharding key is an expression the analyzer const-folds, for example if(1, toInt32(id), toInt32(id) + 1), with optimize_skip_unused_shards = 1.

Description

The sharding key column name is captured from the unanalyzed sharding key AST in the StorageDistributed constructor. Building the sharding key expression analyzes (and may rewrite) it: the analyzer const-folds an expression like if(1, toInt32(id), toInt32(id) + 1) (or the fuzzer's if(2 AS a, toInt32(id), t0)) down to toInt32(id), so the stored raw name is absent from the expression outputs. Every consumer that then looks the column up in the analyzed expression failed:

  • skipUnusedShardsWithAnalyzer threw LOGICAL_ERROR: Cannot find sharding key column ... (aborts the server in debug/sanitizer builds, handled exception in release);
  • isShardingKeySuitsQueryTreeNodeExpression (the GROUP BY sharding-key pushdown path) threw UNKNOWN_IDENTIFIER;
  • the sharding-key IN rewrite (OptimizeShardingKeyRewriteIn) and DistributedSink::createSelector threw NOT_FOUND_COLUMN_IN_BLOCK.

Fix: resolve sharding_key_column_name to the actual expression output name once at construction. The expression is built with project = false, so its DAG has the sharding key output plus its source-column inputs. Resolve by structure: a single-output DAG is the key (even when that output is an input column, for a key that folds all the way down to a bare source column such as if(1, id, id + 1) -> id); otherwise the key is the unique output that is not a source column (e.g. intHash64(id), whose outputs are [id, intHash64(id)]). As defense in depth, skipUnusedShardsWithAnalyzer and isShardingKeySuitsQueryTreeNodeExpression now degrade gracefully (skip the optimization and query all shards) instead of asserting when the column still cannot be resolved unambiguously.

Reproducer (aborts the server in a debug build before this change):

CREATE TABLE data (id Int32) ENGINE = MergeTree ORDER BY id;
INSERT INTO data SELECT number FROM numbers(100);
SET optimize_skip_unused_shards = 1;
SELECT _shard_num, * FROM remote('127.{1..4}', view(SELECT toInt32(id) AS id FROM data), if(1, toInt32(id), toInt32(id) + 1))
WHERE id IN (0, 1, 2147483647) ORDER BY _shard_num, id;

After the fix the query returns the same result as the equivalent plain toInt32(id) sharding key. A regression case is added to 01930_optimize_skip_unused_shards_rewrite_in.

Found by the AST fuzzer (STID 3926-38e4) as a mutation of 01930_optimize_skip_unused_shards_rewrite_in.

Version info

  • Merged into: 26.7.1.255 (included in 26.7 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET optimize_skip_unused_shards=1; SELECT _shard_num, * FROM remote('127.{1..4}', view(SELECT toInt32(id) AS id FROM data), if(1, toInt32(id), toInt32(id)+1)) WHERE id IN (0,1,2147483647) aborts the server every time on a debug build.
b Root cause explained? Yes. sharding_key_column_name is captured from the unanalyzed AST. Building the expression const-folds if(1, x, y) to x, so the analyzed DAG output is named toInt32(id) while the stored name is if(1, toInt32(id), plus(toInt32(id),1)). tryFindInOutputs(name) misses, so skipUnusedShardsWithAnalyzer throws LOGICAL_ERROR.
c Fix matches root cause? Yes. The name is resolved to the actual expression output once at construction (the single non-source output of the project=false DAG), so every consumer that looks it up in the analyzed expression finds it.
d Test intent preserved / new tests added? Yes. No existing assertion weakened; a regression case (if(1, toInt32(id), toInt32(id)+1)) added to 01930_optimize_skip_unused_shards_rewrite_in, asserting the const-folded key gives the same result as the plain toInt32(id) key (shard skipping still works).
e Both directions demonstrated? Yes. Pre-fix (Build ID 076bb50d): Cannot find sharding key column + server abort. Post-fix (Build ID 6dc4488b): clean result 1 0 / 2 1, identical to the plain key; updated test passes 10/10 with randomization.
f Fix is general across code paths? Yes. The same divergence broke four consumers (skipUnusedShardsWithAnalyzer, isShardingKeySuitsQueryTreeNodeExpression, OptimizeShardingKeyRewriteIn, DistributedSink::createSelector). Fixing the name at the source (construction) covers all four; the two shard-skipping entry points also degrade gracefully (skip optimization, query all shards) if the column is ever unresolvable, instead of asserting.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified across const-fold forms (if(2 AS a, x, t0), if(1, x, y), if(0, y, x), multiIf(...), x + 0, x AS k) and integer widths (Int8/16/32/64, signed/unsigned) in 01930; all give results identical to the plain key. Normal keys (plain column, toInt32(id), modulo) are unchanged (fast-path name match).
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, on-disk/wire format, or behavior change for valid queries. The only behavior change is for the previously-broken const-folded-key case, which now works instead of throwing; no setting needed.
i Invariants and contracts preserved? Yes. The invariant sharding_key_column_name names an output of sharding_key_expr is now established correctly at construction. The resolver only changes the stored name when the raw name is absent and a single unambiguous non-source output exists; otherwise it leaves the name as-is (unchanged from prior behavior). The result type / selector contract (createSelector reads the same output column) is preserved.

Session id: cron:clickhouse-worker-slot-4:20260628-100300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @devcrafter — could you review? A const-folded sharding key (e.g. if(1, toInt32(id), toInt32(id)+1) collapses to toInt32(id)) made sharding_key_column_name (taken from the raw AST) no longer match the analyzed expression output, so skipUnusedShardsWithAnalyzer threw Cannot find sharding key column. Fix resolves the name to the actual DAG output at construction.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49630ae]

Summary: ✅


AI Review

Summary

This PR fixes Distributed shard skipping and related consumers by resolving sharding_key_column_name to the analyzed sharding-key DAG output when constant folding rewrites the expression. The current code covers both computed-output and bare-source folds, and I found no unresolved correctness issues after checking the prior inline discussion and current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 28, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
A distributed sharding key that the analyzer const-folds (e.g.
if(1, toInt32(id), toInt32(id) + 1) collapses to toInt32(id)) produces an
expression whose output name no longer matches the unanalyzed key name stored
in sharding_key_column_name. Every consumer that looks the column up in the
analyzed expression then failed: skipUnusedShardsWithAnalyzer threw a
LOGICAL_ERROR (aborting the server in debug/sanitizer builds),
isShardingKeySuitsQueryTreeNodeExpression threw UNKNOWN_IDENTIFIER, and the
sharding-key IN rewrite / DistributedSink selector threw NOT_FOUND_COLUMN_IN_BLOCK.

Resolve sharding_key_column_name to the actual expression output name once at
construction. A key can fold all the way down to a bare source column
(if(1, id, id + 1) -> id), in which case the project=false DAG has a single
output that is itself an input column; resolve a single-output DAG to that
output regardless, and use the non-source-column heuristic only for
multi-output DAGs (e.g. intHash64(id), whose outputs are [id, intHash64(id)]).
skipUnusedShardsWithAnalyzer and isShardingKeySuitsQueryTreeNodeExpression
additionally degrade gracefully (skip the optimization, query all shards)
instead of asserting when the column still can't be resolved.

Found by the AST fuzzer (STID 3926-38e4).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-distributed-sharding-key-const-fold branch from afecc7b to f713d8a Compare June 28, 2026 21:28
@groeneai

Copy link
Copy Markdown
Collaborator Author

Updated pre-PR validation gate for the refined fix (source-column-fold case from the review).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. optimize_skip_unused_shards=1 + remote('127.{1..4}', view(select id from data), if(1, id, id + 1)). Non-analyzer path threw TOO_MANY_ROWS (block.has miss); analyzer path silently full-scanned all shards. Both reproduce on demand.
b Root cause explained? sharding_key_column_name is captured from the unanalyzed key AST (if(...)), but building the expression analyzes/const-folds it. When the key folds to a bare source column (if(1, id, id+1) -> id), the project=false DAG has a single output that is itself an input column. The prior "single non-source output" fallback skipped it (it IS a source column) and returned nullptr, so sharding_key_column_name stayed the raw if(...), which getByName/block.has/createSelector can't find.
c Fix matches root cause? Yes. Resolve a single-output DAG to that output regardless of whether it is an input; restrict the non-source-column heuristic to multi-output DAGs. This directly resolves the folded name for every consumer.
d Test intent preserved / new tests added? Yes. Existing 01930 cases unchanged. Added two regressions: the source-column fold if(1, id, id + 1) over view(select id), and a plain-id baseline, asserting identical shard sets.
e Both directions demonstrated? Yes (Build ID ee1866e1). Pre-fix: non-analyzer TOO_MANY_ROWS, analyzer full-scan. Post-fix: both skip correctly; INSERT via DistributedSink::createSelector routes by the folded key with no NOT_FOUND_COLUMN_IN_BLOCK (8 rows routed to the correct shards).
f Fix is general across code paths? Yes. The single resolution at construction fixes all four consumers uniformly: skipUnusedShardsWithAnalyzer, isShardingKeySuitsQueryTreeNodeExpression, the IN-rewrite (OptimizeShardingKeyRewriteIn), and DistributedSink::createSelector. The first two also degrade gracefully (return nullptr/false, query all shards) if a key is ever unresolvable, instead of asserting.
g Fix generalizes across inputs? Verified against a key matrix on a local 4-shard cluster: toInt32(id) (computed), if(1,id,id+1) / if(1,a,b) / if(0,a,b) (fold to source col), intHash64(id) / modulo / a+b / multiIf (computed, multi-output), if(2 AS a, toInt32(id), t0) (original fuzzer mutation), plain id. All resolve to the same shard set as the equivalent plain key, on both enable_analyzer=0 and 1.
h Backward compatible? N/A. No setting, format, or default change. Pure correctness fix; previously-working keys behave identically.
i Invariants and contracts preserved? Yes. tryFindShardingKeyOutput returns a node owned by sharding_key_dag; callers only read result_name / pass it to evaluateExpressionOverConstantCondition. The DAG-output invariant (key output plus source-column inputs; multi-output puts sources alongside the computed key) is confirmed empirically. Unresolvable keys take the safe fallback (skip optimization), never assert.

Session id: cron:clickhouse-worker-slot-4:20260628-205000

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

The change looks in general fine. However, the code abuses if auto and other implicit semantics making it difficult to read in detail

There is a potential behavior change here, not sure it is desired.

Comment thread src/Storages/StorageDistributed.cpp Outdated
const auto sharding_key_outputs = sharding_key_dag.findInOutputs(Names{sharding_key_column_name});
return allOutputsDependsOnlyOnAllowedNodes(sharding_key_outputs, irreducibe_nodes, matches);
const auto * sharding_key_output = tryFindShardingKeyOutput(sharding_key_dag, sharding_key_column_name);
if (!sharding_key_output)

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.

Explicit (sharding_key_output == nullptr) is cleared to read. Also if possible avoid the "auto" for simple types like this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 49630ae: const ActionsDAG::Node * sharding_key_output = tryFindShardingKeyOutput(...); then if (sharding_key_output == nullptr).

Comment thread src/Storages/StorageDistributed.cpp Outdated
const auto & sharding_key_dag = sharding_key_expr->getActionsDAG();
const auto * expr_node = sharding_key_dag.tryFindInOutputs(sharding_key_column_name);
const auto * expr_node = tryFindShardingKeyOutput(sharding_key_dag, sharding_key_column_name);
if (!expr_node)

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.

explicit nullptr comparison

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 49630ae: if (expr_node == nullptr), and spelled out the types (const ActionsDAG &, const ActionsDAG::Node *).

Comment thread src/Storages/StorageDistributed.cpp Outdated

/// With several outputs the key is the one that is not a source/input column: for `intHash64(id)`
/// the outputs are [id, intHash64(id)] and `id` is only a source column.
NameSet source_columns;

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.

const Names &names = sharding_key_dag.getRequiredColumnsNames();
const NameSet source_columns(names.begin(), names.end());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 49630ae: adopted const Names & names = sharding_key_dag.getRequiredColumnsNames(); then const NameSet source_columns(names.begin(), names.end());. Also replaced the remaining auto in the helper (const ActionsDAG::NodeRawConstPtrs & outputs, const ActionsDAG::Node * output, result != nullptr).

ErrorCodes::LOGICAL_ERROR, "Cannot find sharding key column {} in expression {}",
sharding_key_column_name, sharding_key_dag.dumpDAG());
/// Sharding key column can't be resolved in the analyzed expression (e.g. a const-folded key like
/// `if(2, toInt32(id), t0)`). Skip the optimization and query all shards instead of asserting.

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.

queryng all shards isn't an unexpected behavior change?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No previously-working pruning regresses. This branch is reached only when the sharding key cannot be resolved in the analyzed DAG, which is exactly the case that previously threw LOGICAL_ERROR ("Cannot find sharding key column") -> those queries never pruned, they failed (server abort in debug/sanitizer builds, handled exception in release). Returning nullptr is this function's existing "can't decide, use the full cluster" signal, identical to the !filter_actions_dag and !variants paths just above, so results stay correct, only unpruned.

It is also still gated downstream: with force_optimize_skip_unused_shards set, getOptimizedCluster raises the clean UNABLE_TO_SKIP_UNUSED_SHARDS ("Sharding key is not used") user error instead of silently querying all shards.

And in practice the fallback should not fire: the constructor now resolves sharding_key_column_name to the actual DAG output name, so tryFindInOutputs succeeds here. The nullptr path is defense-in-depth for a genuinely unresolvable (ambiguous multi-output) key.

…ardingKeyOutput

Readability-only follow-up to Ergus's review. No behavior change:
- Use explicit (== nullptr) / (!= nullptr) comparisons instead of
  implicit pointer truthiness at both consumer sites and in the helper.
- Spell out the pointer/container types instead of auto for these
  simple types (ActionsDAG::Node *, ActionsDAG::NodeRawConstPtrs &,
  ActionsDAG &).
- Build source_columns with the iterator-range NameSet constructor.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 49630ae

Every failure below has an owner: a fixing PR (ours 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
CH Inc sync private fork-sync mirror CH Inc sync (private, not actionable by us)

All real CI is green: 155 pass / 18 skipping, Finish Workflow = pass, Mergeable Check = pass, zero test-level FAIL/ERROR on this head. The only red check is CH Inc sync (the sole no-owner-exempt check). This is a focused source fix to StorageDistributed.cpp (const-folded sharding key in skipUnusedShards) plus the readability refinements requested in review.

Session id: cron:our-pr-ci-monitor:20260629-150000

@alexey-milovidov
alexey-milovidov merged commit 799ffff into ClickHouse:master Jun 29, 2026
173 of 174 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 Jun 29, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…arding-key-const-fold

Fix logical error on const-folded sharding key in skipUnusedShards
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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants