Skip to content

Do not marshal blocks of a local shard plan in a distributed query - #111997

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-grouping-set-blob-unmarshall
Aug 4, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
groeneai:fix-grouping-set-blob-unmarshall

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed Expected UInt64 column for __grouping_set, got BLOB and ColumnBLOB should be converted to a regular column before usage logical errors on a distributed query executed on a shard with enable_parallel_blocks_marshalling (enabled by default), for example with GROUP BY GROUPING SETS over a cluster that has a local replica, or when reading a Merge table that spans a local and a distributed table. BlocksMarshallingStep is no longer added to plans whose blocks are consumed in the same process.

Description

Closes: #111945
Related: #102192

Found by the AST fuzzer on #102192 (unrelated to that PR's own changes): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102192&sha=1cc5e03ee5dcdadf1c59c0dd19322992f9c16e72&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Logical error: Expected UInt64 column for __grouping_set, got BLOB at MergingAggregatedTransform.cpp:142.

BLOB there is not a data type: it is what ColumnBLOB::getFamilyName returns, and ColumnBLOB is the enable_parallel_blocks_marshalling wrapper. So __grouping_set sits at the right header position with the right logical type; it is a marshalled UInt64 that was never unmarshalled. Header and arity are fine, so this is not an initiator-vs-remote header mismatch.

Root cause: the gate that adds BlocksMarshallingStep in Planner::buildPlanForQueryNode keys on properties of the context (query_kind == SECONDARY_QUERY, distributed_depth), not on whether the plan's output will actually cross a socket. When a query runs on a secondary context and reads a cluster that has a local replica, the local branch is planned in-process by createLocalPlan at a non-Complete stage on that same secondary context. The gate fires and appends BlocksMarshallingStep to a plan that is then united straight into the parent pipeline, where no UnmarshallBlocksTransform exists (that transform lives only on remote pipes). The ColumnBLOB reaches the parent operators as is.

The fix adds SelectQueryOptions::is_local_plan_for_distributed_query, sets it in the local-plan builders, and adds it to the gate. It is conditioned on !build_logical_plan in createLocalPlan, because a logical plan is serialized and shipped to a shard which sends its blocks back over the network and must keep marshalling. The plan a shard builds for its own top-level query is unaffected: its blocks do go to the socket, so the gate still fires there.

Five carriers are covered. Three build a local shard or replica plan through createLocalPlan / createLocalPlanForParallelReplicas: the local shard stream in SelectStreamFactory, the stale-replica local fallback in ReadFromRemote, and the parallel replicas local plan. Two more build a nested child plan with their own SelectQueryOptions and unite it in this process with no unmarshalling: ReadFromMerge::createPlanForTable and StorageBuffer::read. createLocalPlanFragmentForParallelReplicas is not a carrier: it rewrites an existing plan fragment and never runs the Planner.

The Merge carrier is issue #111945, which has its own message and its own reproducer (below), and is fixed here because the gate is the shared cause.

