Skip to content

Remove columns left unused by join runtime filters, and stop AutoPR keys ignoring computed expressions - #127882

Open
devcrafter wants to merge 4 commits into
plan-based-pr-merge-pre-join-actionsfrom
plan-based-pr-prune-after-runtime-filters
Open

devcrafter wants to merge 4 commits into
plan-based-pr-merge-pre-join-actionsfrom
plan-based-pr-prune-after-runtime-filters

Conversation

@devcrafter

@devcrafter devcrafter commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #127845, which it includes until that is merged.

With parallel_replicas_plan_based, automatic parallel replicas still could not match the plans of a join whose right key is an expression, e.g. t1.key = t2.key + t2.m, when it gets a join runtime filter. Building the filter computes the key below the join, so key and m become unused. The local plan of plan-based parallel replicas is optimized again from the first pass and removes them; the single-node plan never removes unused columns after adding the filters, so its join kept both and carried them into its hash table. The second pass now removes unused columns again when runtime filters were added.

That exposed a collision in the statistics cache key: the expression below the filter now turns key into key + m, one UInt64 into another, and calculateHashFromStep treated any step keeping the byte layout as transparent, so key + 1 and key + 2 shared a key (05292_autopr_stats_key_constants caught it). An ExpressionStep now stays transparent only when it forwards or reorders its inputs; one that computes values is hashed from its serialized form.

05292_autopr_stats_key_constants now passes with parallel_replicas_plan_based=1 (it failed in #112351). The new test 05453_pr_plan_based_autopr_join_key_expression_runtime_filter fails without the change. Locally, the 161 autopr and runtime filter tests and the 638 tests with both a join and EXPLAIN show no plan or reference changes (failures left were environment-only).

Related: #127845
Related: #112351

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code


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

…puting expressions in AutoPR keys

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c59481]

Summary: ✅


AI Review

Summary

This PR removes columns left unused after join runtime filters compute their keys and distinguishes computed expressions in automatic parallel-replica statistics keys. Request changes: the existing alias-placement regression remains in PR head 2c594810e9d087f7ce5327aa2cea91010cba9303, preventing automatic parallel replicas for supported computed projections.

Findings

⚠️ Majors

  • src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp:189 — Equivalent computations must keep the same key when aliases are merged. The new condition sends type-preserving computations through ExpressionStep::serialize. ActionsDAG::serialize includes node counts, action types, and output node IDs, including ALIAS nodes, even with for_cache_key. A computation with a merged rename therefore hashes differently from the same computation followed by a transparent rename.

    For example, SELECT repeat(a, 100) AS a, b FROM s over a populated MergeTree table with two String columns stops matching under query-based automatic parallel replicas with parallel_replicas_local_plan=1 and query_plan_merge_expressions=1: the single-node plan merges the rename into the computing expression, while the replicas plan retains a separate rename. considerEnablingParallelReplicas then increments AutoParallelReplicasPlansNotComparable and returns before statistics collection or replica selection. The prior reviewer reproduced this regression against the base; the current serialization and matching code still retain its cause.

    Hash computed outputs independently of alias nodes while retaining input identity, types, and fixed-size constants. This is the existing unresolved finding; no duplicate inline comment was posted.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build is available, so this run verified the regression through current source and the prior reviewer's reproduction. Running the projection reproduction on this exact head would provide fresh execution evidence.
Tests
  • ⚠️ Add a focused computed-projection regression with parallel_replicas_plan_based=0 and query_plan_merge_expressions=1, asserting comparable plans and collected output-byte statistics. 05136_autopr_projection_is_not_peeled disables expression merging; the new join test passes in current CI but does not exercise this projection shape.
Final Verdict

⚠️ Request changes. Make computed-expression keys invariant under alias merging and add the focused regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 26, 2026
@devcrafter
devcrafter changed the base branch from master to plan-based-pr-merge-pre-join-actions October 26, 2026 21:08
@devcrafter
devcrafter added this pull request to stack #127883 October 26, 2026 21:08
@devcrafter
devcrafter requested review from groeneai and nickitat and a balanced review from Copilot October 26, 2026 21:09

Copilot AI left a comment

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.

🟢 Approval recommended

The focused changes reuse existing pruning and serialization mechanisms, have regression coverage, and leave no identified blocking issues.

No open issues 🎉

What changed in this PR

This PR aligns automatic parallel-replica plan matching for joins with computed keys and runtime filters, building on #127845. It also prevents computed expressions from sharing statistics cache keys merely because their output byte layouts match.

Changes:

  • Remove unused columns after adding join runtime filters.
  • Hash computed ExpressionStep values using serialization while preserving existing forwarding and permutation handling.
  • Add regression coverage for plan matching and statistics collection in query-based and plan-based modes.
File Description
tests/​queries/​0_stateless/​05453_pr_plan_based_autopr_join_key_expression_runtime_filter.sql Tests computed join keys with runtime filters in both parallel-replica modes.
tests/​queries/​0_stateless/​05453_pr_plan_based_autopr_join_key_expression_runtime_filter.reference Expects comparable plans and collected output-byte statistics.
src/​Processors/​QueryPlan/​Optimizations/​optimizeTree.cpp Prunes unused columns after runtime filters are added.
src/​Processors/​QueryPlan/​Optimizations/​calculateHashTableCacheKeys.cpp Distinguishes computed expressions in statistics cache keys.

