Skip to content

Revert "Revert "Multistage distributed queries" (#106020) — fixes ASan heap corruption on master" - #107146

Merged
davenger merged 13 commits into
masterfrom
revert-107122-revert-106020-multistage-distributed
Jun 15, 2026
Merged

davenger merged 13 commits into
masterfrom
revert-107122-revert-106020-multistage-distributed

Conversation

@davenger

@davenger davenger commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Reverts #107122

This reintroduces Multi-stage Distributed Query Execution feature (#106020) with additional fixes that aim at reducing memory consumption in tests with ASAN:

The heap corruption mentioned in the revert PR was not caused by this feature but was a pre-existing bug that was amplified in CI asan runs after a follow-up PR #106978 changed max_thread_pool_free_size to 128 (from default 1000). This PR does not change this setting.

Also includes follow-up fixes for
#106906
#107029

Version info

  • Merged into: 26.6.1.825

@davenger
davenger marked this pull request as draft June 11, 2026 04:10
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [340e648]

Summary: ⏳

job_name test_name status info comment
Stress test (arm_asan_ubsan, s3) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This revert reintroduces the multi-stage distributed query executor, stateless worker protocol, bucketed MergeTree reads, exchange plumbing, and broad stateless coverage. The feature is still gated, but the current implementation has unresolved correctness, compatibility, cancellation, resource-lifetime, and test-environment issues that can produce wrong results, leak server resources, or break rolling upgrades. My verdict is to block until the distributed-plan contract is made safe across identity propagation, serialization, read planning, exchange handshakes, and cleanup.

Findings

❌ Blockers

  • [src/Server/StatelessWorker/StatelessTaskExecutor.cpp:58] Worker fragments rebuild a fresh ClientInfo and keep only query ids before deserializing the plan. ActionsDAG::deserialize recreates context-dependent functions from ctx.context, so functions such as currentUser and row policies using tenant = currentUser() are evaluated with the worker/global user instead of the initiating user. This can return wrong rows or apply row-level filters under the wrong identity. Carry the initiator client info and install it on query_context before plan/action DAG deserialization.

  • [src/Core/ProtocolDefines.h:57] The query-plan serialization version is bumped globally, but that negotiated version is not threaded into the step serializers/deserializers used by distributed tasks. A mixed-version cluster can therefore accept a plan and then misparse step payloads after one side changes the format. Pass the negotiated version through every query-plan step serializer/deserializer, or explicitly reject distributed-plan shipping across incompatible versions.

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:4793] Bucketed distributed ReadFromMergeTree serializes only selected part names, not the filter DAG or coordinator-selected mark ranges. The worker reconstructs mark-range analysis without the original WHERE predicate, so it can read ranges the coordinator pruned, over-read data, trip limits, or return divergent results if later processing assumes the coordinator pruning was preserved. Serialize the selected ranges or the exact filter state needed to reproduce them.

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:4775] Bucketed reads reject several unsupported read-shape features but do not serialize or reject vector_search_parameters. A remote worker can build a plan without the vector-search state while the rest of the plan expects vector-search semantics such as _distance. Serialize the vector-search parameters or fail distributed planning for these reads.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:656] Worker-side reoptimization disables only part of the read-replacement machinery. Normal projections and direct text-index reads can still replace the bucketed ReadFromMergeTree, bypassing the bucket split and causing duplicate or missing rows. Disable all read replacements that can alter the physical MergeTree read shape for distributed fragments, or reject those plans.

  • [src/Server/DistributedQuery/ExchangeConnections.cpp:41] An unauthenticated source hello can create a pending_connections slot for any query id and stream name. A client can keep creating arbitrary pending entries, sockets, and eventfds that are not tied to expected tasks. Pre-register expected streams and reject unknown hellos, or add strict caps and cleanup for unauthenticated pending connections.

  • [src/Server/DistributedQuery/StreamingExchangeProtocol.cpp:26] SourceHelloBody::readAfterVersion uses unbounded readStringBinary for query_id and stream_name. The outer hello frame may be limited, but the string reader can allocate based on the encoded length before that bound is enforced. Bound string reads by the remaining hello-body size.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1432] If sendTask fails while the remote start request is still in flight, cleanup can send cancel/forget before the worker has installed the task, observe Unknown task, and then the delayed start can run orphaned. Make worker task start/cancel ordering durable with a tombstone or pending-cancel state, or make the coordinator wait for a definitive start outcome before treating cleanup as complete.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:461] The persisted-exchange destructor deletes temporary files even when cancellation returns before all remote tasks are truly terminal. A remote task can still write to or read from files the coordinator just removed. Defer local cleanup until every remote task reaches a terminal state, or move persisted exchange lifetime under a worker-side lease/GC contract.