Only GROUP BY GROUPING SETS with two or more sets hits the __grouping_set message, because MergingAggregatedTransform::addChunk returns early for a single set before type-checking the column. The stray ColumnBLOB reached every other consumer on that path too, so the previous fixes in this area (#88544, #98783, #107319) were fixing individual consumers rather than the gate.

Removing the step for local plans is also a small win: it used to serialize and compress every block for data that never leaves the process.

Reproducer (aborts a debug server on master, works with this change):

$CLICKHOUSE_CLIENT --compression 1 --query_kind=secondary_query -q "
    SELECT x, sum(y) FROM remote('127.0.0.{1,2}', currentDatabase(), tab)
    GROUP BY GROUPING SETS ((x, z % 1), (intDiv(z, 100), z + 2))
    SETTINGS enable_parallel_blocks_marshalling = 1, prefer_localhost_replica = 1"

--compression 1 matters: without a network codec the marshalling callback returns the block unchanged, so nothing is wrapped.

Reproducer for the Merge carrier (#111945), same behavior:

CREATE TABLE mt.a (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO mt.a SELECT number FROM numbers(1000);
CREATE TABLE mt.r (x UInt64) ENGINE = Remote('127.0.0.1:9000', 'mt', 'a');
SELECT x FROM remote('127.0.0.1:9000', merge('mt', '')) ORDER BY x DESC LIMIT 3
SETTINGS enable_parallel_blocks_marshalling = 1, prefer_localhost_replica = 0;

The Buffer carrier now has a test too. Reaching that code needs a query processing stage above FetchColumns, and a Buffer inherits its stage from its destination table, so the destination has to be a Distributed one and the flush thresholds have to be large enough that rows are still in the buffer at read time. With that shape, reverting only the assignment in StorageBuffer::read aborts the test with the same Expected UInt64 column for __grouping_set, got BLOB, and the plan assertion added next to it goes from two BlocksMarshalling steps to four, so neither case is asserting nothing.

03403_parallel_blocks_marshalling_for_distributed.sql carries a commented-out case of this shape, annotated "triggers a logical error in fuzzing tests" and "Not yet supported; see the comment in Planner::buildPlanForQueryNode()" (its wording, verbatim). Its plan is correct with this change, but I left it commented out to keep this PR to the fix plus its own regression test.

Version info

  • Backported to: 26.7.26.8, 26.3.47.3

groeneai and others added 3 commits July 26, 2026 18:43
A distributed query with GROUP BY GROUPING SETS executed on a shard could
fail with a logical error:

  Expected UInt64 column for __grouping_set, got BLOB

BLOB there is ColumnBLOB::getFamilyName(), the enable_parallel_blocks_marshalling
wrapper, so the column was at the right header position with the right logical
type: it was a marshalled UInt64 that nothing had unmarshalled.

The gate that adds BlocksMarshallingStep in Planner::buildPlanForQueryNode()
keys on properties of the context (query_kind == SECONDARY_QUERY,
distributed_depth, to_stage) rather than on whether the plan's blocks will be
written to a socket. When a query runs on a secondary context and reads a
cluster that has a local replica, the local branch is planned in-process by
createLocalPlan at a non-Complete stage on that same secondary context. The
gate fired and appended BlocksMarshallingStep to a plan that is then united
straight into the parent pipeline, where no UnmarshallBlocksTransform exists
(that transform lives only on remote pipes), so the ColumnBLOB reached the
parent operators as is.

Add SelectQueryOptions::is_local_plan_for_distributed_query, set it in the
local-plan builders, and add it to the gate. In createLocalPlan it is
conditioned on !build_logical_plan, because a logical plan is serialized and
shipped to a shard which sends its blocks back over the network and must keep
marshalling. A shard's own top-level plan is unaffected: its blocks do go to
the socket, so the gate still fires there.

Three carriers are covered: the local shard stream in SelectStreamFactory,
the stale-replica local fallback in ReadFromRemote, and
createLocalPlanForParallelReplicas.
createLocalPlanFragmentForParallelReplicas is not a carrier, it rewrites an
existing plan fragment and never runs the Planner.

Only GROUP BY GROUPING SETS with two or more sets produces this particular
message, because MergingAggregatedTransform::addChunk returns early for a
single set before type-checking the column. The stray ColumnBLOB reached
every other consumer on that path too, which is why the earlier fixes in this
area addressed individual consumers rather than the gate.

Removing the step for local plans is also a small win: it used to serialize
and compress every block for data that never leaves the process.

Found by the AST fuzzer on ClickHouse#102192, unrelated to that PR's own changes.
The previous commit's carrier enumeration was incomplete: it said three
carriers, all of them local shard/replica plans built through
createLocalPlan.

Two storage layers build a nested child plan of their own, with a fresh
SelectQueryOptions at a non-Complete stage on the caller's context, and
then unite that plan into the current pipeline in this process with no
unmarshalling:

  ReadFromMerge::createPlanForTable, united by ReadFromMerge::buildPipeline
  which adds only a MaterializingTransform,

  StorageBuffer::read, whose buffers plan is united with the table plan.

So the gate still fired for them and produced the same stray ColumnBLOB.
For the Merge table it surfaces as a different message, because the
column is caught by columnMatchesType inside
ExpressionActions::executeOnColumns rather than by
MergingAggregatedTransform::addChunk:

  ColumnBLOB should be converted to a regular column before usage

This is what a Merge table spanning a local MergeTree and a Remote or
Distributed table hits when it is read through remote(), reported as
issue ClickHouse#111945.

Setting the flag on the nested options cannot remove marshalling that
anything depends on: when the outer query is itself a shard plan, the
outer plan carries its own BlocksMarshallingStep, so the socket boundary
is still marshalled exactly once at the right level.

The Merge case is added to the regression test. There is no Buffer case:
the code path is a carrier by inspection, but I could not construct a
query that reaches it with a marshalled block, and a test that may not be
asserting anything is worse than none.

The test also pins enable_analyzer, because only the analyzer adds the
step and CI runs variants with the old analyzer, and it now asserts the
plan shape for three configurations instead of one: remote(), parallel
replicas, and a plan serialized to be shipped to a shard. The last one is
what pins the !build_logical_plan condition, which was previously
unexercised.

Closes: ClickHouse#111945
The `distributed plan` CI variants set `serialize_query_plan = 1` in the default
profile, and a plan serialized and shipped to a shard legitimately still carries
`BlocksMarshallingStep`. That step is not registered in `QueryPlanStepRegistry`
on master, so the shard fails to deserialize the plan with
`Unknown query plan step: BlocksMarshalling` - a pre-existing limitation
unrelated to this fix, which the test would otherwise import as a deterministic
failure in four PR-blocking jobs.

Pin the setting on the clients rather than skipping the test, so the coverage is
kept everywhere. The plan-shape assertion for the shipped plan keeps its own
query-level `serialize_query_plan = 1` and stays EXPLAIN-only.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Three review rounds by a second model, independent of the author, plus my own cold review of the
resulting code in each round. Findings are reproduced with the verdict I reached against the code.

Round 1 (5 findings AGREED, all fixed)

Finding Verdict
❌ enable_analyzer was not pinned, and only the analyzer ever adds BlocksMarshallingStep, so the test would have asserted nothing (and failed on its last line) in the three CI variants that run with allow_experimental_analyzer = 0. AGREE, fixed. Pinned rather than tagged away, so the coverage is kept in those variants.
❌ Two carriers were missed: ReadFromMerge::createPlanForTable and StorageBuffer::read build a nested child plan with fresh SelectQueryOptions at a non-Complete stage and unite it in this process with no unmarshalling. AGREE, fixed. The Merge one turned out to be issue #111945, reproduced and now covered by a test case, so this PR closes it. Buffer is fixed for symmetry; no reproducer found, so no test.
⚠️ The parallel replicas block could go vacuous: enable_parallel_replicas = 1 silently degrades to plain local execution if the cluster is unavailable, and both result rows would still match. AGREE, fixed. Mode 2 throws instead, and a plan-shape assertion for ReadFromRemoteParallelReplicas was added.
⚠️ Nothing tested the one guard that keeps marshalling on plans shipped to shards (!build_logical_plan), so a mutation to true would have passed the whole file. AGREE, fixed. An EXPLAIN-only assertion with serialize_query_plan = 1 was added; the mutation now breaks exactly that line.
💡 Comment style: function names written with application parentheses, SQL and log literals not in inline code. AGREE, fixed.

Round 2 (1 finding AGREED, fixed; 3 DISAGREED)

Finding Verdict
❌ The executed queries did not pin serialize_query_plan, so in the four distributed plan CI jobs they would inherit 1 from the default profile and hit a pre-existing master limitation: a plan shipped to a shard legitimately carries BlocksMarshalling, which is not registered in QueryPlanStepRegistry, so the shard fails with Unknown query plan step: BlocksMarshalling. AGREE, fixed. --serialize_query_plan 0 on the clients; the shipped-plan assertion overrides it at query level and stays EXPLAIN-only. Verified by running the unpinned test against a server with serialize_query_plan = 1 in the default profile: it fails with exactly that error, and the pinned one passes.
⚠️ Register BlocksMarshalling in QueryPlanStepRegistry. DISAGREE. Pre-existing on master (verified on a pristine binary) and not this PR's contract; registering it would change the shipped-plan path and add a cross-version compatibility surface. The finding above is about the test importing the gap, not about closing it.
⚠️ Re-enable the commented-out case in 03403_parallel_blocks_marshalling_for_distributed.sql. DISAGREE. Its plan is correct with this change, but re-enabling it is unrelated churn in another test.
💡 Remaining unquoted SQL and exception literals. AGREE, fixed.

Round 3 (2 findings, both DISAGREED with evidence)

Finding Verdict
❌ The test leaves four tables behind, so the functional-test leftover-table check rejects it and stress reruns on a shared database collide with them. DISAGREE. Both legs are refuted mechanically. The leftover check is gated on self.case_file >= "02800", and case_file is an absolute path built from os.path.abspath(args.queries); '/' sorts before '0', so that comparison is False for every test in the tree, not just this one (64 of the 1645 04* stateless tests that create server tables leave them behind and are green on master). And the shared-database stress regime cannot select this test: it is tagged shard, clickhouse-test skips such tests whenever --shard is absent, --shard defaults to unset, and no stress or upgrade path passes it (only the functional-test job does). Each functional-test run therefore gets a fresh randomized database that is dropped afterwards. The 50x randomized run (50 passes) is the control against self-collision. Adding the drops would still be good hygiene; it is not a correctness issue here.
⚠️ The recorded hashes depend on group_by_use_nulls, which the test does not pin, because the second grouping set omits x and a null x changes cityHash64. DISAGREE. The mechanism is real (AggregatingStep wraps a used grouping key in toNullable under that setting), but the setting is unreachable for this test: its only injection site in the tree is the stress runner, it is not in the settings randomizer and not in any test profile, and as above a shard-tagged test is never selected by the stress runner. In-tree practice matches: 56 of the 77 stateless tests using GROUPING SETS do not pin it.

No finding was raised twice without being fixed. Author self-adjudication was not used: the fix
plans were written by the reviewer and executed by a separate implementation pass, which never
pushed.

Session id: cron:clickhouse-review-slot-9:20260727-000001

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse client --compression 1 --query_kind=secondary_query -q "SELECT x, sum(y) FROM remote('127.0.0.{1,2}', currentDatabase(), tab) GROUP BY GROUPING SETS ((x, z % 1), (intDiv(z, 100), z + 2)) SETTINGS enable_parallel_blocks_marshalling = 1, prefer_localhost_replica = 1" aborts a debug server on every run. No fuzzer and no randomization needed. --compression 1 is required: without a network codec the marshalling callback returns the block unchanged.
b Root cause explained? Yes. The gate that adds BlocksMarshallingStep (Planner.cpp:2684) keys on context properties (query_kind == SECONDARY_QUERY, distributed_depth, to_stage) instead of on whether the plan's blocks will cross a socket. A local shard/replica plan is built in-process by createLocalPlan at a non-Complete stage on that same secondary context, so the gate fires; that plan is then united into the parent pipeline, which has no UnmarshallBlocksTransform (it exists only on remote pipes). The ColumnBLOB reaches MergingAggregatedTransform::addChunk, whose typeid_cast<const ColumnUInt64 *> on __grouping_set fails. BLOB is ColumnBLOB::getFamilyName(), not a data type, so the header and arity were always correct.
c Fix matches root cause? Yes. The missing term is added to the predicate that adds the step. No guard at the consumer, no widened bound, no no-random-* tag, no data-size reduction.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed. New regression test 04647_no_blocks_marshalling_for_local_shard_plan.sh covering the local shard plan, the parallel replicas local plan, and a Merge table over a local plus a distributed table, each with marshalling on and off, plus three plan-shape assertions. It also pins the single-grouping-set branch (the addChunk early return) so the branch this fix does not target cannot regress unnoticed, and marks the non-secondary query case as a control. enable_analyzer = 1 is pinned because only the analyzer ever adds the step, and serialize_query_plan = 0 is pinned on the executed queries because a plan shipped to a shard legitimately carries BlocksMarshalling, which is not in QueryPlanStepRegistry on master; the assertion for the shipped plan overrides that pin at query level and stays EXPLAIN-only.
e Both directions demonstrated? Yes, for both reproducers. Each fails on the pristine master binary with the stack of its reported logical error and passes with the fix; results are byte-identical to enable_parallel_blocks_marshalling = 0. Three mutation tests, each rebuilt with the Build-ID verified against SELECT buildId(): removing the new gate term makes the test abort with Expected UInt64 column for __grouping_set, got BLOB; reverting only the parallel replicas assignment makes it abort on the parallel replicas query; making the createLocalPlan flag unconditional instead of !build_logical_plan breaks exactly the serialized-plan assertion. No assertion is vacuous.
f Fix is general across code paths? Yes. BlocksMarshallingStep is constructed in exactly one place in the tree, so the gate is the complete set of insertion points. Two carriers build a nested child plan and unite it in this process: ReadFromMerge::createPlanForTable (reproduced, issue #111945) and StorageBuffer::read (fixed for symmetry, no reproducer found). All three local-plan carriers are covered: SelectStreamFactory local shard stream (reproduced), createLocalPlanForParallelReplicas (independently reproduced with parallel replicas on a plain local table), and the stale-replica local fallback in ReadFromRemote (same createLocalPlan call, covered by construction). The shipped-plan builders must keep marshalling and were verified to keep it: createLocalPlan with build_logical_plan = true, createRemotePlanForParallelReplicas, and a shard's own top-level plan (EXPLAIN still shows the step at the top, and with no remote() at all). createLocalPlanFragmentForParallelReplicas rewrites an existing plan fragment and never runs the Planner, so it is not a carrier.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and type wrappers are not a factor by construction: convertColumnsToBLOBs wraps every non-const non-Tuple column regardless of Nullable/LowCardinality/Array/Map, and this change removes the wrapping step wholesale for local plans rather than type-gating anything. Parameter matrix covered by the test: one vs several grouping sets, marshalling on/off, secondary vs initial query, plain local shard vs parallel replicas vs Merge table, new analyzer and old analyzer (the test passes with allow_experimental_analyzer both 0 and 1). Boundary note: convertColumnsToBLOBs returns early for rows() <= 1, hence the 1000-row fixture.
h Backward compatible? Yes. No setting is added, removed, or has its default changed, so no SettingsChangesHistory.cpp entry is needed. No serialization format change: BlocksMarshallingStep::deserialize is untouched and plans shipped to shards still contain the step. The only behavior change is that a plan which carried a step whose output nothing could consume no longer carries it.
i Invariants and contracts preserved? Yes. The change establishes the invariant "BlocksMarshallingStep is added only to a plan whose blocks are written to a socket or serialized into a shipped plan", and both halves were verified. BlocksMarshallingStep has input_header == output_header and an empty updateOutputHeader(), so removing it cannot perturb the header the UnionStep matches against. The new option is reset in SelectQueryOptions::subquery() exactly as is_local_shard_plan is, so it cannot leak into a subquery's options. No new error or early-return paths; no durability, on-disk format, or crash-recovery surface is touched.

Session id: cron:clickhouse-impl-slot-42:20260726-234100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @KochetovNicolai - could you review this? The gate that adds BlocksMarshallingStep in Planner::buildPlanForQueryNode keys on context properties (secondary query, distributed depth) rather than on whether the plan's blocks actually cross a socket, so a local shard/replica plan built in-process by createLocalPlan gets the step and is then united into the parent pipeline, which has no UnmarshallBlocksTransform. It adds a SelectQueryOptions flag for the in-process local plans (also the nested Merge and Buffer child plans) while keeping marshalling for plans that are shipped to a shard.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [65ce53d]

Summary: ✅


AI Review

Summary

This PR narrows BlocksMarshallingStep to plans whose output actually crosses a socket by threading a dedicated SelectQueryOptions flag through the local shard/replica carriers (createLocalPlan, parallel replicas, StorageMerge, and StorageBuffer) and backing it with focused regression coverage in 04647. After reviewing the current diff, the modified code paths, the prior discussion threads, and the green CI matrix, I did not find an actionable correctness, compatibility, or test-coverage issue in the current patch.

Final Verdict

✅ No actionable findings.

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: 47/47 (100.00%) · Uncovered code

Full report · Diff report

Comment thread src/Storages/StorageBuffer.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Recording an affects measurement for the Merge carrier (#111945), because an automated triage comment on that issue reported this as reproducing on master only and clean on 26.6, 26.5, 26.4, 26.3, 26.2, 26.1. That matrix is wrong, and the reason is worth having here: its reproducer uses ENGINE = Remote, which is itself a new feature (c1dfaa69a0ea, 2026-05-31) present only on master and 26.7. On older branches the CREATE TABLE fails with Code: 56 UNKNOWN_STORAGE, so merge('mt', '') spans a single plain MergeTree, nothing produces marshalled blocks, and the query returns a correct result. Those six "clean" runs assert nothing.

Measured locally instead. Remote builds a StorageDistributed (StorageDistributed.cpp:2693 -> the create lambda at :2505 -> :2649), so substituting ENGINE = Distributed over a one-replica cluster pointing at the server itself is the same code path and is valid on every branch:

version bot's script (Remote) same shape with Distributed
master 26.8.1.1 (debug) aborts aborts, ColumnBLOB fatal
26.7.2.22 Code: 49 ColumnBLOB -
26.6.2.117 vacuous, Code: 56 Code: 49 ColumnBLOB
26.3.17.77 vacuous, Code: 56 Code: 49 ColumnBLOB
26.1.13.3 vacuous, Code: 56 Code: 49 ColumnBLOB

Note 26.7 reproduces with the unmodified script; it was simply not in that matrix, and it is the one release branch besides master where the script is valid.

Negative controls on 26.6, same fixture: dropping the distributed table out of the merge set is clean, and keeping it with enable_parallel_blocks_marshalling = 0 is clean. Only marshalling on plus a distributed table in the merge set fails.

This is consistent with the root cause described above rather than with a recent regression: the gate at Planner.cpp:2685-2690 is byte-identical on master, 26.7, 26.6, 26.5, 26.4, 26.3, 26.2 and 26.1, and enable_parallel_blocks_marshalling defaults to true on all of them.

So the Bug Fix (user-visible misbehavior in an official stable release) category is correct, and this is reachable on shipping stable releases rather than master-only. I am not adding backport labels; that call belongs to the reviewers.

groeneai and others added 2 commits July 27, 2026 09:09
The regression test covered the `Merge` carrier but never read a `Buffer`
table, so the assignment on the buffers `SelectQueryOptions` in
`StorageBuffer::read` was only correct by inspection and a later refactor
could have dropped it silently.

Reaching that code needs a stage above `FetchColumns`, which a `Buffer`
inherits from its destination table, so the destination is a `Distributed`
one and the flush thresholds are large enough to keep rows in the buffer at
read time. Reverting only that one assignment now aborts the test with
`Expected UInt64 column for __grouping_set, got BLOB`, and the added plan
assertion goes from two `BlocksMarshalling` steps to four.

Co-Authored-By: Claude Fable 5 <[email protected]>
The test exceeded the 180s flaky-check limit on the `amd_asan_ubsan` lane
(194.3s and 183.5s out of 50 runs, the rest between 51s and 146s), which
`tests/clickhouse-test` reports as `Test runs too long (> 180s)`.

Its runtime was dominated by starting client processes rather than by any
query. The statements were spread over 17 separate `clickhouse client`
invocations, and none of the queries is heavy: measured per statement on a
debug build, the whole test took 1.95s spread almost uniformly at about
0.08s per invocation, while running 19 trivial queries as 19 processes cost
1.32s against 0.10s for the same 19 queries inside one process.

That cost is about five times higher under a sanitizer: a single
`clickhouse local -q "SELECT 1"` takes about 0.75s with ASan against 0.14s
on a debug build. The flaky check also runs every selected test many times
concurrently with `nproc - 1` workers, and process startup is exactly the
resource that contention makes more expensive, so the per-run time grew with
the load until the tail crossed the limit.

Group the statements into as few invocations as possible (17 down to 6) and
emit the section headers as `SELECT` constants inside those batches instead
of from the shell. Driving the test with an ASan client against the same
server, this takes it from 9.0s to 3.7s when run alone, and the gain grows
with contention, which is the regime that actually failed: with copies
pinned to 8 CPUs the slowest copy goes from 8.6s to 3.4s at 8 copies and
from 16.9s to 6.0s at 16 copies, so 2.4x alone, 2.5x at 8 copies and 2.8x
at 16.

No assertion is changed, added or removed, and the `.reference` file is
untouched, so the output is byte for byte the same. The relevant behaviour of
a batch was checked first: per-statement `SETTINGS` are still honoured,
`rowNumberInAllBlocks` restarts for every statement, and
`--query_kind=secondary_query` applies to every statement, so the marshalling
gate still fires after the first one.

The `long` tag would also silence the failure, but it cuts the flaky-check
repeats to a tenth, and this test relies on those repeats to cover two
separate carriers.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Planner/Planner.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 81.00% 86.20% +5.20%
Functions 91.50% 91.90% +0.40%
Branches 73.10% 78.30% +5.20%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3b497fb

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) + Server died (one abort, two rows) pre-existing trunk abort, not caused by this diff. 94 hits over 83 distinct pull requests in the last 14 days, plus 5 MASTER runs on the same job (most recently 1d4408f7 on 2026-07-27), first seen 2026-07-14. The aborting query reads an inner materialized-view table under parallel replicas, unrelated to the BlocksMarshallingStep gate this PR changes. Tracking issue #110518. #111689 (ours, open)

Session id: cron:our-pr-ci-monitor:20260727-180000

…ob-unmarshall

Refresh the CI base. The branch was based on master of 2026-07-26 and
`Planner.cpp`, `StorageMerge.cpp` and `StorageBuffer.cpp` have all moved
since, so the previous green run no longer says anything about current
master. The fix itself is unchanged: all five `is_local_plan_for_distributed_query`
sites survive the merge intact.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

All good.

pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Aug 5, 2026
…tion

A mutation is interpreted in a background thread, where the current database is not set.
When the predicate of `ALTER TABLE ... DELETE/UPDATE` used the `merge` table function with
a single argument, the source database was resolved to an empty string, and
`DatabaseCatalog::getDatabase` failed on `chassert(!database_name.empty())`. The mutation is
persisted, so the server kept aborting a second after every start attempt, and could not start.

Now the database of the mutated table is substituted into the `merge` table function when the
mutation is created, in the same way as it is done for table names, so the mutation reads the
same tables as the `ALTER` query. Before, `merge(currentDatabase(), 'regexp')` in a mutation
silently resolved to the database from the `default_database` configuration setting instead.

Additionally, the table function now throws `UNKNOWN_DATABASE` when it is called with a single
argument and the current database is not set, instead of passing an empty name down the stack.

Found by the AST fuzzer in a stress test:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111997&sha=17d2ddbbdee6ee0f726b7621839905cd5caa65e3&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
Related: ClickHouse#111997

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Sep 26, 2026
Antalya 26.6 Backport of ClickHouse#111997 - Do not marshal blocks of a local shard plan in a distributed query
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Sep 26, 2026
The fast test fails `05060_hybrid_unknown_table_exact_schema` with
`Unknown table engine IcebergS3` (`UNKNOWN_STORAGE`). The fast test build
has no S3 or Iceberg support, and the test creates an `IcebergS3` table.
Tag it `no-fasttest`, like the other Iceberg tests.

The note about `enable_parallel_blocks_marshalling = 0` goes too: the
`DISTINCT` over `ColumnBLOB` abort it worked around is fixed by
ClickHouse#111997, now merged here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat nickitat added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 8, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 8, 2026
alexey-milovidov pushed a commit that referenced this pull request Oct 9, 2026
Resolve the cherry-pick of #111997 onto 26.3.

The three conflicts are context only: on master the new assignments sit next to
is_local_shard_plan (35cff6a), which 26.3 does not have, so the resolution
keeps only the lines #111997 adds and does not bring is_local_shard_plan along.

The new test drops SETTINGS explain_query_plan_default = 'legacy': the setting
does not exist on 26.3, where the legacy EXPLAIN format is the only one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll added a commit that referenced this pull request Oct 9, 2026
Cherry pick #111997 to 26.3: Do not marshal blocks of a local shard plan in a distributed query
robot-clickhouse added a commit that referenced this pull request Oct 9, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 9, 2026
alexey-milovidov added a commit that referenced this pull request Oct 9, 2026
Backport #111997 to 26.3: Do not marshal blocks of a local shard plan in a distributed query
clickhouse-gh Bot added a commit that referenced this pull request Oct 10, 2026
Backport #111997 to 26.7: Do not marshal blocks of a local shard plan in a distributed query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Logical error ColumnBLOB should be converted to a regular column before usage when merge() spans a table producing marshalled blocks

7 participants