Skip to content

PR: use serialized query plan - part 2 - #97261

Closed
devcrafter wants to merge 67 commits into
masterfrom
pr-serialize-query-plan-part2
Closed

devcrafter wants to merge 67 commits into
masterfrom
pr-serialize-query-plan-part2

Conversation

@devcrafter

@devcrafter devcrafter commented Feb 18, 2026 •

Copy link
Copy Markdown
Member

Continuation of #88696

#100226 should be merged first

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@clickhouse-gh

clickhouse-gh Bot commented Feb 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d678744]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
04099_source_step_with_filter_rp FAIL cidb
Stateless tests (amd_binary, distributed plan, ParallelReplicas, s3 storage, parallel) FAIL
03151_analyzer_view_read_only_necessary_columns FAIL cidb
03277_json_subcolumns_in_primary_key FAIL cidb
04065_count_exact_ranges_max_rows_to_read FAIL cidb
03166_skip_indexes_vertical_merge_1 FAIL cidb
03143_prewhere_profile_events FAIL cidb
01655_plan_optimizations_optimize_read_in_window_order_long FAIL cidb
03262_filter_push_down_view FAIL cidb
03800_projection_row_policy_filter_column FAIL cidb
03045_unknown_identifier_alias_substitution FAIL cidb
01763_filter_push_down_bugs FAIL cidb
66 more test cases not shown
Stateless tests (amd_binary, distributed plan, ParallelReplicas, s3 storage, sequential) FAIL
02910_prefetch_unexpceted_exception FAIL cidb
01913_exact_rows_before_limit FAIL cidb
01625_constraints_index_append FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
04099_source_step_with_filter_rp FAIL cidb

AI Review

Summary

This PR continues the serialized-query-plan rollout for parallel replicas by transporting logical ReadFromTableSteps, carrying row-policy filters through them, and extending CI coverage. The branch still has multiple correctness gaps: it changes the ReadFromTableStep wire layout without a serialization-version split, can still build non-serializable direct-join plans for the serialized remote path, and still marks only the first logical read for parallel replicas, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromTableStep.cpp:37, src/Core/ProtocolDefines.h:96] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/97261#discussion_r2925894257] ReadFromTableStep changed the version-9 wire layout in place: bit 8 now means is_merge_tree, bit 16 now means use_parallel_replicas, and bit 32 appends a row_policy_filter payload, but DBMS_QUERY_PLAN_SERIALIZATION_VERSION was not bumped. RemoteQueryExecutor only excludes replicas below version 9, so a rolling upgrade between two version-9 builds can still send the new layout to an older reader, which will interpret the flags using the old contract and leave the stream misaligned. Suggested fix: bump the query-plan serialization version and keep backward parsing/writing for the previous ReadFromTableStep layout.

  • [src/Planner/PlannerJoinTree.cpp:3045, src/Processors/QueryPlan/JoinStepLogical.h:243, src/Processors/QueryPlan/IQueryPlanStep.h:82] Allowing ReadFromTableStep into tryMakeDirectJoinWithMergeTree still lets the serialized remote-plan path build JoinStepLogicalLookup, but that step does not implement serialize and remains non-serializable by default. createRemotePlanForParallelReplicas immediately calls ensureSerialized, so join_algorithm = direct queries can still fail during planning with NOT_IMPLEMENTED instead of shipping the remote plan. Suggested fix: either suppress the direct-join rewrite while the plan is being serialized, or implement serialization for JoinStepLogicalLookup together with a focused regression test.

  • [src/Processors/QueryPlan/ParallelReplicasLocalPlan.cpp:182] The remote logical plan still marks only the first ReadFromTableStep as useParallelReplicas. Queries whose shipped fragment contains several logical reads, for example a view expanded into UNION ALL, will split only one branch while the others read fully on every replica, which can duplicate rows and make the local and remote halves use different read modes. Suggested fix: mirror the local-plan traversal here and set the flag on every eligible logical read.

⚠️ Majors

  • [src/Processors/QueryPlan/ReadFromTableStep.cpp:99] clone() reuses the same row_policy_filter pointer between plan copies. The new logical direct-join path clones a plan while it still contains ReadFromTableStep (lookup_plan = right_query_plan.clone()), so the lookup plan and the main right-side plan share one mutable FilterDAGInfo. ReadFromMergeTree::clone() already deep-copies row-level filters because optimizations mutate them; keeping the shared pointer here lets those mutations bleed across plan copies or race. Suggested fix: deep-copy row_policy_filter in ReadFromTableStep::clone() the same way ReadFromMergeTree::clone() copies query_info.row_level_filter.

  • [src/Planner/PlannerJoinTree.cpp:2415] is_merge_tree is still assigned only in the non-temporary branch, so every temporary table is serialized as "not MergeTree". Temporary MergeTree tables therefore miss the same direct-join / MergeTree behavior this PR is enabling for permanent tables, and planning diverges solely because the table is temporary. Suggested fix: compute is_merge_tree from table_node->getStorage()->isMergeTree() regardless of getTemporaryTableName().

Tests

