Skip to content

Fix heap-use-after-free after a streaming read round whose sort spilled to disk is torn down - #125158

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-streaming-spilled-round-teardown-uaf
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-streaming-spilled-round-teardown-uaf

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Description

Related: #112320. Found by the AST fuzzer (amd_tsan): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120758&sha=6829c431b4a3e2819e0f270d0ed168e8851ec545&name_0=PR&name_1=AST%20fuzzer%20%28amd_tsan%29

MergeTreeCommitOrderSource retires a finished STREAM read round by returning the round's Pipe processors in to_remove. When the round's commit-order sort spills, MergeSortingTransform::updatePipeline adds a merging transform and temporary-file source/sink connected to new ports of the MergeSortingTransform itself. Those are not in the Pipe, so the executor destroyed the sort and kept them in the pipeline, still connected to its freed ports. Any later reader that follows a peer reads freed memory; the fuzzer hit it through processors_profile_log of a cancelled query (failed queries are logged there since #121503).

The V1 ExecutingGraph now records which node added each runtime processor. A new removal group takes in the processors its members added earlier, and when a processor pending removal expands, its new processors join its group and increment not_finished.

Validation: on master the new test gives the CI heap-use-after-free under ASan (freed by ~SortingTransform from the round teardown) and fails 17/17 randomized debug runs. With only the increment it still fails 10/10: the sort spills while it consumes, before the round is queued for removal. With the fix it passes 50/50 (debug), and the Processors.* gtests pass.

Raw timed log of the failing query (CI server log)
2026.10.11 04:36:38.916862 [ 1424 ] {e79e1769-ad5c-401e-b055-86042716eac4} <Trace> MergeSortingTransform: Will dump sorting block (123.49 KiB, limit: 97.66 KiB) to disk (query memory: 0.00 B, limit: 0.00 B)
2026.10.11 04:36:39.107364 [ 1424 ] {e79e1769-ad5c-401e-b055-86042716eac4} <Information> MergeSortingTransform: There are 7 temporary sorted parts to merge
2026.10.11 04:36:44.059990 [ 1424 ] {e79e1769-ad5c-401e-b055-86042716eac4} <Trace> system.query_log (707f305d-1fb4-489c-ad77-894c9479dd06) (SelectExecutor): Reading 1 ranges in order from part 202610_646_646_0, approx. 29 rows
2026.10.11 04:36:48.820915 [ 188 ] {BgSchPool::a9f969d2-ae44-4878-b287-21fbdc076a0f} <Debug> CancellationChecker: Cancelling the task because of the timeout: 10000000 us, query_id: e79e1769-ad5c-401e-b055-86042716eac4

The read round that spilled was retired before the second round (04:36:44) started; the exception callback then logged the processors profile and read the freed port.

🤖 Generated with Claude Code


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

…that added them

`MergeTreeCommitOrderSource` retires a finished read round of a `STREAM`
query by returning the round's `Pipe` processors in `to_remove`. When the
round's commit-order sort spills, `MergeSortingTransform::updatePipeline`
adds merging and temporary-file processors connected to new ports of the
`MergeSortingTransform` itself. They are recorded only in the executor
graph and the shared processors list, never in the round's `Pipe`, so the
round teardown destroyed the sort and left them in the pipeline, still
connected to its freed ports. The processors profile log, which runs for
failed queries too since ClickHouse#121503, then read freed memory through
`Port::getProcessor` (heap-use-after-free found by the AST fuzzer).

`ExecutingGraph` now records which node added each runtime processor and
extends every removal group with the processors added (transitively) by
its members, including ones added after the group was created.
`removePendingGroup` throws `LOGICAL_ERROR` when a removed processor is
still connected to a processor that stays, so a remover that leaves a
dangling connection fails at removal instead of at a later reader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test can pass without the spilled round being retired before the 2 s limit (05361_...sql:13-17) DISAGREE Measured query start to round teardown: 0.007-0.035 s debug (94 runs), 0.018-0.121 s ASan (43 runs), so the margin is at least 16x. If it ever happened, the result would be a vacuous pass, not a false pass on a run that retired the round. Asserting retirement would make the same rare event a flaky failure.
2 ⚠️ No test exercises the late join (expansion of a processor already pending removal) or the new LOGICAL_ERROR check DISAGREE The check is proven live by deletion: without the closure it aborts on the first run with Processor MergeSortingTransform_10 ... is removed from the pipeline while it is still connected to MergingSortedTransform_15. Neither branch is reachable from SQL with the only in-tree remover: a round is retired only after its output finished, which needs every sort in it finished. Only a gtest could cover them; I can add one to gtest_update_pipeline.cpp, or drop the late join, if preferred.
3 💡 The parent-id oracle would also pass if no processors_profile_log rows were written noted Live today: the oracle is red on master 17/17.
4 💡 Node::expanded_from can keep the address of an already removed node noted Only compared, never dereferenced; such a node is still pending in its own group, which the closure skips.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261011-051000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test's SQL on a master ASan build gives the CI report 1/1 (heap-use-after-free READ in Port::getProcessor from getProcessorsProfileLogInfo); on a master debug build its oracle is red 17/17 randomized runs.
b Root cause explained? The STREAM round teardown removes the round's Pipe processors, but the processors the spilled MergeSortingTransform added at run time are not in that Pipe; they stay in the pipeline connected to the destroyed sort's ports, and the processors profile log follows those ports.
c Fix matches root cause? Yes. The executor, which is the only component that knows what an expansion added, now removes those processors with the processor that added them. No reader-side workaround.
d Test intent preserved / new tests added? New SQL test 05361_streaming_queries_spilled_round_teardown: positive control (the round spilled) plus a structural oracle (every logged parent is a processor of the query).
e Both directions demonstrated? Yes. Master and a same-tree build without the new logic: red (ASan UAF 1/1, debug 17/17 and 10/10). Fix: 50/50 debug, 20/20 ASan, no sanitizer report.
f Fix is general across code paths? Yes. Parentage is generic: it covers every runtime expander inside a removed group (external sort, aggregation, external distinct, delayed and lazy sources) and every reader of the pipeline's processors that dereferences peers.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for types (executor graph lifetime); 50 runs with randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. A remover that leaves a dangling connection now gets LOGICAL_ERROR at removal instead of a later use-after-free; no in-tree remover does that.
i Invariants and contracts preserved? No processor left in the pipeline is connected to one the executor destroyed. A removal group is removed only after all its members, including the added ones, finished. The new check runs before anything is mutated.

Session id: cron:clickhouse-impl-slot-6:20261011-040700

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [acd3f55]

Summary: ✅


AI Review

Summary

PR #125158 removes runtime-expanded processors with their owning processor, preventing dangling port references when a spilled STREAM read round is retired. Reviewed head acd3f55d4fd30fabb010aabbce5a4a365f450e71, the full diff, surrounding execution and removal paths, and all prior discussion. No actionable findings remain. The added 05361_streaming_queries_spilled_round_teardown regression passes in the exact-head Fast test report. Validation used source inspection and existing CI evidence; no local build or tests were run.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 11, 2026
@Michicosun Michicosun self-assigned this Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 476f865

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR (it changes pipeline executor teardown only; 147 of 147 reruns pass): UNKNOWN_TABLE for the initiator-local _materialized_cte_c_* table when a reused MATERIALIZED CTE is read through parallel replicas with a local plan. 101 PRs and 18 master runs in 7 days #123121 (mine, open)
Mergeable Check, PR praktika rollups of the row above #123121 (mine, open)

All 165 check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261011-100007

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

That is too complex, we just need to increment not_finished in the removal group of the expanded processor.

Drop the removal-time connection check and the separate group-node set.
When a processor that is already pending removal expands, its new
processors join its removal group and increment `not_finished`. When a
removal group is created, the processors its members added earlier join
it as well: a spilling sort in a `STREAM` read round expands while it
consumes, before `MergeTreeCommitOrderSource` queues the finished round
for removal, so the increment alone does not cover this case (the new
test still fails 10/10 with only the increment).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Simplified in acd3f55: the LOGICAL_ERROR check and the extra node set are removed, and what remains includes the increment you suggested: a processor pending removal that expands adds its new processors to its removal group and increments not_finished.

The increment alone does not cover this case: the sort spills while it consumes, so it expands before the round is queued for removal, when it has no removal group yet. Log of the test query on a build with only the increment:

2026.10.23 15:31:16.665621 [ 877663 ] <Trace> MergeSortingTransform: Will dump sorting block (846.91 KiB, limit: 1.00 B) to disk (query memory: 1.51 MiB, limit: 0.00 B)
2026.10.23 15:31:16.667759 [ 877663 ] <Information> MergeSortingTransform: There are 1 temporary sorted parts to merge
2026.10.23 15:31:16.669423 [ 877663 ] <Test> MergeTreeCommitOrderSource: Finished read round #1
2026.10.23 15:31:16.669432 [ 877663 ] <Test> MergeTreeCommitOrderSource: Tear down finished read round sub-pipeline

With only the increment the new test fails 10/10, so a new removal group also takes in the processors its members added earlier (Node::expanded_from, one pass over nodes). With both it passes 50/50, and the Processors.* gtests pass.

@Michicosun

Copy link
Copy Markdown
Member

Will wait till executors v2 lands so we can fix in both places.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

OK, I'll leave it open until then. One data point for the timing: AST fuzzer keeps failing on this dangling-port read in IProcessor::getProcessorsProfileLogInfo on unrelated PRs, 6 PRs since Oct 11, the latest on Nov 4 (TSan, MSan, debug, SIGSEGV, ASan). If you prefer to merge the V1 part first, it is ready on acd3f55 with green CI; otherwise I can add the V2 part here once V2 lands.

This branch has not been deployed

No deployments
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

2 participants