Repository navigation
Do not marshal blocks of a local shard plan in a distributed query - #111997
alexey-milovidov merged 7 commits into
Conversation
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]>
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 Round 1 (5 findings AGREED, all fixed)
Round 2 (1 finding AGREED, fixed; 3 DISAGREED)
Round 3 (2 findings, both DISAGREED with evidence)
No finding was raised twice without being fixed. Author self-adjudication was not used: the fix Session id: cron:clickhouse-review-slot-9:20260727-000001 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-42:20260726-234100 |
|
cc @devcrafter @KochetovNicolai - could you review this? The gate that adds |
|
Workflow [PR], commit [65ce53d] Summary: ✅
AI ReviewSummaryThis PR narrows Final Verdict✅ No actionable findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 47/47 (100.00%) · Uncovered code |
|
Recording an affects measurement for the Measured locally instead.
Note Negative controls on 26.6, same fixture: dropping the distributed table out of the merge set is clean, and keeping it with This is consistent with the root cause described above rather than with a recent regression: the gate at So the |
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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 52/52 (100.00%) · Uncovered code |
CI finish ledger — 3b497fbEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
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]>
Pulls in the fix for the unrelated `ColumnBLOB should be converted to a regular column before usage` stress failure (ClickHouse#111997, ClickHouse#113165). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=88234&sha=6729c72c50125a345ffaadec601d8e66a5de8148&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
…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]>
Antalya 26.6 Backport of ClickHouse#111997 - Do not marshal blocks of a local shard plan in a distributed query
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]>
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]>
Cherry pick #111997 to 26.3: Do not marshal blocks of a local shard plan in a distributed query
… in a distributed query
Backport #111997 to 26.3: Do not marshal blocks of a local shard plan in a distributed query
Backport #111997 to 26.7: Do not marshal blocks of a local shard plan in a distributed query
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Expected UInt64 column for __grouping_set, got BLOBandColumnBLOB should be converted to a regular column before usagelogical errors on a distributed query executed on a shard withenable_parallel_blocks_marshalling(enabled by default), for example withGROUP BY GROUPING SETSover a cluster that has a local replica, or when reading aMergetable that spans a local and a distributed table.BlocksMarshallingStepis 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 BLOBatMergingAggregatedTransform.cpp:142.BLOBthere is not a data type: it is whatColumnBLOB::getFamilyNamereturns, andColumnBLOBis theenable_parallel_blocks_marshallingwrapper. So__grouping_setsits at the right header position with the right logical type; it is a marshalledUInt64that was never unmarshalled. Header and arity are fine, so this is not an initiator-vs-remote header mismatch.Root cause: the gate that adds
BlocksMarshallingStepinPlanner::buildPlanForQueryNodekeys 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 bycreateLocalPlanat a non-Completestage on that same secondary context. The gate fires and appendsBlocksMarshallingStepto a plan that is then united straight into the parent pipeline, where noUnmarshallBlocksTransformexists (that transform lives only on remote pipes). TheColumnBLOBreaches 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_planincreateLocalPlan, 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 inSelectStreamFactory, the stale-replica local fallback inReadFromRemote, and the parallel replicas local plan. Two more build a nested child plan with their ownSelectQueryOptionsand unite it in this process with no unmarshalling:ReadFromMerge::createPlanForTableandStorageBuffer::read.createLocalPlanFragmentForParallelReplicasis not a carrier: it rewrites an existing plan fragment and never runs the Planner.The
Mergecarrier 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 SETSwith two or more sets hits the__grouping_setmessage, becauseMergingAggregatedTransform::addChunkreturns early for a single set before type-checking the column. The strayColumnBLOBreached 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):
--compression 1matters: without a network codec the marshalling callback returns the block unchanged, so nothing is wrapped.Reproducer for the
Mergecarrier (#111945), same behavior:The
Buffercarrier now has a test too. Reaching that code needs a query processing stage aboveFetchColumns, and aBufferinherits its stage from its destination table, so the destination has to be aDistributedone 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 inStorageBuffer::readaborts the test with the sameExpected UInt64 column for __grouping_set, got BLOB, and the plan assertion added next to it goes from twoBlocksMarshallingsteps to four, so neither case is asserting nothing.03403_parallel_blocks_marshalling_for_distributed.sqlcarries a commented-out case of this shape, annotated "triggers a logical error in fuzzing tests" and "Not yet supported; see the comment inPlanner::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
26.7.26.8,26.3.47.3