Review effort: Balanced

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I reviewed the delta over #127845 on 92476fd with two debug builds (this head, and #127845's head cb89393) and a local parallel_replicas cluster.

Change 1 (removeUnusedColumns after the runtime filters) looks right to me:

  • 05453 passes here and fails on the base (05453_plan_based 1 0).
  • In the single-node plan the right join input goes from plus(key, m), key, m to plus(key, m).
  • 18 single-node result probes, mostly with an expression right key (INNER/LEFT/RIGHT/SEMI/ANY, USING, join_use_nulls = 1, a mixed ON condition, query_plan_merge_expressions = 0, a right-side column used in ORDER BY/GROUP BY above the join, lazy materialization, read in order, parallel_hash, chained joins) return the same results on both builds.
  • Of the 156 stateless tests with runtime_filter / autopr / hash_table_stats in the name, only 05453 changes output (24 fail on both builds here for environment reasons, with identical output).

Change 2 makes query-based automatic parallel replicas stop matching a projection that computes a same-type column:

CREATE TABLE s (a String, b String) ENGINE = MergeTree ORDER BY b;
INSERT INTO s SELECT toString(number), toString(number) FROM numbers(1e6);
SELECT repeat(a, 100) AS a, b FROM s FORMAT Null SETTINGS enable_parallel_replicas = 1, automatic_parallel_replicas_mode = 2,
    parallel_replicas_local_plan = 1, parallel_replicas_for_non_replicated_merge_tree = 1, max_parallel_replicas = 3,
    cluster_for_parallel_replicas = 'parallel_replicas', automatic_parallel_replicas_min_bytes_per_replica = 0, max_threads = 4;

AutoParallelReplicasPlansNotComparable is 0 on the base and 1 here; same for a || 'z' AS a, repeat(a, 100) AS x and upper(a) AS a ... WHERE b != ''. It still matches with parallel_replicas_plan_based = 1 or query_plan_merge_expressions = 0. The single-node plan has the Project names rename merged into the projection's Expression, the replicas plan keeps Expression + Expression (Project names), so the serialized forms differ; on the base both steps contributed nothing to the key. A layout-changing projection (cityHash64(a) AS h) already fails to match this way on the base.

Overlap with my #126148 (#125826): it changes the same branch of calculateHashFromStep for the same collision, but hashes a computing step with ActionsDAG::getComputedOutputsHash, which looks through ALIAS nodes, so a merged and an unmerged rename get the same key. Measured:

  • This head on #126148's 05401: the numeric cases pass; the string-literal ones (trimBoth(s, '0123456789') vs 'x', formatDateTime(d, '%Y') vs '%F %T') still share an entry, since variable-size constant values stay out of the key; q05401_autopr_projection (the case above) fails.
  • Change 1 plus #126148's hashing instead of change 2: 05453, 05292 (with and without parallel_replicas_plan_based = 1), 05291 and 05401 pass, the projection probes match, and the same 156-test sweep differs from the base only in 05453.
  • The two PRs merge without a textual conflict, but the result is wrong: git attaches #126148's else to if (!is_identity) in the restructured block, so whichever lands second needs a manual rebase.

I can rebase #126148 onto this PR or close it, whichever you prefer.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 26, 2026
…ions' into plan-based-pr-prune-after-runtime-filters
/// different keys to match. It gets a key from its serialized form below.
const auto * expression = typeid_cast<const ExpressionStep *>(&transform);
const auto permutation = expression ? pureColumnPermutation(expression->getExpression()) : std::nullopt;
if (isByteTransparentTransform(transform) && (!expression || permutation))

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.

⚠️ Major: Keep computed-expression keys stable when aliases are merged

This sends a type-preserving computing ExpressionStep through DAG serialization, but that representation changes when Project names is merged into the expression. ActionsDAG::serialize writes the node count, action types and output node IDs, including ALIAS nodes, even with for_cache_key. Consequently, a merged expression and the same computation followed by a transparent rename get different keys.

For example, with a populated MergeTree table s(a String, b String) and the configured parallel_replicas cluster:

SELECT repeat(a, 100) AS a, b FROM s FORMAT Null
SETTINGS enable_parallel_replicas=1, automatic_parallel_replicas_mode=2,
    parallel_replicas_local_plan=1, parallel_replicas_for_non_replicated_merge_tree=1,
    max_parallel_replicas=3, cluster_for_parallel_replicas='parallel_replicas',
    automatic_parallel_replicas_min_bytes_per_replica=0, max_threads=4,
    parallel_replicas_plan_based=0, query_plan_merge_expressions=1;

The single-node plan absorbs the rename while the replicas computation remains separate. Their boundary hashes no longer match, so considerEnablingParallelReplicas increments AutoParallelReplicasPlansNotComparable and returns before collecting statistics or choosing parallel replicas. The prior reviewer reproduced this regression against the base; the current hashing and serialization paths still have the same behavior. Existing test 05136_autopr_projection_is_not_peeled explicitly disables expression merging and misses it.

Hash computed outputs in a way that looks through aliases while preserving input identity, types and constants, and add a focused regression with expression merging enabled. The overlapping implementation in the related PR addresses this distinction.

Related: #126148

@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2c594810e with master 509fb3681 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

155 translation units recompiled, 1483 s compile time in total, 155 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 19, 2026

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

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants