Skip to content

Support JOIN queries with AutoPR - #106073

Merged
nickitat merged 49 commits into
masterfrom
autopr_support_join
Aug 5, 2026
Merged

nickitat merged 49 commits into
masterfrom
autopr_support_join

Conversation

@nickitat

@nickitat nickitat commented May 28, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

JOIN queries are supported with automatic parallel replicas.

Version info

  • Merged into: 26.8.1.870 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cd52f0e]

Summary: ✅


AI Review

Summary

This PR extends AutoPR to JOIN queries by teaching the optimizer to collect/reuse join dataflow statistics and by making the plan hash stable in the presence of join runtime filters and join_any_take_last_row. The remaining issue is that AutoPR can now reuse statistics from runtime-filtered local joins even though the shipped parallel-replicas fragment still executes without those runtime filters, so the cost model can be comparing different plans.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp:296] AutoPR now admits plans containing BuildRuntimeFilterStep, but remote parallel-replica fragments still deserialize that step with an empty filter_key, so the build side publishes nothing and __applyFilter becomes pass-all on the replica. The cached input_bytes / output_bytes are therefore collected under local runtime filtering and possible runtime-filter index pruning, while the applied parallel-replicas plan runs without either. A selective runtime filter can make AutoPR enable parallel replicas on a query that will actually ship much more data remotely.
    Suggested fix: fail closed for AutoPR when the matched subtree contains runtime filters, or rematerialize runtime filters inside the remote fragment before reusing the statistics.
Final Verdict