⚠️ Majors

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1191] forgetTask is best effort after a task reaches terminal state. If the forget RPC fails, the worker can keep terminal task state, progress records, and future slots indefinitely. Add retry/TTL cleanup on the worker or keep coordinator-side forgetting tracked until it succeeds.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1334] The in-flight status counter is incremented after scheduling the async request, while the lambda can decrement before the increment runs. That race can underflow or exceed the intended concurrency limit. Increment before scheduling and roll it back only if scheduling throws.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1106] Cancellation cleanup walks tasks serially and can spend minutes in status/forget RPCs during query teardown. Run independent cleanup concurrently or enforce a global deadline so cancellation latency does not scale with task count times timeout.

  • [src/Server/DistributedQuery/StreamingExchangeSource.cpp:37] The source-side hello timeout is applied per receive operation, not as an absolute handshake deadline. A peer can keep the connection alive indefinitely by sending one byte before each timeout. Track an absolute deadline for the full hello exchange.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:725] Local object-storage temporary paths use only the endpoint subpath and unique filename when distributed_query.temporary_files_storage is configured, so local storage can write outside the configured root. Include the configured local path or use the storage path generator instead of rebuilding the key manually.

  • [tests/config/config.d/distributed_query.xml:16] The global stateless config binds a fixed streaming_exchange_port on every Linux server. db-replicated and similar stateless modes clone that config into multiple servers on the same host, so they race for port 9223. Install this config only for tests that need remote distributed plans, or rewrite/remove the fixed port for cloned servers.

  • [tests/queries/0_stateless/03394_distributed_shuffle_join_with_aggregation.sql:1] The new remote distributed-plan stateless tests are tagged only with no-old-analyzer, while their server config is installed only in Linux test runs and is not available in Darwin fast tests. Add linux or equivalent local-only tags to the remote-worker cases, and keep local-only distributed-plan tests separate if they should run everywhere.

Tests
  • ⚠️ Add a focused distributed-plan test proving initiator identity survives on worker fragments, ideally with a row policy or expression that depends on currentUser.
  • ⚠️ Add focused coverage for bucketed MergeTree reads with pruned mark ranges, vector search, projections, and direct text-index reads so unsupported read shapes either produce the same result remotely or are rejected.
  • ⚠️ Add failure-path coverage for delayed task start versus cancel/forget, persisted exchange cleanup during cancellation, bounded source hello parsing, and absolute handshake timeouts.
  • ⚠️ Add CI/test-environment coverage or tags that prove the new stateless tests run only where their remote-worker config is installed and cannot collide on a fixed port.
Performance & Safety

The Cloud performance report is off-path because make_distributed_plan is disabled by default, so it does not exercise the new executor. The unresolved safety concerns are mainly resource exhaustion, cancellation latency, worker-state lifetime, and rolling-upgrade compatibility rather than steady-state benchmark regressions.

Final Verdict

Status: ❌ Block

Minimum required actions: preserve initiator identity/context on workers before deserialization, make query-plan serialization versioned across distributed tasks, serialize or reject every MergeTree read feature that changes selected ranges or read shape, harden exchange handshake bounds and pending-connection admission, make task cancellation/forget/temp-file cleanup ordered and bounded, and constrain the new stateless tests to environments where their config is valid.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 11, 2026
@@ -0,0 +1,68 @@
-- Tags: no-old-analyzer

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.

These new remote distributed-plan stateless tests need to be kept out of non-Linux fast tests, or made local-only. tests/config/install.sh installs distributed_query.xml only on Linux because distributed_query.streaming_exchange_port is rejected elsewhere; on Darwin this test is still fast-test eligible, then make_distributed_plan = 1 either forces unsupported Streaming exchange or tries remote execution without stateless_worker_client configured. The same applies to the sibling new remote distributed-plan tests. Please add the linux tag to this group, or set distributed_plan_execute_locally = 1 where remote workers are not the behavior under test.

return;
}

auto & slot = pending_connections[connection_key];

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.

addConnection accepts any SourceHello and creates a pending_connections slot for arbitrary query_id / exchange_stream_id values. Because the streaming exchange handshake is unauthenticated and there is no expected-stream registry or expiry for producer-only slots, any peer that can reach this listen host can send unique stream names and keep a socket plus FutureConnection eventfd alive forever; random query ids also bypass cleanupQuery because no query owns them. Please pre-register the expected streams and reject unknown handshakes, or at least add a hard cap and timeout/reaper for pending producer-only slots.


