Skip to content

Fix segfault when a subquery scopes distributed_plan_execute_locally - #113422

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distributed-plan-execute-locally-split-brain
Aug 19, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distributed-plan-execute-locally-split-brain

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 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):

Fixes a segfault and a LOGICAL_ERROR (No host found for exchange stream final_result__0_0) when a subquery sets distributed_plan_execute_locally in its own SETTINGS clause under make_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::convertToDistributed decides whether a make_distributed_plan query runs in-process or is dispatched to workers, but that decision was read from two different settings objects: QueryPlan.cpp used optimization_settings (the interpreter's context), while createExchangeLookup and createDistributedQueryExecutor re-read distributed_plan_execute_locally from CurrentThread::tryGetQueryContext().

A subquery with its own SETTINGS clause gets a fresh context the planner uses and the outer interpreter never sees, so the two sides can disagree. One query produced both failures:

  • the plan built no 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;
  • the plan left the exchange stream hosts empty while the lookup was built for streaming exchanges, so resolving final_result__0_0 threw LOGICAL_ERROR.

The fix decides once, where the decision already lives. createExchangeLookup takes the mode as a parameter, and createDistributedQueryExecutor derives it from task_to_host_map == nullptr instead of re-reading the setting, so the remote executor can no longer be selected with a null map. doExecuteTask threads the mode through: true from the local executor, false from 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. #86353 conflicts textually in DistributedPlanExecutor.cpp but does not fix this: it keeps both ambient reads.


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

Version info

  • Merged into: 26.8.1.1725 (included in 26.8 and later)

groeneai and others added 2 commits August 5, 2026 02:30
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]>
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 5 findings adjudicated, 1 fix round) - click to expand

I reviewed this change with an independent model before publishing, in three rounds. Round 1
returned three blocking/major findings on the regression test; round 2 (after the fix) returned
one nit; round 3 was a fresh cold pass that returned none. The source fix itself was approved in round 1 and is byte-identical since
(md5 of all five source files unchanged between the two reviewed commits), so the second commit
is test-only.

Round 1: 3 findings agreed, 1 refuted

❌ The test could not pass in any stateless job. tests/config/users.d/limits.yaml sets
max_rows_to_group_by: 10G in the default profile and install.sh installs it unconditionally,
while makeDistributed.cpp rejects any nonzero value, so both count() subqueries died with
SUPPORT_IS_DISABLED. The setting is not randomized, so no opt-out tag would have helped either.
AGREED, severity raised from major to blocker (a deterministic red, not a flake), and
reproduced under the real profile before prescribing the fix. Fixed by resetting the setting per
subquery, matching the 37 of 42 aggregating make_distributed_plan tests that already do.

⚠️ automatic_parallel_replicas_mode unpinned. The runner randomizes it to 2 a quarter of the
time and a separate guard rejects it under make_distributed_plan. AGREED on the static chain
but explicitly not on a measurement I had not taken. Verified on a real server in round 2: the
guard is currently unreachable, because adjustSettingsForMakeDistributedPlan normalizes both of
its disjuncts to zero on every settings change. The pin was kept anyway (it documents the
requirement next to its already-pinned alias, and the randomizer produced the value 416 times in
the 50-run batch), and the inertness is recorded in the commit message rather than asserted away.

⚠️ Two of three arms had no execution-mode oracle. Both modes return identical rows, so a
result-only assertion cannot tell whether the plan ran in process or was dispatched. The design
note said so, but only one arm applied it. AGREED, and I required each new assertion to redden
on a mutant or the item stayed open. Round 2 also found the prescribed oracle unsatisfiable on
the control arm as written (it built no distributed plan at all, so neither profile event existed);
the arm was reshaped to apply its settings to the whole query, which keeps it free of the
jointly-scoped divergence that makes it a control while actually exercising the distributed path.
A new mutant that forces the wrong mode without crashing returns the identical row counts and
flips both new assertions.

💡 Refuted: no platform or job tag is needed. The suggestion was that the fast-test job cannot
serve a worker dispatch. It can: the worker endpoint runs inside the ordinary server, the
distributed query config carrying both the worker server and the worker client is installed
outside every fast-test guard, and the arm gets the same streaming transport as an existing
untagged multi-stage shuffle-join test. DISAGREED, and round 3 settled it by measurement
rather than by reading: over fourteen days that untagged sibling reports 4025 passes on
Fast test (arm_darwin) and 6856 on Fast test with no failures, while a no-darwin sibling
reports 4024 skips on the same job. A dispatching plan therefore succeeds on both platforms
thousands of times a fortnight. I also withdrew one of my own supporting citations on
re-derivation.

Round 2: 1 nit, noted not blocking

💡 The test comment presents the automatic_parallel_replicas_mode pin as load-bearing without
repeating that it is currently inert. Agreed; the inertness is stated in the commit message, which
is where the reasoning belongs.

Round 3: no findings

A third cold pass over the final tree returned nothing. It re-derived the three fixed items
independently, re-ran the failure census, and checked two further hypotheses that earlier rounds had
not raised: whether any other limit in the test profile can be rejected by a distributed plan the way
max_rows_to_group_by is (of roughly fifty limits that profile sets, that one is the only setting any
make_distributed_plan refusal reads; the sort and distinct limits travel with the fragment instead of
throwing), and whether a randomized setting could flip an execution-mode assertion (the mode is now a
function of a single pointer, derived from a setting the runner does not randomize). One inaccurate
count in this comment was corrected.

Also verified and found sound (no action): the plan's value is genuinely the one the plan was
built with rather than a mirror; the remote executor has exactly one construction site and it is
reachable only when the map is non-null, so the crash state is unrepresentable; no ambient reads of the setting
remain in the executor; both worker entry paths force the flag off, so there is no recursion; the
new mandatory parameter makes a missed call site a compile error rather than a silent conversion;
and #86353 conflicts textually in this file but keeps both ambient reads, so it does not
supersede this fix.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 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, serialize_query_plan = 1, distributed_plan_max_rows_to_broadcast = 0, enable_join_runtime_filters = 0, enable_parallel_replicas = 0) on a debug build whose config supplies distributed_query.streaming_exchange_port and stateless_worker_client. Segfaults 5 runs out of 5 on master; the local stack is frame for frame the CI stack.
b Root cause explained? QueryPlan.cpp read distributed_plan_execute_locally from optimization_settings (the interpreter's context) while createExchangeLookup and createDistributedQueryExecutor re-read it from CurrentThread::tryGetQueryContext(). A subquery with its own SETTINGS clause gets a fresh context that the planner uses and the outer interpreter never sees, so the two sides disagree: the plan built no TaskToHostMap while the executor factory picked the remote executor, whose constructor dereferences that null pointer, and the plan left the stream hosts empty while the lookup was built for streaming exchanges, so final_result__0_0 could not be resolved.
c Fix matches root cause? Yes. The decision is made once, where it already lives. No guard was added at the dereference site or at the throw site: createDistributedQueryExecutor now derives the branch from task_to_host_map == nullptr, so the remote executor cannot be selected with a null map at all.
d Test intent preserved / new tests added? New stateless test 04746_distributed_plan_execute_locally_subquery_settings with three arms: the crash direction, the opposite direction, and a no-divergence control. No existing test was weakened or removed; the whole distributed_plan suite (22 tests) and DistributedQueryTest.* still pass.
e Both directions demonstrated? Yes. Segfault 5/5 on master, correct result 5/5 with the fix, both on Build ID verified binaries (0988965dcbee29f6 vs ff72eb2289556a7d). 50 randomized runs of the new test pass.
f Fix is general across code paths? Yes. The reader census was re-run on the final tree: the only remaining runtime readers of the setting are QueryPlanOptimizationSettings.cpp:245 (the source of truth) and :355, which reads the same object. Both ambient readers are gone. doExecuteTask is shared by the local and the worker paths, so the mode is threaded through it (true from the local executor, false from the stateless worker) rather than hardcoded; a mutant hardcoding either constant reddens the test.
g Fix generalizes across inputs (params/datatypes/wrappers)? The divergent value is a boolean, so the input axis is the two directions, and both are test arms: inner local under an outer default, and inner remote under an outer local. Type wrappers do not apply. I also measured the original fuzzer carrier (a three argument cluster(..., view(... SETTINGS ...))) and a well formed two argument cluster(); only shapes that give the subquery its own context reproduce, which is what the test encodes.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changed, so no SettingsChangesHistory.cpp entry is needed; no wire format or serialization version changed; no new setting. The changed signatures are internal C++ and every call site is updated in this PR.
i Invariants and contracts preserved? The load bearing invariant is that task_to_host_map == nullptr means "this plan executes in process", which is what makes deriving the branch from the pointer correct. It holds at both call sites: ReadFromDistributedPlanSource forwards the map built in convertToDistributed, which is null exactly when execution is local, and the existing gtest already passes nullptr next to setSetting("distributed_plan_execute_locally", 1), so the convention predates this change and that test needed no edit. One chassert(task_to_host_map) pins it in the remote executor's constructor.

Session id: cron:clickhouse-impl-slot-6:20260805-012800

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @davenger @antaljanosbenjamin, could you review this? convertToDistributed decided local-vs-dispatched execution from optimization_settings, while createExchangeLookup and createDistributedQueryExecutor re-read distributed_plan_execute_locally from the ambient query context, so a subquery that scopes the setting in its own SETTINGS clause made the two sides disagree: the plan built no TaskToHostMap while the factory picked the remote executor, which dereferences that null pointer. The fix passes the mode into the lookup and derives the executor kind from task_to_host_map == nullptr, so the null-map remote executor is unrepresentable.

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

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec5be1d]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Compile before-binary (ninja unit_tests_dbms, without the fix) ERROR IGNORED

AI Review

Summary

This PR removes the distributed_plan_execute_locally split-brain by carrying the planner's execution-mode decision into createExchangeLookup, deriving executor selection from task_to_host_map, and adding a focused stateless regression test for both mode directions. That should fix the reported segfault and LOGICAL_ERROR exception, but one settings-scoping bug is still open in the execution path, so I would not approve it as-is.

Findings

⚠️ Majors

  • [src/Processors/Sources/ReadFromDistributedPlanSource.cpp:41-42; src/QueryPipeline/DistributedPlanExecutor.cpp:932-939,1736-1739; src/Server/StatelessWorker/StatelessTaskExecutor.cpp:73-75] [dismissed by author -- https://github.com/Fix segfault when a subquery scopes distributed_plan_execute_locally #113422#discussion_r3718697561] The patch now carries distributed_plan_execute_locally explicitly, but fragment execution still clones and serializes settings from CurrentThread::tryGetQueryContext() instead of the subquery context that produced the distributed plan. A nested SETTINGS clause therefore still loses every other execution-affecting setting before fragment execution, so limits such as max_rows_to_read, max_threads, or max_block_size can still be enforced from the outer or default context rather than the subquery that was planned. Suggested fix: carry the planning context's SettingsChanges, or the full query-node context, alongside the distributed plan and use that snapshot for both DistributedQueryPlanExecutorLocal::makeContextForLocalExecution and DistributedQueryPlanExecutorRemote::startStage.
Final Verdict

Needs one more change before merge: the segfault path is fixed, but make_distributed_plan still does not preserve subquery-scoped settings across fragment execution.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 5, 2026
/// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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.

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.

@davenger davenger self-assigned this Aug 5, 2026
… 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.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c6db92c

Every failure below has an owner: a fixing PR (mine 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
Build (arm_release) / Post Hooks infra: build-profile telemetry INSERT fails against the CI logs cluster (non-gating hook; the enclosing check reports success, so it is invisible to the check-runs API) #113409 (external, open)
Bugfix validation (unit tests) harness: inconclusive, not a refutation. The job reports that contrib/musl differs between the merge-base and the checkout, so it cannot populate the before-worktree at the merge-base submodule revision. My diff changes no submodule (0 gitlinks of mode 160000) a fix task is moved to pending (investigating at full effort — fixing-PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260805-170000

…/fix-distributed-plan-execute-locally-split-brain

# Conflicts:
#	src/QueryPipeline/DistributedPlanExecutor.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b50e86a

Every failure below has an owner: a fixing PR (mine 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
Stress test (amd_tsan) / Hung check failed, possible deadlock found trunk: DROP TABLE prometheus from 04811_promql_topk_bottomk_limitk parks while the materialized shared subquery still holds a reference #114326 (external, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found same signature #114326 (external, open)
Bugfix validation (unit tests) harness: inconclusive, not a refutation. The before-binary cannot compile the overlaid gtest_distributed_query.cpp, because my diff changes the createExchangeLookup signature a fix task owns it (fixing-PR link to follow on this PR)

Both hung checks belong to the 2026-08-10 spike, not the analyzer-recursion family that the aggregated stacks
suggest. I read the HEAD of each hung_check.log instead of the CIDB context, because test_context_raw
keeps the TAIL: it preserves the post-mortem stack appendix and truncates the processlist block away, which
inverts the signature. Found hung queries sits at byte 7479 of 251665 (amd_tsan) and 6744 of 379024
(arm_tsan), and the first row of both is query: DROP TABLE prometheus;, is_cancelled: 1, single thread,
elapsed 947s and 432s, log_comment: 04811_promql_topk_bottomk_limitk.sql-test_<db>. resolveFunction
appears 20 and 18 times in those files and zero times inside the processlist block. #114326 reverts the
PromQL topk/limitk streaming plan and its shared-subquery materialization, which is this mechanism.

Bugfix validation (unit tests) is inconclusive rather than a regression, and the job's own log says so:
before_src/src/Server/DistributedQuery/tests/gtest_distributed_query.cpp:592:28: error: no matching function for call to 'createExchangeLookup', followed by ninja: build stopped: subcommand failed. The harness
compiles this PR's gtest against the before-binary, and this PR makes createExchangeLookup take the exchange
transport explicitly, so the before-side cannot build and the result cannot be attributed to the touched
regression case. The functional halves of the same validation are green on both amd64 and aarch64, i.e.
the regression tests do catch the bug.

Nothing here is PR-caused. Fast test, Style check, Config Workflow and Finish Workflow are all green,
and my diff touches the distributed-plan exchange path only.

Session id: cron:our-pr-ci-monitor:20260811-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Bugfix validation (unit tests): no fixing PR is owed for this row

I investigated the Bugfix validation (unit tests) error on b50e86a5592046843205d095c1fffcbf89f8c06e
and concluded that no code change is warranted, on this PR or in the harness. Recording why.

The job overlays this PR's changed src/**/tests/* onto the merge base and requires a touched gtest
suite to fail there. The only test-file change here is 2 lines, adapting one call site to
createExchangeLookup's new parameter list:

-        "test_query", ExchangeDescriptions{}, ..., /*temporary_files_=*/ nullptr, context);
+        "test_query", ExchangeDescriptions{}, ..., /*temporary_files_=*/ nullptr, context,
+        /*execute_locally=*/true);

TEST_F(DistributedQueryTest, InMemoryExchangeStreamWithoutColumns) already exists at the merge base
with an identical body. It came in with #111762 for an in-memory-exchange deadlock, and it contains no
reference to subquery-scoped settings, so it is a bystander of this fix rather than its regression
test. The before-side cannot compile it purely because the fix changes a function signature, which
says nothing about the bug.

The regression coverage for this PR is
04746_distributed_plan_execute_locally_subquery_settings, and both
Bugfix validation (functional tests, amd64) and (aarch64) are green on this head. So the bug is
validated; the unit row is reporting "inconclusive", which is accurate.

That row also cannot block this PR. new_tests_check.py:213 branches on new functional or
integration tests and returns at :218 once any per-arch validation passed, so the unit branch at
:234 is not reached here. The job is allow_failure=True in any case
(ci/defs/job_configs.py:970), and compile failures are deliberately classified as inconclusive
rather than as a refutation (ci/jobs/unit_tests_bugfix_validation_job.py:666-688).

I also checked the obvious remedy of making the overlaid call site compile against the merge base,
with the if constexpr (requires ...) technique used in ca63edf26803. It would make things worse
rather than better: the suites pass on a merge-base binary (30 days of CI show 4490 OK and 0 FAIL for
DistributedQueryTest*), so the job would reach :765 and report FAIL, "failed to reproduce the
bug". That trades a truthful inconclusive for an untruthful refutation on a test that is not this
fix's regression test.

Breadth, for context: over 30 days this exact signature is 18 rows across 7 PRs, against 2090
successes for the check. I am not proposing a harness change, since the compile-is-inconclusive
policy is deliberate and current, and I see no maintainer request to revisit it.

Session id: cron:clickhouse-plan-slot-0:20260811-192800

…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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ec5be1dba with master c26092991 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.05 MiB 699.03 MiB -3.03 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ec5be1d

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
Bugfix validation (unit tests) / Compile before-binary (gtest_distributed_query.cpp:592) harness inconclusive: the before-binary cannot compile the overlaid gtest, because this PR changes createExchangeLookup's parameter list. A compile failure is inconclusive, never a refutation Already adjudicated on this PR, no fixing PR is owed for this row: #113422 (comment)
Sync - CH Inc sync (private, not actionable)

Same signature as the head that adjudication covered (same file, same line, same function, and no
submodule-divergence message), so the conclusion carries over unchanged.

The functional halves of the same validation are green on both arches at this head
(Bugfix validation (functional tests, amd64) and (aarch64) both succeeded), so the regression
coverage does demonstrate the bug on the merge base.

Session id: cron:our-pr-ci-monitor:20260818-210000

@alexey-milovidov

Copy link
Copy Markdown
Member

This is a blocker to not reverting Cascades.

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

The code LGTM.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 19, 2026
Merged via the queue into ClickHouse:master with commit 90e6c43 Aug 19, 2026
181 of 183 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 20, 2026
…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]>
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov @davenger — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

6 participants