Repository navigation
Fix logical error on const-folded sharding key in skipUnusedShards - #108737
alexey-milovidov merged 2 commits into
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260628-100300 |
|
cc @azat @devcrafter — could you review? A const-folded sharding key (e.g. |
|
Workflow [PR], commit [49630ae] Summary: ✅
AI ReviewSummaryThis PR fixes Final VerdictStatus: ✅ Approve |
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]>
afecc7b to
f713d8a
Compare
|
Updated pre-PR validation gate for the refined fix (source-column-fold case from the review). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-4:20260628-205000 |
Ergus
left a comment
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
Explicit (sharding_key_output == nullptr) is cleared to read. Also if possible avoid the "auto" for simple types like this
There was a problem hiding this comment.
Done in 49630ae: const ActionsDAG::Node * sharding_key_output = tryFindShardingKeyOutput(...); then if (sharding_key_output == nullptr).
| 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) |
There was a problem hiding this comment.
Done in 49630ae: if (expr_node == nullptr), and spelled out the types (const ActionsDAG &, const ActionsDAG::Node *).
|
|
||
| /// 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; |
There was a problem hiding this comment.
const Names &names = sharding_key_dag.getRequiredColumnsNames();
const NameSet source_columns(names.begin(), names.end());
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
queryng all shards isn't an unexpected behavior change?
There was a problem hiding this comment.
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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 30/33 (90.91%) | Lost baseline coverage: none · Uncovered code |
CI finish ledger — 49630aeEvery 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
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 Session id: cron:our-pr-ci-monitor:20260629-150000 |
…arding-key-const-fold Fix logical error on const-folded sharding key in skipUnusedShards
No related open issue found (searched "Cannot find sharding key column", "skipUnusedShardsWithAnalyzer", "sharding key column expression").
Changelog category (leave one):
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 aDistributedtable's sharding key is an expression the analyzer const-folds, for exampleif(1, toInt32(id), toInt32(id) + 1), withoptimize_skip_unused_shards = 1.Description
The sharding key column name is captured from the unanalyzed sharding key AST in the
StorageDistributedconstructor. Building the sharding key expression analyzes (and may rewrite) it: the analyzer const-folds an expression likeif(1, toInt32(id), toInt32(id) + 1)(or the fuzzer'sif(2 AS a, toInt32(id), t0)) down totoInt32(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:skipUnusedShardsWithAnalyzerthrewLOGICAL_ERROR: Cannot find sharding key column ...(aborts the server in debug/sanitizer builds, handled exception in release);isShardingKeySuitsQueryTreeNodeExpression(theGROUP BYsharding-key pushdown path) threwUNKNOWN_IDENTIFIER;INrewrite (OptimizeShardingKeyRewriteIn) andDistributedSink::createSelectorthrewNOT_FOUND_COLUMN_IN_BLOCK.Fix: resolve
sharding_key_column_nameto the actual expression output name once at construction. The expression is built withproject = 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 asif(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,skipUnusedShardsWithAnalyzerandisShardingKeySuitsQueryTreeNodeExpressionnow 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):
After the fix the query returns the same result as the equivalent plain
toInt32(id)sharding key. A regression case is added to01930_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
26.7.1.255(included in26.7and later)