/// Task reached a terminal state on the worker. Release worker-side
/// bookkeeping for it (TaskState/progress/future). Best-effort.
tryForgetTask(task);

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.

forgetTask is the only path that erases a terminal TaskState on the worker, but this best-effort call is followed by setTaskFinished even when it failed. A transient HTTP failure, or an initiator that disappears after the worker reports a terminal status, leaves the completed task entry, progress object, and future in StatelessTaskExecutor::tasks until worker shutdown. Please make terminal-task cleanup eventually guaranteed, for example with a worker-side TTL/reaper or a coordinator retry queue that keeps retrying forgetTask until it succeeds.


/// The fragment's read is bucketed; re-introducing the implicit count projection would count the
/// whole part per bucket. Keep it off so counts read the bucket's mark ranges.
optimization_settings.optimize_use_implicit_projections = false;

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.

The worker still leaves read-replacement optimizations such as normal projections and direct text-index reads enabled when it re-optimizes a serialized fragment. A bucketed ReadFromMergeTree is correct only while its distributed_read_bucket_count survives; worker-side projection or direct text-index rewrites can replace it with a fresh read that is not bucketed, so every reader bucket can scan the same projection/index result and duplicate rows or diverge from the coordinator-selected parts. The serialization guard only checks the step before this worker re-optimization, so it will not catch the replacement. Please disable these read replacements for distributed task fragments, or make the optimizers skip ReadFromMergeTree steps whose getDistributedReadBucketCount is nonzero.

/// Otherwise, when the counter sits at the limit, every re-enqueue
/// inside `checkStatusFunc` sees a full pipeline, all in-flight checks
/// then decrement to zero, and no further check is ever scheduled.
--in_flight_request_count;

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.

in_flight_request_count is updated after the status task is published to thread_pool, so a fast path such as checkCancelled throwing before the HTTP call, or a local getTaskStatus exception, can run the lambda and execute --in_flight_request_count while the counter is still zero. That leaves the tracker with a negative or otherwise stale in-flight count, so the max-in-flight guard stops bounding status requests and can schedule extra status/cleanup work during cancellation. Please increment before scheduleOrThrow publishes the job, and roll the increment back if scheduling throws.


void SourceHelloBody::readAfterVersion(ReadBuffer & in)
{
readStringBinary(query_id, in);

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.

readStringBinary still uses the default DEFAULT_MAX_STRING_SIZE and resizes the String before readStrict. The outer SourceHello body is capped to 64 KiB, but a peer can send protocol version 2 followed by a VarUInt string length in the hundreds of MiB; this line allocates that much for query_id before it notices the memory buffer ended. Since this is reachable from the exchange port before addConnection, please pass a max size bounded by the remaining hello body, or parse these fields with remaining-size checks before resizing.


/// The handshake runs synchronously on a blocking socket. Apply per-call
/// timeouts so a stalled peer cannot freeze the source startup indefinitely.
Poco::Timespan hello_timeout(StreamingExchangeProtocol::HELLO_TIMEOUT_SECONDS, 0);

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 sets a per-receive timeout. receiveHello then loops until the full SinkHello header and body arrive, so a peer can send one byte just under every HELLO_TIMEOUT_SECONDS and keep the worker thread in onStart indefinitely. The server side already uses an absolute Stopwatch deadline around the whole hello read in receiveAll; the source side needs the same absolute deadline while reading SinkHello.

</stateless_worker_client>

<distributed_query>
<streaming_exchange_port>9223</streaming_exchange_port>

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 config is installed globally for Linux stateless runs, so every server gets the same streaming_exchange_port. In install.sh --db-replicated, the config directory is copied into clickhouse-server1 and clickhouse-server2 without rewriting this file, so the extra servers try to bind 9223 after the main server already did. Server throws when all exchange binds fail, so database-replicated stateless runs can fail at startup even if the test never uses make_distributed_plan. Please either install this config only for distributed-plan tests or remove/rewrite the port in the cloned server configs.

const auto & config = context->getConfigRef();
String config_prefix = "distributed_query.temporary_files_storage";
if (config.has(config_prefix))
return config.getString(config_prefix + ".endpoint_subpath") + unique_temp_file_path;

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.

For type=local, ObjectStorageFactory roots the storage at the configured .path, but LocalObjectStorage::writeObject opens StoredObject.remote_path directly. Returning only endpoint_subpath + unique_temp_file_path here makes persisted exchange files go under tmp_sub_path/... relative to the server cwd instead of under distributed_query.temporary_files_storage.path such as ./local_object_storage/. This puts temp data outside the configured storage root and makes directory cleanup stop at the wrong root. Please include the configured local path in the object key, or build the StoredObject key through the local object storage key generator.

if (analyzed_result_ptr && analyzed_result_ptr->readFromProjection())
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED,
"make_distributed_plan does not support a distributed read from a projection");
if (!index_read_tasks.empty())

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 guard also needs to reject or preserve vector_search_parameters. tryUseVectorSearch stores that state on ReadFromMergeTree before tryMakeDistributedRead; after serialization, the worker restores only the bucket count and part names. The worker then builds its ranges without the coordinator's vector-search parameters while the rest of the optimized plan can still expect vector-search read hints such as _distance. Please either serialize vector_search_parameters for bucketed distributed reads or reject make_distributed_plan when they are set.

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR changes only experimental distributed-query execution: multi-stage distributed plans (gated behind the make_distributed_plan setting), the exchange server/handshake pool, stateless-worker thread-pool sizing, bucket-count validation, and query cancellation. The ClickBench and TPC-H benchmarks run ordinary single-node queries that never exercise any of these paths, so neither the flagged improvements (Q4, Q15, Q22, Q23, and TPC-H Q7/Q20) nor the Q16 regression can plausibly come from this change. All flagged deltas are downgraded to not-sure as run-to-run variance rather than real PR effects. No actionable performance signal here.