⚠️ [tests/queries/0_stateless/04049_pr_row_policy_and_trivial_count.sql:5, src/Interpreters/ClusterProxy/executeQuery.cpp:1091, src/Interpreters/ClusterProxy/executeQuery.cpp:1153] This regression test still does not cover the serialized remote-plan transport it is meant to validate. With parallel_replicas_local_plan = 0, executeQueryWithParallelReplicas takes the remote-only branch where remote_query_plan is never built, so the query still ships the formatted AST instead of a serialized ReadFromTableStep. Please add a case that goes through the branch with a non-null remote_query_plan, or enable serialized-plan transport in the remote-only branch before relying on this as coverage.

Final Verdict

Changes requested. The serialized-plan rollout still has blocking wire-format and remote-plan correctness issues, and the new ReadFromTableStep clone semantics add another mutable-state hazard on top of that.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 80/91 (87.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Feb 18, 2026
@devcrafter
devcrafter force-pushed the pr-serialize-query-plan-part2 branch from ef195af to 93a8b89 Compare February 26, 2026 17:14
devcrafter and others added 2 commits May 19, 2026 15:08
The new `distributed plan, ParallelReplicas` job has the random-settings
generator pick `parallel_replicas_local_plan` from {0, 1}. Picking 0
takes the path that builds the remote plan first and trips not-yet-
implemented execution on the initiator. Force it to 1 in
`adjust_settings_for_autopr` whenever both `--distributed-plan` and
`--no-parallel-replicas` are set on the test runner.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…plan-part2

# Conflicts:
#	.github/workflows/pull_request.yml
devcrafter and others added 3 commits June 10, 2026 22:51
`Config Workflow` check on CI flagged 5 YAMLs as outdated vs what
`python3 -m praktika yaml` produces. Bring them in sync; only
`pull_request.yml` actually differs from master (carries the new
`distributed plan, ParallelReplicas` jobs), the rest just catch up
master's drift.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
SET enable_analyzer = 1;
SET serialize_query_plan = 1;
SET enable_parallel_replicas = 1, max_parallel_replicas = 2, cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost', parallel_replicas_for_non_replicated_merge_tree = 1;
SET parallel_replicas_local_plan=0; -- to ensure plan serialization/deserialization will happen

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 setting does not exercise the serialized-plan path the test is meant to cover. With parallel_replicas_local_plan = 0, executeQueryWithParallelReplicas takes the remote-only branch, and that branch still constructs ReadFromParallelRemoteReplicasStep without a remote_query_plan. ReadFromParallelRemoteReplicasStep::createPipeForSingeReplica then sends the formatted AST at the original stage instead of QueryProcessingStage::QueryPlan, so the new ReadFromTableStep row_policy_filter serialization/deserialization can be broken while this test still passes. Please either run this case through the branch that passes a non-null remote_query_plan, or enable serialized-plan transport in the remote-only branch before relying on this as coverage.

|| typeid_cast<const ReadNothingStep *>(children_step)
|| typeid_cast<const ReadFromPreparedSource *>(children_step);
|| typeid_cast<const ReadFromPreparedSource *>(children_step)
|| (read_from_table_step && read_from_table_step->isMergeTree());

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.

Allowing ReadFromTableStep here makes the serialized-plan path choose JoinStepLogicalLookup for join_algorithm = direct, but JoinStepLogicalLookup does not implement serialize or isSerializable and inherits the default non-serializable behavior. createRemotePlanForParallelReplicas immediately calls ensureSerialized, so a query that previously serialized as a normal join can now fail during planning once the right side is a MergeTree represented by ReadFromTableStep.

Please either keep this direct-join optimization disabled while select_query_options.build_logical_plan or serialize_query_plan is active, or add serialization support for JoinStepLogicalLookup together with a regression test for join_algorithm = direct plus serialize_query_plan = 1.

@alexey-milovidov alexey-milovidov mentioned this pull request Jun 12, 2026
1 task done
alexey-milovidov pushed a commit to niyue/ClickHouse that referenced this pull request Jun 13, 2026
`createRemotePlanForParallelReplicas` re-ran the analyzer on the AST,
which produced a `TableNode` for a materialized CTE without its
subquery, crashing the planner with `LOGICAL_ERROR: CTE '...' does not
have query tree, but was not planned yet`. Switching to the pre-analyzed
query tree (mirroring `createLocalPlanForParallelReplicas`) preserves
the shared `MaterializedCTE` so `hasPlanOrBuilt()` short-circuits the
check.

Regression test `04227_pr_materialized_cte_set_subquery` pins
`parallel_replicas_local_plan = 1` because the remote builder otherwise
pollutes `MaterializedCTE::plan` with a serialize-only step that the
initiator later tries to execute. See TODO in the test.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97261&sha=0537180f689f5e8f09d034af910c5b6800f9d739&name_0=PR&name_1=Stateless+tests+%28amd_binary%2C+distributed+plan%2C+ParallelReplicas%2C+s3+storage%2C+parallel%29
PR: ClickHouse#97261

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…plan-part2

# Conflicts:
#	.github/workflows/pull_request.yml
#	src/Processors/QueryPlan/ParallelReplicasLocalPlan.cpp

auto new_context = Context::createCopy(context);

/// Build from the pre-analyzed query tree (not AST): re-analysis from AST loses

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.

createRemotePlanForParallelReplicas now builds the remote logical plan, but below this point it still marks only the first ReadFromTableStep as useParallelReplicas. The local-plan path uses findReadingSteps so views with UNION can parallelize every underlying MergeTree read; the serialized remote plan leaves later ReadFromTableSteps unmarked, so resolveStorages will make those branches read normally on every remote replica. With parallel_replicas_allow_view_over_mergetree = 1 that can duplicate data or make the local and remote halves use different read modes. Please use the same multi-read traversal for logical ReadFromTableSteps and set useParallelReplicas on every eligible read.

@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 81/92 (88.04%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

Three resolutions:

- `PlannerJoinTree`: keep master's refined `can_push_down_filter` condition
  (which also excludes remote storages and unsupported PREWHERE columns) while
  assigning to `table_expression_query_info.row_level_filter`, the destination
  this branch moved the filter to. Master's line still assigned to the local
  `row_level_filter`, which this branch removed.
- `ci/workflows/pull_request.py`: master renamed
  `FUNCTIONAL_TESTS_PARALLEL_BLOCKING_JOB_NAMES` to `CORE_BLOCKING_JOB_NAMES`.
  The textual merge left one stale reference on this branch's
  `functional_tests_distributed_plan_pr_jobs` block, which made the workflow
  generator fail with a `NameError`.
- Regenerate the praktika workflow YAML from the merged `ci/` sources.
QueryPlanStepPtr ReadFromTableStep::clone() const
{
return std::make_unique<ReadFromTableStep>(getOutputHeader(), table_name, table_expression_modifiers, use_parallel_replicas);
return std::make_unique<ReadFromTableStep>(

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.

row_policy_filter is a mutable FilterDAGInfo, but clone keeps reusing the same shared_ptr between plan copies. That becomes observable with the new logical direct-join path: tryMakeDirectJoinWithMergeTree now does lookup_plan = right_query_plan.clone() while the right side can still be a ReadFromTableStep, so the lookup plan and the main right-side plan end up sharing one filter DAG.

ReadFromMergeTree::clone already deep-copies query_info.row_level_filter because optimizations mutate these DAGs. Keeping the shared pointer here means those mutations can bleed across plan copies (or race if two clones are optimized/executed independently). Please deep-copy row_policy_filter in ReadFromTableStep::clone the same way ReadFromMergeTree::clone copies row-level filters.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d67874418 with master 7c48f2ee2 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.45 MiB 701.40 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +3.9 s (+4%) in total before that adjustment.

Job report

@abashkeev abashkeev added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 3, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test exercises a very specific configuration (parallel replicas +
`parallel_replicas_local_plan = 0` + `join_algorithm = direct` +
`serialize_query_plan = 1`) to assert that serialization of
`JoinStepLogicalLookup` raises `NOT_IMPLEMENTED`. Random settings in
the flaky check can change the plan so the lookup step is not reached
remotely, the query succeeds, and the test fails with "query succeeded
but server error '48' was expected".

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97261&sha=0537180f689f5e8f09d034af910c5b6800f9d739&name_0=PR&name_1=Stateless+tests+%28amd_asan_ubsan%2C+flaky+check%29
PR: ClickHouse#97261

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`createRemotePlanForParallelReplicas` re-ran the analyzer on the AST,
which produced a `TableNode` for a materialized CTE without its
subquery, crashing the planner with `LOGICAL_ERROR: CTE '...' does not
have query tree, but was not planned yet`. Switching to the pre-analyzed
query tree (mirroring `createLocalPlanForParallelReplicas`) preserves
the shared `MaterializedCTE` so `hasPlanOrBuilt()` short-circuits the
check.

Regression test `04227_pr_materialized_cte_set_subquery` pins
`parallel_replicas_local_plan = 1` because the remote builder otherwise
pollutes `MaterializedCTE::plan` with a serialize-only step that the
initiator later tries to execute. See TODO in the test.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97261&sha=0537180f689f5e8f09d034af910c5b6800f9d739&name_0=PR&name_1=Stateless+tests+%28amd_binary%2C+distributed+plan%2C+ParallelReplicas%2C+s3+storage%2C+parallel%29
PR: ClickHouse#97261

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test exercises a very specific configuration (parallel replicas +
`parallel_replicas_local_plan = 0` + `join_algorithm = direct` +
`serialize_query_plan = 1`) to assert that serialization of
`JoinStepLogicalLookup` raises `NOT_IMPLEMENTED`. Random settings in
the flaky check can change the plan so the lookup step is not reached
remotely, the query succeeds, and the test fails with "query succeeded
but server error '48' was expected".

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97261&sha=0537180f689f5e8f09d034af910c5b6800f9d739&name_0=PR&name_1=Stateless+tests+%28amd_asan_ubsan%2C+flaky+check%29
PR: ClickHouse#97261

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@devcrafter devcrafter closed this Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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