Skip to content

DO NOT MERGE: ASan heap corruption repro — with distributed queries - #107161

Closed
davenger wants to merge 8 commits into
masterfrom
corruption-repro-with-distributed
Closed

davenger wants to merge 8 commits into
masterfrom
corruption-repro-with-distributed

Conversation

@davenger

Copy link
Copy Markdown
Member

Related: #107122
Related: #107146
Related: #107160

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Draft, never to be merged: the second half of the corruption repro experiment — the #107146 branch (multistage distributed queries + cancellation deadlock fixes) plus the same two crash-amplifying settings as #107160 (the plain-master repro PR).

How to read the results across the two PRs: crashes in both mean the bug is in shared infrastructure, not the distributed feature; crashes only here mean the feature is involved, and the enlarged ASan quarantine should yield a heap-use-after-free report that names the actual buggy code.

🤖 Generated with Claude Code

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [27f347e]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
Server died FAIL cidb, issue
02835_drop_user_during_session UNKNOWN cidb
02835_drop_user_during_session UNKNOWN cidb
02835_drop_user_during_session UNKNOWN cidb
02835_drop_user_during_session UNKNOWN cidb
02835_drop_user_during_session UNKNOWN cidb
Stateless tests (amd_debug, flaky check) FAIL
04097_distributed_join_kinds FAIL cidb
04097_distributed_join_kinds FAIL cidb
Scraping system tables FAIL cidb
Unit tests (asan_ubsan, function_prop_fuzzer) FAIL
FunctionsStress.stress FAIL cidb, issue
AllTests FAIL cidb
Fast test (arm_darwin) ERROR
Build (amd_release) ERROR
Build (arm_release) ERROR
Build (amd_darwin) ERROR
Build (arm_darwin) ERROR
Build (arm_v80compat) ERROR
Build (amd_freebsd) ERROR

AI Review

Summary

This PR adds an experimental multi-stage distributed query execution path with stateless workers, streaming/persisted exchanges, distributed plan splitting, and tests. I found multiple unresolved correctness, cancellation, compatibility, and security issues in the new distributed control plane and plan serialization; these need fixes before this can be considered mergeable.

Findings

❌ Blockers

  • [src/Server/DistributedQuery/ExchangeConnections.cpp:41] The streaming exchange listener accepts a producer socket for any query_id/stream pair before the server knows that stream belongs to a running query. Because SourceHello is unauthenticated and unknown streams create retained FutureConnection slots, a reachable host can leak file descriptors/memory indefinitely or preempt a real stream if ids are known. Reject unknown streams by authenticating the handshake and/or pre-registering expected streams before accepting producers.

  • [src/Server/StatelessWorker/StatelessTaskExecutor.cpp:195] StatelessTaskExecutor::forgetTask erases the only TaskState without proving the task is terminal. A reordered or malicious forget makes later cancel/get_status return UnknownTaskId, and shutdown no longer waits for the running fragment, so it can keep writing exchanges or temporary files with no owner. Make forgetTask fail/defer while the future is not ready, or cancel and wait before erasing.

  • [src/Storages/SelectQueryInfo.cpp:63] PrewhereInfo::serialize writes need_filter unconditionally, but IQueryPlanStep::Serialization does not carry the negotiated QueryPlan serialization version. QueryPlan::serialize(max_supported_version) can still write a version 0 header for older peers, and the extra byte corrupts the rest of the stream for a version 0 reader. Propagate the negotiated plan version into step serialization and gate this field, or reject version 0 peers for plans containing version 1 fields.

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:4772] Projection reads are rejected only when distributed_read_bucket_count > 0. A non-bucket ReadFromMergeTree can still be serialized after projection optimization, but deserialization reconstructs a read from the base table name and columns, not the projection identity/snapshot. That can read the wrong source or fail when downstream projection actions expect projection columns. Reject any analyzed_result_ptr->readFromProjection before serialization unless projection identity and snapshot are serialized and restored.

⚠️ Majors

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:771] Local cleanup only wakes InMemoryExchange waiters. If a local fragment throws while sibling fragments are scanning, sleeping, or otherwise outside an exchange, is_cancelled remains false and cleanup waits for every future instead of stopping them promptly. Set *is_cancelled = true before waking exchanges and waiting for task futures.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1154] The worker cleanup RPC still gates stage completion: tryForgetTask runs before setTaskFinished, and forgetTask uses the normal long HTTP timeout/retry budget. A terminal worker task can therefore keep waitForStage blocked solely on best-effort cleanup. Mark terminal status first and run forget on a bounded best-effort path.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1300] TaskTracker::enqueueGetStatus increments in_flight_request_count after scheduling the callback. A fast callback can decrement from zero and recurse before the slot is reserved, bypassing max_in_flight_requests. Reserve the slot before scheduleOrThrow and roll it back if scheduling throws.

  • [src/QueryPipeline/DistributedPlanExecutor.cpp:1391] sendTask is synchronous while ReadFromDistributedPlanSource::tryGenerate holds executor_mutex, and the task is not tracked until the request returns. Cancellation during remote startup cannot enter cleanup or cancel a worker that has already accepted the task, so KILL QUERY SYNC can wait for the start RPC timeout while the fragment keeps running. Make startup cancellable/bounded or track the task before the start request can block.

Tests
  • ⚠️ Add focused tests for rejecting unauthenticated/unknown streaming producers and for not retaining orphan FutureConnection slots.
  • ⚠️ Add cancellation tests for local fragment exceptions, remote startup cancellation, and forget ordering so worker fragments cannot outlive their owner.
  • ⚠️ Add a mixed-version serialization test or explicit version-gating test for the PrewhereInfo::need_filter field.
  • ⚠️ Add a projection-read distributed-plan test that proves projection reads are either rejected consistently or round-trip with projection identity intact.
Final Verdict

Status: ❌ Block

Minimum required actions: fix the stream registration/authentication issue, make forget and cancellation ordering ownership-safe, fix plan serialization versioning, and reject or correctly serialize projection reads before enabling this path.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 11, 2026
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.

This accepts and stores a producer socket for any query_id/stream pair before the server knows that such a stream belongs to a running query. Because the streaming exchange listener is unauthenticated, any host that can reach the configured listen address can send valid SourceHello packets with unique ids and make pending_connections retain a FutureConnection, eventfd, and socket indefinitely; no cleanupQuery or removePendingStreams will ever name those fake queries. That gives the new listener an unbounded FD/memory DoS path, and the same "first producer wins" behavior can also preempt a real stream if the ids are known. Please authenticate the handshake and/or pre-register expected streams so unknown producers are rejected instead of creating rendezvous 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.

This cleanup RPC is best-effort, but it currently gates stage completion: setTaskFinished is not called until forgetTask returns, and forgetTask uses the normal long HTTP timeouts/retries. A worker task that has already reported Finished can therefore keep waitForStage blocked solely because the cleanup request is slow, and a Failed status is also delayed before it is surfaced. Please mark the terminal status first (or at least propagate failures first) and run forget on a bounded/best-effort path that cannot delay the stage result.

/// task stuck in InMemoryExchange::getChunk never returns. The exchanges are not removed here:
/// the result reader still drains final_result after the driver finishes; removal happens when
/// the query pipeline is destroyed (see makeInMemoryExchangesCleaner).
InMemoryExchanges::instance()->cancelQuery(toString(unique_query_id));

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.

cleanup also runs after a local task throws, not only after onCancel. In that exception path the shared is_cancelled flag is still false, so this only wakes tasks blocked in InMemoryExchange; sibling tasks that are scanning, sleeping, or otherwise executing outside an exchange keep running while cleanup waits for every future. That can turn the first fragment exception into a long wait or hang instead of promptly failing the query. Set *is_cancelled = true before waking exchanges and waiting on the task futures, so the executor cancel callback stops all local fragments.

LOG_DEBUG(logger, "Sending task {} to {}", task_info.task_id, task_info.endpoint_uri);
try
{
sendTask(task_info.endpoint_uri, task_info.task_id, task_description, unique_temp_file_path, context);

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 is synchronous and can spend up to the HTTP send/receive timeout here while ReadFromDistributedPlanSource::tryGenerate is holding executor_mutex. During that window onCancel can set the flag, but it cannot enter cleanup or send cancel/forget for a task that the worker may already have accepted, because the task is not tracked until this call returns. A KILL QUERY SYNC during remote startup can therefore wait for the start RPC timeout while the worker keeps running the fragment. The start path needs to be cancellable/bounded, or the task must be tracked early enough that cleanup can cancel it while the start request is in flight.

--in_flight_request_count;
enqueueGetStatus();
});
++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.

The in-flight slot is reserved after scheduleOrThrow, but the scheduled callback can run immediately. For a fast status response it can execute --in_flight_request_count while the counter is still zero, recurse into enqueueGetStatus with a negative count, and bypass the max_in_flight_requests gate. That defeats the tracker’s concurrency bound and can drive extra scheduleOrThrow calls from inside the tracker thread. Reserve the slot before scheduling, and roll it back if scheduling throws.

if (it == tasks.end())
return Result::UnknownTaskId;

tasks.erase(it);

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.

forget drops the only TaskState without checking whether the task is terminal. If a cleanup request arrives out of order, is retried against the wrong task id, or is sent by another authenticated interserver caller while the fragment is still running, later cancel/get_status see UnknownTaskId and shutdown no longer has this task in the map to cancel or wait for it. The task thread can then continue writing exchange streams or temporary files with no owner. Please make forgetTask fail or defer while completion_future is not ready, or cancel and wait before erasing the task state.

if (deferred_row_level_filter || deferred_prewhere_info)
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED,
"make_distributed_plan does not support a distributed read with deferred FINAL filters");
if (analyzed_result_ptr && analyzed_result_ptr->readFromProjection())

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 rejection only runs for bucketed reads, but a non-bucket ReadFromMergeTree can still be serialized after the second optimization pass has replaced it with a projection read. The serialized form records only the base table name and column list; deserialize reconstructs the step with MergeTreeDataSelectExecutor on the base table snapshot, not the projection snapshot/name. For aggregate or normal projections whose columns/actions do not match the base table, the remote fragment will either read the wrong source or fail while building the downstream projection steps. Please reject any analyzed_result_ptr->readFromProjection() before serialization unless the projection identity and snapshot are serialized and restored.

prewhere_actions.serialize(ctx.out, ctx.registry);
writeStringBinary(prewhere_column_name, ctx.out);
writeBinary(remove_prewhere_column, ctx.out);
writeBinary(need_filter, ctx.out);

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.

QueryPlan::serialize(max_supported_version) can still negotiate and write version 0 for an older remote server, but IQueryPlanStep::Serialization does not carry that negotiated version, so this new field is written unconditionally even when the stream header says the old format. An older server will deserialize PrewhereInfo without consuming need_filter, leaving the extra byte to be read as the next field and corrupting the rest of the serialized plan. Please propagate the plan serialization version into step serialization/deserialization and either omit/default need_filter for version 0, or refuse to serialize plans containing version-1-only fields to a version 0 peer.

@davenger davenger added the ci-force-all Do not skip any jobs when running label Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-force-all Do not skip any jobs when running pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant