Repository navigation
Revert "Revert "Multistage distributed queries" (#106020) — fixes ASan heap corruption on master" - #107146
Conversation
…n heap corruption on master"
|
Workflow [PR], commit [340e648] Summary: ⏳
AI ReviewSummaryThis revert reintroduces the multi-stage distributed query executor, stateless worker protocol, bucketed Findings❌ Blockers
Tests
Performance & SafetyThe Cloud performance report is off-path because Final VerdictStatus: ❌ Block Minimum required actions: preserve initiator identity/context on workers before deserialization, make query-plan serialization versioned across distributed tasks, serialize or reject every |
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…hecks Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
| @@ -0,0 +1,68 @@ | |||
| -- Tags: no-old-analyzer | |||
There was a problem hiding this comment.
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]; |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
|
||
| void SourceHelloBody::readAfterVersion(ReadBuffer & in) | ||
| { | ||
| readStringBinary(query_id, in); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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> |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (5 of 43)
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_officialFlagged queries (2 of 22)
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
|
| 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(); |
There was a problem hiding this comment.
This looks slightly unsafe, but it is used only in unit tests right?
Co-Authored-By: Claude Fable 5 <[email protected]>
|
|
||
| const auto & table_expression_modifiers = query_info.table_expression_modifiers; | ||
|
|
||
| UInt8 flags = 0; |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Fable 5 <[email protected]>
| 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; |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
…ks and memory Co-Authored-By: Claude Fable 5 <[email protected]>
…t-106020-multistage-distributed # Conflicts: # src/Processors/Transforms/ScatterByPartitionTransform.cpp
…r merge Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
| ContextMutablePtr query_context = Context::createCopy(global_context); | ||
| query_context->makeQueryContext(); | ||
| { | ||
| ClientInfo client_info; |
There was a problem hiding this comment.
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.
LLVM Coverage Report
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 |
|
Tests are green https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107146&sha=340e648dcae581d1d4cfe2f6671eceea70735472&name_0=PR |
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_sizeto 128 (from default 1000). This PR does not change this setting.Also includes follow-up fixes for
#106906
#107029
Version info
26.6.1.825