Skip to content

Fix serialization of IN-subquery sets under plan-based parallel replicas - #110874

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-futureset-subquery-serialize-pr
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-futureset-subquery-serialize-pr

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108504

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Fixes a LOGICAL_ERROR under the experimental plan-based parallel replicas feature (parallel_replicas_plan_based = 1, added by #108504). Found by the AST fuzzer (STID 2678-3c21); not reachable in a stable release, as the setting is experimental and off by default.

That path ships the initiator's already-optimized plan fragment to the replicas, sharing FutureSetFromSubquery objects with the local plan. For SELECT ... WHERE a IN (SELECT k FROM src) the shared set loses its subquery plan before the fragment is serialized, and QueryPlan::serializeSets throws. Two causes, each fixed here:

  1. FutureSetFromSubquery::buildOrderedSetInplace discarded the subquery plan even on its non-destructive path, where the speculative pipeline runs against a clone so the canonical plan is still valid. Primary key analysis takes that path, and the fragment is now built after index analysis. Serializing the set by value is no alternative: past use_index_for_in_with_subqueries_max_values the set keeps only its hash table. The plan is retained only when a setting enabling a plan-serializing consumer is on, so a plain local IN (subquery) still releases it and its table locks.
  2. The eager serialization in createRemotePlanFragmentForParallelReplicas was gated on serialize_query_plan, but ReadFromParallelReplicasStep always hands the fragment to its RemoteQueryExecutor, which always sends it.

Validated on a 3-replica cluster: the test fails before the fix, passes after, matches non-parallel results, and reverting either change reddens it. It asserts its own preconditions, so silently losing the distributed read or the set build cannot leave it green.

Three shapes are still broken and tracked separately, all reproducing on master. A nested IN and a non-key PREWHERE take the destructive analysis-time build, which moves the plan out unconditionally. A LowCardinality(Nullable) key hits this same error on master and becomes a catchable Code: 117 from the function type round trip here, which is a separate defect outside these files.

Under parallel_replicas_plan_based=1 with serialize_query_plan=1, a query with
an IN-subquery aborted with LOGICAL_ERROR 'Cannot serialize FutureSetFromSubquery
with no query plan' (and 'Method serialize is not implemented for
ParallelReplicasSplit'). Introduced by ClickHouse#108504; found by the AST fuzzer
(STID 2678-3c21).

The plan-based path ships the initiator's optimized fragment to replicas,
sharing FutureSetFromSubquery objects with the local plan. The deferred set
build consumes each set's subquery source plan during local execution, so lazy
send-time serialization found no plan. Additionally the IN-subquery's own plan
carried a transient ParallelReplicasSplitStep, which has no serialization.

Serialize the remote fragment in createRemotePlanFragmentForParallelReplicas
while the shared sets still own their source plans (mirroring the classic
serialize_query_plan path), and skip the ParallelReplicasSplitStep marker in
QueryPlan::serialize like the other transient pass-through markers.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 3-replica cluster with parallel_replicas_plan_based=1, serialize_query_plan=1, use_index_for_in_with_subqueries=1: SELECT count() FROM t WHERE a IN (SELECT k FROM src) aborts every time on the pre-fix binary.
b Root cause explained? Yes. Plan-based PR ships the initiator's optimized fragment to replicas, sharing FutureSetFromSubquery objects with the local plan. Local execution's deferred set build moves each set's subquery plan (source) out, so lazy send-time serialization finds source==nullptr -> throw. Separately, the IN-subquery's own plan carries a transient ParallelReplicasSplitStep, which has no serialize.
c Fix matches root cause? Yes. (1) Serialize the fragment in createRemotePlanFragmentForParallelReplicas while the shared sets still own their source plans (cached, reused by sendQueryPlan) — mirrors the classic serialize_query_plan path. (2) Skip ParallelReplicasSplitStep in QueryPlan::serialize like the other transient pass-through markers.
d Test intent preserved / new tests added? New stateless test 04561_pr_plan_based_in_subquery_set added; asserts results match non-PR execution across local_plan 0/1, key/non-key IN, and aggregation.
e Both directions demonstrated? Yes. Pre-fix binary aborts with the LOGICAL_ERROR; post-fix binary returns correct results matching the reference (exact diff match).
f Fix is general across code paths? Yes. Serialization skip covers every plan containing the marker (local_plan 0/1, nested subquery set plans). The eager-serialize hook is the single site building the remote fragment. Not a symptom guard.
g Fix generalizes across inputs? Verified with key-IN, non-key-IN, and GROUP BY (aggregation split); UInt64 columns. The fix is structural (marker skip + serialize timing), independent of set element type.
h Backward compatible? Yes. Serialization only skips a transient never-persisted marker; no on-disk/wire format change beyond not emitting a step that never had a serialization. Setting is experimental, default off. SettingsChangesHistory.cpp not affected.
i Invariants and contracts preserved? Yes. ParallelReplicasSplitStep is a single-child pass-through marker (documented: "transient marker; never reaches pipeline generation; pass-through if executed directly"), handled identically to DelayedCreatingSetsStep/DelayedMaterializingCTEsStep which the traversal already skips. Eager serialization uses the existing ensureSerialized cache contract.

Session id: cron:clickhouse-worker-slot-0:20260717-131800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @KochetovNicolai — could you review this? It fixes a LOGICAL_ERROR under plan-based parallel replicas (parallel_replicas_plan_based=1, from #108504) with serialize_query_plan=1: an IN-subquery's shared FutureSetFromSubquery has its source plan consumed by the local deferred set build before lazy send-time serialization, and the subquery's own plan carries a non-serializable transient ParallelReplicasSplitStep. Fix serializes the remote fragment early (sets still own their plans) and skips the split marker in QueryPlan::serialize like the other transient markers.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [342bdf2]

Summary: ⏳

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID: 2678-39f1) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Cannot serialize FutureSetFromSubquery with no query plan (STID: 2678-39f1) FAIL cidb

AI Review

Summary

This PR fixes the original plan-based parallel-replicas IN-subquery serialization exception and the new regression test exercises the intended remote-serialization path well. One resource-lifetime regression is still present, though: the retained subquery plan is now keyed off session settings instead of an actual serializing consumer, so some plain local queries still keep the subquery plan's locks and QueryPlanResourceHolder alive until the outer query finishes.

Findings

⚠️ Majors

  • [src/Interpreters/PreparedSets.cpp:434-437,623] The new maySerializeQueryPlan gate still treats serialize_query_plan = 1 as if every query will ship a set plan. In reality, serialize_query_plan only builds a remote query_plan when SelectStreamFactory::createForShardImpl is constructing a remote shard stream at src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:177-183. A plain local MergeTree query with serialize_query_plan = 1 never serializes anything, but after a clone-path buildOrderedSetInplace it still retains source, so the subquery's QueryPlanResourceHolder / table locks stay pinned until the outer query ends. The original “common local-query path” regression is therefore only partially fixed; the retention needs to key off an actual serializing consumer, not the session setting.
Final Verdict

Request changes: narrow the retained source predicate to queries that will actually serialize the set plan.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4dbd9b9bdabe7cbaea464a906ed05770

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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) + (targeted, old_compatibility) / Cannot serialize FutureSetFromSubquery with no query plan (STID 2678-39f1) LOGICAL_ERROR (the bug THIS PR fixes) This PR (#110874) is the fix. Pre-merge fuzzer draws random settings that still reach the pre-fix serialize_query_plan + parallel_replicas_plan_based path; the fix targets exactly this serialization site. 0 master hits.
Integration tests (arm_binary, distributed plan, 1/4) / test_replicated_database::test_replicated_table_structure_alter flaky #110030 (ours, open) + issue #110036 (open)
Stress test (amd_msan) / current_version != existing_version (STID 2508-399f, PatchJoinCache.cpp:326) LOGICAL_ERROR a fix task is moved to pending (investigating at full effort — fixing PR link to follow here). Chronic trunk patch-parts assertion, 8 unrelated PRs + 1 master in 30d; unrelated to this PR (touches only ParallelReplicasLocalPlan.cpp + Serialization.cpp).
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260717-230000

alexey-milovidov and others added 3 commits July 29, 2026 01:06
…rialized

After master moved the parallel-replicas split into the plan optimizer, the
remote fragment is now built during optimizeTreeSecondPass, i.e. AFTER primary
key analysis has already built the IN-subquery's set in place. The in-place
build discarded the set's subquery plan unconditionally, so serializing the
fragment threw

  Cannot serialize FutureSetFromSubquery with no query plan

which reddened this PR's own regression test in Fast test.

Two things are fixed:

1. buildOrderedSetInplace no longer drops `source` on its non-destructive path.
   That path deliberately runs the speculative pipeline against a clone, so the
   canonical plan is still valid and unconsumed when it finishes; it was simply
   being thrown away. Serializing the set by value is not an alternative,
   because once the set exceeds use_index_for_in_with_subqueries_max_values it
   clears its materialized elements and keeps only the hash table, so the
   subquery plan is the only shippable description of it. On the destructive
   fallback (a non-clonable source, e.g. a nested IN) `build` really did move
   the plan out, so the reset is kept there.

2. The eager serialization in createRemotePlanFragmentForParallelReplicas is no
   longer gated on serialize_query_plan. ReadFromParallelReplicasStep always
   hands the fragment to its RemoteQueryExecutor, which always sends it, so this
   path serializes regardless of that setting; with the gate, a fragment whose
   set is consumed only by the local pipeline still failed at send time.

Each change is covered separately by the extended test: item 1 by the key-column
IN (only a key column reaches index analysis) plus the max_values shape, item 2
by the serialize_query_plan = 0 queries with index analysis disabled.

Verified on a 3-replica cluster: the test fails on the pre-fix build and passes
on the fixed one, and reverting either change alone reddens it again. Every
result matches non-parallel execution.

A nested IN subquery still hits the same error through the destructive fallback;
that is pre-existing and tracked separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ss silently

Every asserted result equals what plain local execution returns, so if the
distributed split or the index-time set build silently stopped happening the
value assertions would still be green and the test would no longer cover the
serialization path at all.

Assert both preconditions explicitly: the plan contains a ReadFromParallelReplicas
step, and index analysis reports granule pruning (i.e. it really built the set).
Both are written as SELECT over EXPLAIN filtered with ILIKE, which is robust to
plan formatting changes. Verified load-bearing: setting parallel_replicas_plan_based = 0
reddens the first guard and use_index_for_in_with_subqueries = 0 reddens the second.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Interpreters/PreparedSets.cpp Outdated
set_and_key->set = speculative_set;
source.reset();

/// Keep the preserved `source`: plan serialization ships a set as a subquery plan and cannot rebuild one

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.

Keeping source whenever the clone path succeeds changes the common local-query path too, not just the serialized remote one. source owns the subquery plan's QueryPlanResourceHolder (table locks, storage holders, interpreter contexts), and before this patch a successful in-place build released all of that here. Now a plain local ... IN (subquery) that hit key analysis keeps the entire RHS plan and its locks alive until the outer query finishes even though build will never consume source again once set_and_key->set is created.

For long-running queries this can hold share locks on the subquery tables and extra plan memory for no benefit. Can we preserve source only when the set may actually need plan serialization, or replace it with a compact serialized form once the remote fragment has been eagerly cached?

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.

Agreed, and fixed in 342bdf2e2da1c0.

The blast radius is real: buildOrderedSetInplace has around fifteen callers with nothing to do with parallel replicas (key analysis, the skip-index conditions, VirtualColumnUtils, KVStorageUtils, StorageSystemUsers, StorageSystemZooKeeper, ConditionSelectivityEstimator, evaluateConstantExpression), and the retention was ungated, so it was not confined to the experimental setting the rest of the change is scoped to.

The plan is now retained only when a setting that enables a query-plan-serializing consumer is on: serialize_query_plan for the classic parallel-replicas and distributed readers, parallel_replicas_plan_based, and make_distributed_plan. Those are all the consumers, and the predicate fails closed, so a new one keeps the plan only once its setting is listed. A plain local IN (subquery) releases the plan exactly as before, which I verified: it returns the right result, still prunes granules, and the subquery table can be dropped immediately afterwards.

That is your first suggestion. The second one is not available in general: past use_index_for_in_with_subqueries_max_values the set clears its materialized elements and keeps only the hash table (Set.cpp:216-220), so hasExplicitSetElements() is false and there is no compact value form to substitute. The retained plan is the only shippable description of such a set.

The regression test gained the shape that pins this: serialize_query_plan = 0 with index analysis still on. Keying the retention on serialize_query_plan alone still aborts there, and no previously covered shape detected it.

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.

I don't think this is fully fixed yet. The current predicate is still session-wide: maySerializeQueryPlan returns true for any query with serialize_query_plan = 1 (src/Interpreters/PreparedSets.cpp:434-437), and that is enough to skip the source.reset at src/Interpreters/PreparedSets.cpp:623.

But serialize_query_plan only creates a remote query_plan when a remote shard stream is actually being built (src/Interpreters/ClusterProxy/SelectStreamFactory.cpp:177-183). A plain local SELECT ... WHERE key IN (subquery) over a local MergeTree can have serialize_query_plan = 1 and never hit any plan serialization at all, so the clone-path buildOrderedSetInplace still keeps the subquery plan's QueryPlanResourceHolder / table locks alive until the outer query ends.

So the original local-query retention issue is still present; the predicate needs to depend on an actual serializing consumer, not just the session setting.

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 14/14 (100.00%) · Uncovered code

Full report · Diff report

Addresses the automated review on the previous revision.

`buildOrderedSetInplace` kept the preserved `source` plan on every non-destructive build,
but that plan is only needed by `QueryPlan::serializeSets`, which ships a prepared set to
another server as its subquery plan and cannot rebuild one from an already-built set. On a
plain local query nothing serializes, so the retained plan is unreachable (`build` returns
early once the set is created) while still owning the subquery's table locks, storage
holders and interpreter contexts: after a clone-path build it is their sole owner, because
`QueryPlan::clone` copies the plan nodes and not the resource holder.

That function has around fifteen callers across key analysis, skip indexes, virtual columns
and system tables, none of which involve parallel replicas, so the retention was not
confined to the experimental setting the rest of this change is scoped to. Release the plan
as before unless one of the three settings that enable a query-plan-serializing consumer is
set: the classic and plan-based parallel-replicas readers and the distributed-plan
executor. The predicate fails closed, so a future consumer keeps the plan only once its
setting is listed.

The `ParallelReplicasSplitStep` serialization skip is dropped: master has since moved split
insertion into the plan optimizer, and the fragment builder clones the subtree below the
marker, so no such step can enter a serialized plan. The set's own plan cannot carry one
either, being built unoptimized with only its clone optimized. Removing the branch leaves
the test green and no plan-based shape reaches the corresponding error, which is what
identifies it as dead rather than untested. `Serialization.cpp` is therefore unchanged.

Three test fixes. The index-analysis precondition asserted only that `Granules:` appears,
which it does whenever any index analysis runs, so it could not detect the set dropping out
of key analysis; it now asserts the `IN` set reached the primary key condition. The
`serialize_query_plan = 0` cases used `parallel_replicas_local_plan = 0` instead of the
process-global one-shot `parallel_replicas_wait_for_unused_replicas` failpoint, which a
concurrent query could consume. A case with `serialize_query_plan = 0` and index analysis
on was added, the only shape that shows the retention must key on
`parallel_replicas_plan_based` rather than on `serialize_query_plan` alone.

Co-Authored-By: Claude Fable 5 <[email protected]>
@devcrafter

Copy link
Copy Markdown
Member

Close in favor of #112443

@devcrafter devcrafter closed this Jul 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing the loop on the one ledger line above that was owned by a fix task rather than a PR: current_version != existing_version (STID 2508-399f, PatchJoinCache.cpp:326) is fixed by #115979. Root cause was upstream duplicate (_block_number, _block_offset) identities, not this PR.

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

4 participants