clickbench

⚠️ 5 inconclusive

Flagged queries (5 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 264 217 -17.8% <0.0001 PR only touches experimental distributed-query/exchange code, not the path Q4 runs; off-path variance.
⚠️ 15 not_sure 246 203 -17.5% <0.0001 Change is confined to make_distributed_plan/exchange plumbing; Q15's standard SELECT path is untouched.
⚠️ 16 not_sure 796 879 +10.4% <0.0001 Flagged regression but PR edits only distributed-plan/stateless-worker code Q16 never executes; treat as variance.
⚠️ 22 not_sure 334 250 -25.1% <0.0001 Off-path for this PR plus very noisy measurements (high spread both sides); not a PR effect.
⚠️ 23 not_sure 297 199 -33.0% <0.0001 Large clean delta but PR touches only distributed-query infra, not Q23's single-node path; build/run variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 7 not_sure 113 71 -37.2% <0.0001 Intrinsically flaky query and PR is distributed-only plumbing; delta not attributable to this change.
⚠️ 20 not_sure 248 128 -48.4% <0.0001 Noisy query with very high spread; PR's distributed-query code is off-path, so this is variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: c2ed0885-1ad2-46a0-b7df-92234e433cfa
  • MIRAI run: 905b1698-f18e-48de-940c-e8a50a3d82f2
  • PR check IDs:
    • clickbench_159620_1781518978
    • clickbench_159621_1781518979
    • clickbench_159631_1781518977
    • tpch_adapted_1_official_159649_1781518976
    • tpch_adapted_1_official_159657_1781518976

Comment on lines +794 to +809
std::thread([promise = std::move(task_promise), query_id = unique_query_id, task_description, ctx = context, is_cancelled = this->is_cancelled]() mutable
{
ThreadStatus thread_status;
/// The task attaches its own query context and thread group inside executeTask (matching
/// the worker path), so this thread is intentionally left detached from the initiator group.

try
{
executeTask(query_id, task_description, ctx, is_cancelled);
promise.set_value();
}
catch (...)
{
promise.set_exception(std::current_exception());
}
}).detach();

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.

This looks slightly unsafe, but it is used only in unit tests right?


const auto & table_expression_modifiers = query_info.table_expression_modifiers;

UInt8 flags = 0;

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.

ReadFromMergeTree fragments also need to carry the filter DAG used for mark-range analysis. The worker deserialize path below creates a fresh SelectQueryInfo and only restores table modifiers, row_level_filter, prewhere_info, bucket count, and part names; it never restores filter_actions_dag. For a bucketed read the worker then calls selectRangesToRead, and that path passes query_info_.filter_actions_dag.get() into buildIndexes, so the pinned parts are reselected without the coordinator's WHERE predicate. Selective distributed reads can therefore scan all marks in the pinned parts and trip max_rows_to_read / max_rows_to_read_leaf even when the coordinator-selected ranges were within the limit. Please serialize the storage filter DAG, or serialize the exact selected mark ranges instead of only part names.

stage->tasks_to_check.clear();
}