Changes requested: AutoPR is currently allowed to compare a runtime-filtered local join against an unfiltered replica plan.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 139/151 (92.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 28, 2026
@nickitat
nickitat force-pushed the autopr_support_join branch from a97d99a to c7c1acc Compare May 29, 2026 19:34
@clickhouse-gh

clickhouse-gh Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

@ClickHouse/integrations team, please, take a look

@nickitat
nickitat force-pushed the autopr_support_join branch from c7c1acc to 7d3c56a Compare May 29, 2026 19:41
@nickitat
nickitat force-pushed the autopr_support_join branch 2 times, most recently from c494fab to 88d23e0 Compare May 29, 2026 21:53
@nickitat
nickitat force-pushed the autopr_support_join branch from 6e49c4e to 74b3443 Compare June 1, 2026 14:02
@nickitat
nickitat force-pushed the autopr_support_join branch 2 times, most recently from f6e703c to 21d5253 Compare June 2, 2026 09:24
Comment thread src/DataTypes/DataTypesBinaryEncoding.h Resolved
@nickitat
nickitat force-pushed the autopr_support_join branch from d270b3e to 1b3a43c Compare June 2, 2026 22:10
@alexey-milovidov

Copy link
Copy Markdown
Member

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged.

Please update your branch to pick up the revert; the tests should pass again.

@nickitat nickitat changed the title [WIP] Support JOIN queries with AutoPR Support JOIN queries with AutoPR Jun 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=5 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b82a5a44-25d5-43ef-80a6-a2e91386803c
  • MIRAI run: 5c8a1ab5-a65e-4a5b-be70-afc9f617fe1c
  • PR check IDs:
    • clickbench_383295_1780575977
    • clickbench_383304_1780575977
    • tpch_adapted_1_official_383306_1780575977
    • tpch_adapted_1_official_383316_1780575977
    • tpch_adapted_1_official_383322_1780575977

Comment thread src/Processors/QueryPlan/JoinStep.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 138/150 (92.00%) · Uncovered code

Full report · Diff report

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.

Pull request overview

This PR extends AutoPR (automatic parallel replicas) support to JOIN queries by enabling dataflow statistics collection around joins, refining the statistics cache-key hashing to include JOIN-specific semantics (and avoid unstable hash components), and adding regression/statistical validation tests.

Changes:

  • Enable runtime dataflow statistics collection for JoinStep, and make AutoPR’s “find reading step / transplant index analysis” logic JOIN-aware.
  • Strengthen AutoPR statistics cache keys for JOIN plans (child-slot–aware hashing, join semantics, output header types, and join_any_take_last_row), and avoid hash instability from join runtime-filter id values.
  • Add stateless tests covering JOIN AutoPR apply behavior, input/output byte estimation, and cache-key separation.

Reviewed changes

Copilot reviewed 25 out of 27 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/queries/0_stateless/04655_autopr_join_any_take_last_row_cache_key.sql Validates that join_any_take_last_row changes the AutoPR stats cache key (no cross-mode cache reuse).
tests/queries/0_stateless/04655_autopr_join_any_take_last_row_cache_key.reference Expected output for 04655.
tests/queries/0_stateless/04342_autopr_join_apply_distinct_preanalyzed.sql Regression test for APPLY path when JOIN-side reads may already be analyzed (DISTINCT/subquery shape).
tests/queries/0_stateless/04342_autopr_join_apply_distinct_preanalyzed.reference Expected output for 04342.
tests/queries/0_stateless/04341_autopr_mode1_apply_join.sql End-to-end AutoPR APPLY path tests for INNER/LEFT/RIGHT joins, including correctness and ParallelReplicasUsedCount.
tests/queries/0_stateless/04341_autopr_mode1_apply_join.reference Expected output for 04341.
tests/queries/0_stateless/04340_autopr_input_bytes_estimation_join.sql Validates RuntimeDataflowStatisticsInputBytes instrumentation targets the parallelized JOIN side.
tests/queries/0_stateless/04340_autopr_input_bytes_estimation_join.reference Empty reference (test prints only on failure).
tests/queries/0_stateless/04305_autopr_output_bytes_estimation_join.sql Validates RuntimeDataflowStatisticsOutputBytes for JOIN output against stable baselines.
tests/queries/0_stateless/04305_autopr_output_bytes_estimation_join.reference Empty reference (test prints only on failure).
src/Processors/QueryPlan/Serialization.h Replaces ad-hoc skip flags with a unified for_cache_key mode for cache-key hashing serialization.
src/Processors/QueryPlan/Optimizations/joinRuntimeFilter.cpp Marks runtime-filter id const column so hashing can ignore its volatile value.
src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp Adds JOIN-aware descent in findReadingStep and avoids overwriting existing read analysis; broadens “simple enough” check.
src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp Makes cache-key hashing aware of JOIN semantics and output layout; improves handling of row-preserving transforms.
src/Processors/QueryPlan/JoinStep.h Declares JOIN as supporting dataflow statistics collection.
src/Processors/QueryPlan/JoinStep.cpp Inserts RuntimeDataflowStatisticsCollector into JOIN pipeline when enabled.
src/Processors/QueryPlan/AggregatingStep.cpp Uses for_cache_key to omit final and stats-collection cache key from cache-key hashing.
src/Interpreters/SpillingHashJoin.h Exposes anyTakeLastRow via IJoin for this join implementation.
src/Interpreters/SetSerialization.h Adds SerializedSetsRegistry::for_cache_key to control cache-key hashing serialization behavior.
src/Interpreters/JoinSwitcher.h Propagates anyTakeLastRow through JoinSwitcher.
src/Interpreters/IJoin.h Introduces IJoin::anyTakeLastRow to surface join_any_take_last_row from concrete join algorithms.
src/Interpreters/HashJoin/HashJoin.h Overrides anyTakeLastRow in HashJoin.
src/Interpreters/GraceHashJoin.h Exposes anyTakeLastRow via IJoin for this join implementation.
src/Interpreters/ConstantJoin.h Exposes anyTakeLastRow via IJoin for this join implementation.
src/Interpreters/ConcurrentHashJoin.h Exposes anyTakeLastRow via IJoin for this join implementation.
src/Interpreters/ActionsDAG.h Adds is_runtime_filter_id marker and extends addColumn signature to carry it.
src/Interpreters/ActionsDAG.cpp Skips hashing/serialization of runtime-filter id const VALUE for cache keys, while keeping stable identity via name.

@nickitat
nickitat added this pull request to the merge queue Aug 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 5, 2026
nickitat and others added 4 commits August 5, 2026 13:41
… limit

`04342_autopr_join_apply_distinct_preanalyzed` and
`04655_autopr_join_any_take_last_row_cache_key` exceeded the 180s per-test limit
of the merge-queue flaky check, which runs each new test 20 times in parallel.

The tests are not slow by themselves: the CI query log shows one `04342` run
spending 3.6s of `UserTimeMicroseconds` across 167.9s of wall time, with 32.3s
of `OSCPUWaitMicroseconds`. They simply carry enough work to tip over the limit
once the runner is saturated - the same job was concurrently loading `test.hits`
into `test.hits_s3`.

Shrink both by 4x. The AutoPR apply condition reduces to `input > 2 * output`,
which is scale-invariant, so the smaller tables still take the apply path. The
key overlap of `aj_small` with `aj_big` and the two-duplicates-per-key ratio
that `join_any_take_last_row` needs to pick a different row are both preserved,
so the references are unchanged. Rows read per run drop from 3000002 to 750002
for `04342` and from 700000 to 175000 for `04655`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-106073-25cffb2f32f6cbbf648ff5e569c2819419a2d63a&sha=023112869f4fb8b64037db81c4615e52776a5fb1&name_0=MergeQueueCI
Related: #106073

Co-Authored-By: Claude Opus 5 <[email protected]>
Follow-up to the previous commit, which shrank
`04342_autopr_join_apply_distinct_preanalyzed` and
`04655_autopr_join_any_take_last_row_cache_key` after they exceeded the 180s
per-test limit of the merge-queue flaky check. Attributing the same CI run per
test shows two more worth trimming:

    test                                       runs   p50    max   % of 180s
    04341_autopr_mode1_apply_join                 2   206s   211s        117
    04305_autopr_output_bytes_estimation_join    20    39s    92s         51

`04341` exceeded the limit on every run and stays green only because it is
tagged `long`, which skips the check (`get_runs` also gives it 2 runs instead of
20, which is why it has so few). `04305` sits at half the budget, which is where
the two tests that did fail sat before a saturated runner pushed them over.

Shrink both by 4x. `04341` uses the same tables as `04342` and asserts only
`result_ok` / `pr_used`, so the scale-invariant `input > 2 * output` argument
carries over unchanged. `04305` compares the collected output-byte estimate
against fixed baselines, so those are re-derived for the smaller tables. The
estimate is no noisier at 250K rows than at 1M: over 28 runs with randomized
settings the worst deviation from the new baselines is 1.003x, against the
test's 2x tolerance.

Rows read per run drop from 8000009 to 2000009 for `04341` and from 5600000 to
1400000 for `04305`, with CPU following at 4.2x and 3.8x.

The `long` tag on `04341` is left in place; it can be dropped separately now
that the test no longer needs the exemption, which would also return it to the
fast test and give it the full 20 flaky-check runs.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-106073-25cffb2f32f6cbbf648ff5e569c2819419a2d63a&sha=023112869f4fb8b64037db81c4615e52776a5fb1&name_0=MergeQueueCI
Related: #106073

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit shrank this test by 4x alongside `04341_autopr_mode1_apply_join`
and re-derived its hardcoded output-byte baselines. Restore it to its original
1M/200K tables and baselines; keep the `04341` shrink.

Unlike the other AutoPR join tests, `04305` was not failing: it ran 20/20 in the
merge-queue flaky check at p50 39s and max 92s, i.e. half the 180s limit. The
change was pre-emptive, and it is the only one of the four that trades a fixed
assertion (sampled output bytes against constants) for a time saving, so leaving
it alone keeps the baselines tied to the data they were originally measured on.

Verified restored: 10/10 runs under `--flaky-check`.

Related: #106073

Co-Authored-By: Claude Opus 5 <[email protected]>
The tag was needed when the test read 8000009 rows per run and took 206s in the
merge-queue flaky check. After the 4x shrink it no longer is, and the tag has
two costs: `--no-long` excludes the test from the fast test, and `get_runs`
gives `long` tests a reduced repeat count, so it got 2 flaky-check runs where
its siblings got 20.

Verified with the tag removed: 20/20 runs under `--flaky-check --test-runs 20`,
and the test now executes under `--no-long` in 0.70s, comfortably inside the
60s per-test timeout the fast test runs with.

Note this raises the test's total share of the flaky check, since 20 runs of a
4x cheaper test is more work than 2 runs of the original. Summed over the five
tests this pull request adds, the job's query time still comes out roughly a
third lower than the run that failed.

Related: #106073

Co-Authored-By: Claude Opus 5 <[email protected]>
[&](auto & frame_node)
{
const bool step_is_supported = frame_node.step->supportsDataflowStatisticsCollection()
|| typeid_cast<const BuildRuntimeFilterStep *>(frame_node.step.get())

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.

This makes AutoPR admit plans that contain a BuildRuntimeFilterStep, but the shipped parallel-replicas fragment still cannot execute that runtime filter after serialization. BuildRuntimeFilterStep::deserialize always drops filter_key, BuildRuntimeFilterStep::transformPipeline then returns immediately on the empty key, and __applyFilter passes all rows when the lookup misses.

That means the input_bytes / output_bytes we cache here are collected on the runtime-filtered single-node plan, while the applied parallel-replicas fragment runs without the filter or its runtime-filter index pruning. A selective runtime filter can therefore make AutoPR look profitable and then ship much more data on the applied query. Please fail closed for AutoPR when the matched subtree contains runtime filters, or rematerialize the runtime filter inside the remote fragment before reusing these statistics.

@nickitat
nickitat added this pull request to the merge queue Aug 5, 2026
Merged via the queue into master with commit 1a969f3 Aug 5, 2026
180 checks passed
@nickitat
nickitat deleted the autopr_support_join branch August 5, 2026 23:00
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
alexey-milovidov added a commit that referenced this pull request Aug 6, 2026
Re-merge after #106073 "Support JOIN queries with AutoPR" landed on master,
which addresses the JOIN-with-parallel-replicas red classes surfaced by this
canary. Diff vs master remains exactly the single randomizer line.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The AutoPR apply path transplants the single-node index analysis onto the
parallel-replicas branch read (to honor parallel_replicas_index_analysis_only_on_coordinator)
under chassert(getAnalyzedResult() == nullptr). That held when a table sat on top of
the plan, but the new JoinStep descent in findReadingStep lets the apply path reach a
branch read that the join (or a scalar subquery in the query) already analyzed - so a
supported AutoPR JOIN could hit the chassert in debug, and in release silently overwrite
a pre-existing analysis result.

Handle it explicitly: if the branch read is already analyzed for the same parallelized
table (pointer identity on the underlying MergeTreeData, since both plans reference the
same storage object), keep its own equivalent result instead of overwriting; if it is
analyzed for a different table, the read we found is not the one we estimated against, so
skip the optimization rather than apply a mismatched analysis.

Reproduced by the AST fuzzer on a LEFT JOIN apply query with a scalar subquery; the
existing 04341 mode=1 apply test exercises exactly this shape.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106073&sha=c691b4191826494e69ec29ab93dc3279da6aaa0f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: ClickHouse#106073
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rror

The AST fuzzer, mutating 04341, hit
  Logical error: 'local_replica_plan_reading_step->getAnalyzedResult() == nullptr'
on a top-level SELECT DISTINCT over a LEFT JOIN with a scalar subquery in the AutoPR
apply path: the DISTINCT/subquery leaves the parallel-replicas branch read already
analyzed, which the apply path assumed could not happen for the table-on-top case.

This is the reduced reproducer (the fuzzer crash itself proves the branch read is
non-null at that point, i.e. it exercises the reuse branch added in the fix). The
collect run reaches no-stats, the apply run reaches the buffered apply formula and
swaps in the parallel-replicas plan; both must return result_ok = 1 and the apply
run must have used parallel replicas. Verified 30/30 (no-random + randomized).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106073&sha=c691b4191826494e69ec29ab93dc3279da6aaa0f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: ClickHouse#106073
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

5 participants