Repository navigation
Fix segfault when a subquery scopes distributed_plan_execute_locally - #113422
Conversation
QueryPlan::convertToDistributed decides whether a make_distributed_plan query
runs in process or is dispatched to workers, but that decision was consulted
from two different settings objects fed by two different contexts.
QueryPlan.cpp read optimization_settings, built from the interpreter's context,
while createExchangeLookup and createDistributedQueryExecutor re-read
distributed_plan_execute_locally from CurrentThread::tryGetQueryContext().
A subquery carrying its own SETTINGS clause gets a fresh per node context
(QueryTreeBuilder applies the clause to a Context::createCopy and stores it on
the QueryNode, and the planner plans against that node context), which the
outer interpreter never sees. The two sides then disagree and the initiator
builds a pipeline whose halves contradict each other. One query produced both
resulting failures: the plan built no TaskToHostMap because it saw local
execution while the executor factory selected DistributedQueryPlanExecutorRemote
because it saw remote execution, and that constructor dereferences the null map,
so the server segfaults; and the plan left the exchange stream hosts empty while
the lookup was built for streaming exchanges, so resolving the terminal
final_result__0_0 stream raised a logical error.
Decide once, where the decision already lives. createExchangeLookup takes the
mode as a parameter instead of reading the ambient context, and
createDistributedQueryExecutor derives it from task_to_host_map == nullptr,
which makes the segfault unrepresentable rather than merely keeping a bool and a
pointer in sync. doExecuteTask threads the mode through because it is shared by
both paths: true from the local executor's entry point, false from the stateless
worker. Adding a null check at the dereference or an early return at the lookup
would leave the initiator building a contradictory pipeline, so neither is done.
The null map already meant "execute locally" at every call site before this
change, which is why the existing gtest that passes nullptr next to
setSetting("distributed_plan_execute_locally", 1) needs no edit. One chassert
pins that invariant in the remote executor's constructor.
Found in CI, five failures across three unrelated pull requests and two check
types (Stress test, AST fuzzer) in ninety days, no master hits, since
make_distributed_plan and distributed_plan_execute_locally are both experimental
and off by default.
The new test covers the crash direction, the opposite direction (whose oracle
reads the execution mode from system.query_log, since both modes return the same
rows), and a control that must stay green. Reverting either half of the fix
independently reddens it on a different failure mode, and mutants hardcoding
either constant at doExecuteTask's call also redden it.
No wire format, setting default, or serialization version changed.
The test profile sets max_rows_to_group_by to 10G (tests/config/users.d/limits.yaml, installed unconditionally by install.sh) and distributed aggregation rejects any nonzero limit, so both count() subqueries failed with SUPPORT_IS_DISABLED in every stateless job. The setting is not randomized, so no opt-out tag would have helped. Reset it per subquery, matching the ten aggregating distributed siblings that already do. automatic_parallel_replicas_mode is pinned next to enable_parallel_replicas because the runner randomizes it to 2 a quarter of the time; the pin is currently inert because adjustSettingsForMakeDistributedPlan resets it, but it documents the requirement alongside its already-pinned alias. Both execution modes return the same rows, so a result-only assertion cannot tell whether the plan ran in process or was dispatched. Only one of the three arms checked the mode. The other two now read it from system.query_log as well. The control arm additionally had to change shape: with the settings on its inner table subquery it built no distributed plan at all, so neither DistributedPlan profile event was ever emitted and a mode assertion there was unsatisfiable rather than merely weak. Applying the settings to the whole query keeps the arm free of any jointly scoped divergence, which is what makes it a control, while actually exercising the distributed path. A mutant that forces the remote branch while still building the host map returns the identical row counts and flips both new assertions, so they catch a wrong mode that the row counts cannot see. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (3 rounds, 5 findings adjudicated, 1 fix round) - click to expandI reviewed this change with an independent model before publishing, in three rounds. Round 1 Round 1: 3 findings agreed, 1 refuted ❌ The test could not pass in any stateless job.
💡 Refuted: no platform or job tag is needed. The suggestion was that the fast-test job cannot Round 2: 1 nit, noted not blocking 💡 The test comment presents the Round 3: no findings A third cold pass over the final tree returned nothing. It re-derived the three fixed items Also verified and found sound (no action): the plan's value is genuinely the one the plan was |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260805-012800 |
|
cc @davenger @antaljanosbenjamin, could you review this? |
|
Workflow [PR], commit [ec5be1d] Summary: ❌
AI ReviewSummaryThis PR removes the Findings
Final VerdictNeeds one more change before merge: the segfault path is fixed, but LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 52/52 (100.00%) · Uncovered code |
| /// The query's single decision on where the plan runs. Every consumer below derives from it, | ||
| /// directly or from `task_to_host_map` being null, so none of them re-reads the setting from | ||
| /// the ambient context, which a subquery-scoped SETTINGS clause can leave disagreeing. | ||
| const bool execute_locally = optimization_settings.distributed_plan_execute_locally; |
There was a problem hiding this comment.
This only preserves distributed_plan_execute_locally. The executor still re-enters through ReadFromDistributedPlanSource::tryGenerate with CurrentThread::tryGetQueryContext(), and then both the local-task path (executeTask/Context::createCopy(context)) and remote-task path (startStage/task_description.settings_changes = context->getSettingsRef().changes()) clone or serialize settings from that ambient context.
The reproducer already proves that this ambient context can differ from the query-node context that produced optimization_settings, so a subquery-scoped execution setting like max_threads, max_memory_usage, or max_block_size is still lost when the fragment starts. That fixes the transport branch, but SETTINGS scoping is still broken for distributed fragments unless the source/executor carries the whole subquery settings/context, not just this boolean.
There was a problem hiding this comment.
I measured this. The mechanism is real: a subquery-scoped setting other than distributed_plan_execute_locally does not reach the fragment. It is also pre-existing and unchanged by this PR, so I am not widening the diff here.
Oracle: each fragment gets its own system.query_log row (query = 'stage_0_<n>') whose Settings map is what that fragment actually ran with. I set marker values on max_rows_to_read / max_result_rows / max_execution_speed / lock_acquire_timeout, one fresh database per arm, and asserted each server's build id before reading it:
binary markers scoped fragment Settings reading
pristine base inside nested subquery 20000000 1000000000 1e11 60 lost (profile/default)
pristine base whole query (control) 88881 88882 88883 88884 present
this PR inside nested subquery 20000000 1000000000 1e11 60 lost
this PR whole query (control) 88881 88882 88883 88884 present
The control arm is what makes the loss meaningful: same settings, same shape, no nesting divergence, and the markers do arrive. max_block_size and max_threads are likewise absent from the fragment's changed-settings map in the divergent arm and present in the control, so the two you named by name are confirmed.
Base and this PR read identically, and the diff touches neither site you cite: grepping settings_changes and createCopy over git diff <base>..HEAD -- src/ returns nothing. The leak is at DistributedPlanExecutor.cpp:1544 and :822, which no version of this PR read. What this PR removes is the ambient read of the one boolean at plan and executor construction, 2 ambient reads down to 0; the settings set at fragment start is assembled elsewhere.
For the record, the user-visible consequence is a rejection, not a lost limit:
SELECT (SELECT count() FROM t1 INNER JOIN t2 ON intDiv(t1.key,2)=t2.key
SETTINGS make_distributed_plan = 1, distributed_plan_execute_locally = 1,
max_rows_to_group_by = 0, max_rows_to_read = 1000000)
SETTINGS max_rows_to_read = 5;The subquery relaxes its own limit, so 100 is the right answer. Observed on base and on this PR: Code: 158 TOO_MANY_ROWS ... max rows: 5.00, current rows: 100.00: While executing ReadFromDistributedPlanSource. The identical shape with no distributed plan returns 100, so the distributed path is the deviation. It is not wrong results: with read_overflow_mode='break' on the outer query it returns the correct 100.
Both gating settings are EXPERIMENTAL and default off, and I found no issue or PR tracking the fragment-settings source, so I am recording it here rather than stacking a design change onto a segfault fix.
… unavailable
`Build (amd_freebsd)` failed with
DistributedPlanExecutor.cpp:582:16: error: unused parameter 'context'
[-Werror,-Wunused-parameter]
`createExchangeLookup` reads `context` only through
`context->getConfigRef()` at two sites, and both sit inside the
`#if defined(OS_LINUX) || defined(OS_DARWIN)` block that guards the
streaming-exchange transport. Replacing the ambient
`distributed_plan_execute_locally` read with the explicit
`execute_locally` parameter removed the one use that was outside that
block, so on FreeBSD the parameter became unreferenced and
`-Weverything -Werror` rejected the translation unit.
Add `context` to the existing `UNUSED(...)` call in the `#else` branch,
which is the pattern the same branch already applies to
`exchange_stream_sources`. Deleting the parameter instead is not
possible: it is genuinely used on Linux and macOS, and dropping it makes
those platforms fail with `use of undeclared identifier 'context'` at
the two `getConfigRef` sites (measured).
`UNUSED` is a `constexpr` empty function template taking
`[[maybe_unused]]` arguments, so this cannot affect code generation. The
Linux object file for this translation unit is byte-identical before and
after the change (md5 5d89fca3c90a62ee554b4fb1ea17454a in both arms),
and the `clickhouse` binary keeps Build ID
ff72eb2289556a7df4f9a66ca9003828c69a27e8.
Verified by compiling the real translation unit with its own CI flags and
only the OS define swapped, so the FreeBSD preprocessor branch is
selected: before the change the FreeBSD arm reproduces the exact
diagnostic at 582:16 and the Linux arm is clean; after it, both arms
report zero diagnostics under `-Werror`. Reverting just the added token
restores the error on the FreeBSD arm while the Linux arm stays clean.
CI finish ledger — c6db92cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260805-170000 |
…/fix-distributed-plan-execute-locally-split-brain # Conflicts: # src/QueryPipeline/DistributedPlanExecutor.cpp
CI finish ledger - b50e86aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Both hung checks belong to the 2026-08-10 spike, not the analyzer-recursion family that the aggregated stacks
Nothing here is PR-caused. Session id: cron:our-pr-ci-monitor:20260811-190000 |
|
…lly-split-brain Master added two new reads of `distributed_plan_execute_locally` since the previous merge (TaskToHostMap's constructor and getCascadesPlanningNodeCount), so the `namespace Setting` block keeps all four declarations. The branch's own removal of the two split-brain reads in createExchangeLookup and createDistributedQueryExecutor is unchanged.
The constructor read the setting from the ambient query context and returned an empty map when it was set. Its only caller already decides where the plan runs and passes a null map for local execution, so the map is only ever constructed for a plan that dispatches to workers and the read was redundant. It was also wrong for the case this branch fixes. With `distributed_plan_execute_locally` set on the outer query and unset inside a subquery, the plan decided to dispatch while the constructor observed the outer value and leased no hosts, so startStage looked up a task host that was never assigned and threw std::out_of_range. On master the same ambient value was read by createExchangeLookup as well, so both halves were wrong together and produced in-memory exchanges; making the lookup follow the plan exposed the constructor. Verified on the merged tree with two build ids: pristine master plus the new test dies with a segfault and 'No host found for exchange stream', the fixed build passes and the server stays alive. The distributed_plan suite is 37/37 and DistributedQueryTest 2/2.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units14 translation units recompiled, 49 s compile time in total, 14 of them have a recent master baseline. |
CI finish ledger - ec5be1dEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Same signature as the head that adjudication covered (same file, same line, same function, and no The functional halves of the same validation are green on both arches at this head Session id: cron:our-pr-ci-monitor:20260818-210000 |
|
This is a blocker to not reverting Cascades. |
90e6c43
…annot compile the overlaid tests `Bugfix validation (unit tests)` overlays a PR's changed `src/**/tests/*` files onto the merge base and builds `unit_tests_dbms` without the fix. When the fix changes a function signature that an existing gtest calls, the adapted call site can never compile against the merge base, so the job reported a permanent ERROR the PR author cannot avoid - e.g. on PR ClickHouse#113422, where a 2-line adaptation of `gtest_distributed_query.cpp` to `createExchangeLookup`'s new parameter keeps the check red while the actual regression coverage (a functional test, validated green by `Bugfix validation (functional tests)` on both arches) is elsewhere. This signature-adaptation shape is recurring: 18 such rows across 7 PRs in the last 30 days. Attribute the compile errors instead of failing close unconditionally: when every compiler error lies inside the overlaid test files, report the compile step as an expected failure (`XFAIL`, job OK) with "nothing to validate on the unit side". It is deliberately NOT counted as a reproduction - nothing proves the touched suite catches the bug - and the merge gate is unchanged: `new_tests_check.py` still demands a real validation from the functional/integration jobs when such tests exist, and already treats an inconclusive unit result as non-blocking for unit-only PRs. Any other compile failure (errors in fix sources or contrib, a link error, no parsable diagnostic) keeps the fail-close ERROR. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113422&sha=latest&name_0=PR&name_1=Bugfix%20validation%20%28unit%20tests%29 Related: ClickHouse#113422 Co-Authored-By: Claude Fable 5 <[email protected]>
|
@groeneai @alexey-milovidov @davenger — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a segfault and a
LOGICAL_ERROR(No host found for exchange stream final_result__0_0) when a subquery setsdistributed_plan_execute_locallyin its ownSETTINGSclause undermake_distributed_plan. The distributed plan and the code executing it read the setting from two different contexts and could disagree, so the initiator built a self-contradictory pipeline.Description
QueryPlan::convertToDistributeddecides whether amake_distributed_planquery runs in-process or is dispatched to workers, but that decision was read from two different settings objects:QueryPlan.cppusedoptimization_settings(the interpreter's context), whilecreateExchangeLookupandcreateDistributedQueryExecutorre-readdistributed_plan_execute_locallyfromCurrentThread::tryGetQueryContext().A subquery with its own
SETTINGSclause gets a fresh context the planner uses and the outer interpreter never sees, so the two sides can disagree. One query produced both failures:TaskToHostMap(it saw local) while the executor factory chose the remote executor (it saw non-local), whose constructor dereferences that null pointer: a segfault, present in release builds;final_result__0_0threwLOGICAL_ERROR.The fix decides once, where the decision already lives.
createExchangeLookuptakes the mode as a parameter, andcreateDistributedQueryExecutorderives it fromtask_to_host_map == nullptrinstead of re-reading the setting, so the remote executor can no longer be selected with a null map.doExecuteTaskthreads the mode through:truefrom the local executor,falsefrom the stateless worker. No wire format, default, or setting changes.Found in CI: five failures over ninety days across three unrelated pull requests and two check types (
Stress test,AST fuzzer), no master hits, since the setting is experimental and off by default. No carrier touches this code. Example report: Stress test (amd_debug) on #110084.A deterministic repro segfaults on master 5 of 5 runs and returns the correct result with the fix. The new test covers both directions plus a control, and reverting either half of the fix independently reddens it on a different failure mode.
#86353conflicts textually inDistributedPlanExecutor.cppbut does not fix this: it keeps both ambient reads.Workflow [PR]
Sync PR [sync-upstream/pr/113422]
Version info
26.8.1.1725(included in26.8and later)