for (auto & task : tasks_to_cancel)

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 cleanup loop is still serial across all remote tasks, and each cancelTask can spend its full HTTP retry/timeout budget before the next task is even told to stop. The following loop then does up to ten getTaskStatus cleanup polls per task as well. A cancelled query with many fragments, or one slow/unreachable worker per fragment, can keep KILL QUERY SYNC, client-disconnect cleanup, timeout cleanup, or server shutdown blocked for minutes while query resources remain held. Please issue the cancel requests and terminal polls concurrently, or enforce one global cleanup deadline with short no-retry cleanup calls.

}
LOG_TRACE(getLogger("TemporaryFilesInObjectStorageCleaner"), "Removing temporary files at path {} : [{}]",
object_storage_path, fmt::join(temporary_files, ", "));
object_storage->removeObjectsIfExist(all_objects);

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 removes persisted exchange objects unconditionally when the final plan resources are destroyed, but remote cancellation can leave tasks running: TaskTracker::cancel logs and keeps any task for which waitForTaskTerminal returns false. Those live fragments can still be writing or reading the same persisted exchange files while this cleaner deletes them, which can turn cancellation/failure cleanup into worker-side exceptions or leave objects recreated after cleanup. Please defer or skip persisted temp-file cleanup unless all remote tasks reached a terminal state, or move it behind a worker-side lease/GC mechanism.

@groeneai groeneai mentioned this pull request Jun 12, 2026
static constexpr auto DBMS_MERGE_TREE_PART_INFO_VERSION = 1;

static constexpr auto DBMS_QUERY_PLAN_SERIALIZATION_VERSION = 0;
static constexpr auto DBMS_QUERY_PLAN_SERIALIZATION_VERSION = 1;

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.

DBMS_QUERY_PLAN_SERIALIZATION_VERSION is bumped, but the negotiated version is not actually available to step serializers or deserializers. QueryPlan::serialize only writes min(max_supported_version, DBMS_QUERY_PLAN_SERIALIZATION_VERSION); IQueryPlanStep::Serialization has no version, so a changed step such as ReadFromMergeTree::serialize still writes the new layout even when Connection::sendQueryPlan is downgrading for a v0 server. The reverse path also accepts a v0 plan but current step deserializers parse the v1 layout, and pre-cached plans bypass per-connection downgrade entirely. In a rolling upgrade, serialized query plans sent to parallel replicas can be rejected or misparsed. Please thread the negotiated query-plan version through step serialization/deserialization and branch the changed layouts, or disable serialized-plan shipping across version mismatch.

}
catch (...)
{
running_tasks.cancelAndForgetUntracked(task_info);

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.

sendTask can fail while the original start request is still in flight on the worker. This cleanup then sends cancel/forget, but waitForTaskTerminal treats Unknown task as terminal; if those cleanup requests overtake the delayed start, the worker can register and run the task afterwards with no tracker entry, so later cancellation and temp-file ownership are lost. Please make cancel-before-start leave a worker-side tombstone/pending cancellation for this task_id, or keep retrying cleanup until the start request is known not to have been accepted.

davenger and others added 3 commits June 14, 2026 23:01
…t-106020-multistage-distributed

# Conflicts:
#	src/Processors/Transforms/ScatterByPartitionTransform.cpp
ContextMutablePtr query_context = Context::createCopy(global_context);
query_context->makeQueryContext();
{
ClientInfo client_info;

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.

Worker fragments need to preserve the initiator ClientInfo before deserializing and executing the serialized plan. ActionsDAG::deserialize rebuilds functions from ctx.context, and functions such as currentUser capture context->getClientInfo().initial_user when the function object is created. This worker context only sets query ids, so a row policy or expression like tenant = currentUser() inside a remote fragment is evaluated as the worker/global user instead of the user who started the query, producing wrong filtering/results. Please carry the initiator client info (at least current_user, initial_user, authenticated_user, current database/address/quota key) in the task description and install it on query_context before plan/action DAG deserialization.

@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.40% 92.30% -0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 2829/3317 (85.29%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@CheSema CheSema self-assigned this Jun 15, 2026
@davenger
davenger enabled auto-merge June 15, 2026 14:53
@davenger

Copy link
Copy Markdown
Member Author

@davenger
davenger added this pull request to the merge queue Jun 15, 2026
Merged via the queue into master with commit 7eec85d Jun 15, 2026
805 of 814 checks passed
@davenger
davenger deleted the revert-107122-revert-106020-multistage-distributed branch June 15, 2026 15:25
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants