Skip to content

Fix stack-use-after-scope in MergeTreeData::loadStatisticsOfPartsInParallel when scheduling a loader job throws - #127911

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-load-statistics-parallel-use-after-scope
Oct 31, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-load-statistics-parallel-use-after-scope

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127895
Related: #126625

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

loadStatisticsOfPartsInParallel (added in #126625) declares std::optional<ThreadPool> pool before the load_parts lambda, and the pool jobs captured load_parts by reference. When scheduleOrThrowOnError throws for a later job (thread creation failure, CANNOT_SCHEDULE_TASK), unwinding destroys load_parts before ~ThreadPool joins the jobs that are still running it, so they read a dead stack object.

Found by Stress test (arm_asan_ubsan) on master: report (READ of size 8 in the loop condition of load_parts, object 'load_parts' (line 1276)).

The jobs now capture a copy of load_parts. The closure holds only references to pool, to objects declared before it and to the caller's arguments, so nothing a job reads is destroyed before the join. Behaviour is otherwise unchanged.

The new gtest MergeTreeData.LoadStatisticsOfPartsInParallelWhenSchedulingThrows enables CannotAllocateThreadFaultInjector from the first loaded part and keeps that job running for 1 s, so the next scheduling throws while it runs. The sleep must outlast the throw itself: the exception message of a failed thread start carries a symbolized stack trace, which takes 0.1-0.5 s under ASan. Under ASan the test aborts with the same report as CI in 20/20 separate runs without the fix and passes 200/200 with it; 05407_statistics_parallel_load passes 50/50 with random settings.

Not in any release: #126625 is not in 26.10.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.962-master (included in 26.11 and later)

…eduling throws

`std::optional<ThreadPool> pool` is declared before the `load_parts` lambda
(the lambda names `pool`), and the pool jobs captured `load_parts` by
reference. When `scheduleOrThrowOnError` throws for a job after the first
(thread creation failure, `CANNOT_SCHEDULE_TASK`), unwinding destroys
`load_parts` before `~ThreadPool` joins the jobs that are still inside it,
and they read the dead closure. Found by Stress test (arm_asan_ubsan) on
master, STID 4822-4aba.

The jobs now capture a copy of `load_parts`. Its members are references to
objects declared before `pool` and to the caller's arguments, so nothing a
job reads dies before the join.

The gtest makes the first loaded part enable `CannotAllocateThreadFaultInjector`
and keep its job running for 1 s, so the next scheduling throws while it
runs. The sleep has to outlast the throw: a failed thread start builds an
exception message with a symbolized stack trace, 0.1-0.5 s under ASan, so
50 ms let the job finish before the frame unwound. Under ASan it aborts in
20/20 runs without the fix and passes 200/200 with it.

Closes ClickHouse#127895

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding).

# Sev Finding Verdict Evidence / action
1 ⚠️ The gtest's overlap relies on the 1 s sleep outlasting the failed scheduling's symbolized exception (gtest_load_statistics_of_parts_in_parallel.cpp:25-52) DISAGREE The throw takes 87-107 ms warm, about 0.5 s first in a process; 20/20 unfixed launches abort with the CI report. A slow run can only miss the bug, never fail on the fixed code; a deterministic overlap needs a product failpoint.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261027-030100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ASan build, unit_tests_dbms --gtest_filter='MergeTreeData.LoadStatisticsOfPartsInParallelWhenSchedulingThrows' aborts in 20/20 separate runs without the fix, with the CI report's frames (MergeTreeData.cpp:1278:17 from the job at :1340:25) and object 'load_parts' (line 1276).
b Root cause explained? Yes. pool is declared before load_parts, and the jobs captured load_parts by reference. When scheduling a later job throws, unwinding destroys load_parts before ~ThreadPool joins the jobs still running it.
c Fix matches root cause? Yes. The jobs capture a copy of load_parts, whose members are references to objects that outlive the join. No guard, no try/catch.
d Test intent preserved / new tests added? New gtest. A SQL test cannot inject a thread scheduling failure.
e Both directions demonstrated? Yes. Without the fix: 20/20 ASan aborts. With the fix: 0/20 and --gtest_repeat=200 200/200 passed (ASan), 50/50 passed (debug).
f Fix is general across code paths? Yes. The jobs read nothing else declared after pool, and only the scheduling loop can throw while jobs run. The sibling filterPartsByPrimaryKeyAndSkipIndexes already declares everything its jobs read before its pool.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for types (a lifetime bug, independent of data). The paths with max_threads <= 1 or a single part to load schedule no jobs and are unchanged; 05407_statistics_parallel_load passes 50/50 with random settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change.
i Invariants and contracts preserved? Yes. Everything a job reads now outlives the pool's destructor on the exception path too. The order of parts, the abandonment via pool->isFinished(), and which exception is rethrown are unchanged.

Session id: cron:clickhouse-impl-slot-7:20261027-013600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @CurtizJ, could you review this and add the can be tested label so CI runs? The jobs in loadStatisticsOfPartsInParallel captured load_parts by reference, but it is declared after pool, so when scheduling a later job throws it is destroyed before ~ThreadPool joins the running jobs (stack-use-after-scope in Stress test (arm_asan_ubsan)); the jobs now capture a copy.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c029c4c]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

The PR fixes a stack-use-after-scope in MergeTreeData::loadStatisticsOfPartsInParallel by capturing load_parts by value in each scheduled job, and adds a focused scheduling-failure regression test. No actionable correctness or safety findings remain at c029c4c6510168296caffdd301248b4838b2b1d3.

Missing context / blind spots
  • ⚠️ No local build or test binary is available, and the fetched CI reports do not expose a result for the new gtest. Regression evidence comes from the author's documented ASan runs: 20/20 failures without the fix and 200/200 passes with it. A CI log for the focused gtest would independently confirm those results.
Final Verdict

Status: ✅ Approve. No changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c029c4c

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 profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 282 of 286 runs since 2026-10-26 22:00 UTC are red, on 236 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

The first run of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-203012

@alexey-milovidov alexey-milovidov self-assigned this Oct 31, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 31, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Oct 31, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, in the original PR, what did we miss in the code review or the original coding instructions to prevent this issue to happen, and how can we prevent it in general? Should we provide more specific instructions in our code review skill? Reflect on this and send a PR with general development process improvements.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Coding. The bug came with the last review round of #126625, d05d94d. It moved the job body into the named closure load_parts, so that one part can be loaded inline. The closure checks pool->isFinished() (added in 06d59cd for the finding about claiming parts after scheduling throws), so it has to be declared after pool, and the jobs capture it by reference through [&]. The comment above pool states the right rule ("Declared after the variables above to be destroyed first: its destructor joins the jobs that still use them when scheduling throws"), but it was applied to the data variables only, not to the closure, which is also a local the jobs use. [&] hides which locals a job uses.

Review. The Code Review job approved the final head d4e8e7f with "the prior findings are addressed". Its first review had traced exactly this path (a later scheduleOrThrowOnError throws, unwinding destroys pool, its destructor joins the running jobs), but asked only what the jobs do after that, not what they still read. The review skill has only the general gate about exceptions and "async work already in flight", and the summary of the last re-review covers only the earlier findings, not the new code of that round.

Tests. Thread creation failures are injected only in Stress tests, with probability 0.0001 (tests/config/config.d/cannot_allocate_thread_injection.xml), so the 6 Stress test jobs on the final head were green. Since 2026-10-27 it has failed 8 Stress test runs, 3 of them on master.

Known class. #95818 fixed the same bug class across 20 files (merged 2026-02-10) and added a warning with this exact shape to src/Common/threadPoolCallbackRunner.h (WRONG: [&my_lambda, ...] { my_lambda(); }). It is a comment on ThreadPoolCallbackRunnerLocal, while this code uses ThreadPool directly, and neither .claude/CLAUDE.md nor the review skill mentions it.

Prevention. Yes, the review skill should have a specific check. I'll send a PR with:

  1. .claude/skills/review/SKILL.md: a triggered check for code that schedules jobs on other threads. List every local a job uses, including a lambda or std::function it calls, and check that each is destroyed after the join on every path after the first schedule: a later schedule throws, the calling thread throws, wait rethrows. Locals are destroyed in reverse order of declaration, so whatever joins the jobs (a pool, a runner, a guard) must be declared after all of them, and a closure that refers to the pool must be captured by value. A green CI is no evidence for this path.
  2. Same file: a review of a later revision reviews the changes since the last reviewed revision as new code, not only whether the earlier findings are resolved.
  3. .claude/CLAUDE.md, for authors: a job must not capture by reference anything that can be destroyed before it is joined; capture by value, or declare everything it uses before whatever joins it.

I'll post the link here.

Merged via the queue into ClickHouse:master with commit 5332ba8 Oct 31, 2026
524 of 528 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 Oct 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Sent #128365. One change from the list above: I dropped "wait rethrows" as an exit, because ThreadPool::wait and waitForAllToFinishAndRethrowFirstError join all jobs before rethrowing; the rule lists an early return instead.

syoshida20 pushed a commit to syoshida20/ClickHouse that referenced this pull request Nov 1, 2026
Add three rules to the agent instructions:

- `.claude/skills/review/SKILL.md`, triggered expansion "Jobs on other
  threads": list everything a scheduled job uses, including a lambda or
  `std::function` it calls, and check that each outlives the join on
  every exit after the first schedule (a later schedule throws, the
  scheduling thread throws while doing its own share, an early return).
  The joiner is declared after everything the jobs use, and a closure
  that refers to the pool is captured by value.
- Same file, "A fix is new code": a re-review covers the code changed
  since the previous review, including the fixes for earlier findings,
  with the same gates as the first review.
- `.claude/CLAUDE.md`: the same lifetime rule for authors.

The last round of ClickHouse#126625 moved the job body of
`loadStatisticsOfPartsInParallel` into a closure declared after the
pool, called by the jobs through `[&]`. A later schedule that threw
destroyed the closure before the pool joined the jobs (fixed by
ClickHouse#127911). The AI review approved that round with "the prior findings
are addressed", and Stress tests, the only ones that inject thread
creation failures broadly, were green on the final head.

Asked for in
ClickHouse#127911 (comment)

The reply there listed "`wait` rethrows" as an exit; it is not in the
rule because `ThreadPool::wait` and
`waitForAllToFinishAndRethrowFirstError` join all jobs before
rethrowing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

load_parts destroyed before the pool joins its jobs: stack-use-after-scope

3 participants