Skip to content

Prevent use-after-free in BackgroundSchedulePool::TaskInfo by tracking pool shutdown - #80069

Merged
serxa merged 8 commits into
ClickHouse:masterfrom
VicoWu:fix-schedule-pool-use-after-free-4
May 27, 2025
Merged

serxa merged 8 commits into
ClickHouse:masterfrom
VicoWu:fix-schedule-pool-use-after-free-4

Conversation

@VicoWu

@VicoWu VicoWu commented May 11, 2025 •

Copy link
Copy Markdown
Contributor

This patch adds a pool_shutdown flag to BackgroundSchedulePool::TaskInfo to indicate when the owning BackgroundSchedulePool is being destroyed. This prevents calling cancelDelayedTask() on an already-destroyed pool from within TaskInfo::deactivate().

Also:

  • Set pool_shutdown = true for all delayed tasks during pool destruction.
  • Guarded pool_shutdown with schedule_mutex and grouped it with other task state flags.
  • Improved code safety and future maintainability.

This prevents a use-after-free crash in rare cases when a delayed task
is still pending while the BackgroundSchedulePool is shutting down.
Already reported in issue #80066

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Prevent use-after-free in BackgroundSchedulePool::TaskInfo by tracking pool shutdown

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 11, 2025
@clickhouse-gh

clickhouse-gh Bot commented May 11, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cb81089]

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 11, 2025
@VicoWu
VicoWu force-pushed the fix-schedule-pool-use-after-free-4 branch from 0e1666d to 46b205a Compare May 12, 2025 04:01
@serxa serxa self-assigned this May 12, 2025
@VicoWu

VicoWu commented May 12, 2025 •

Copy link
Copy Markdown
Contributor Author

@serxa Quite a bit confused about the CI error. Most of them seems unrelated.
Would you please help to give me some guidance about what should I do next?

                                                                               
Read :  0 / 793 MB ==>  0%
                                                                               
Read : 523 / 793 MB ==>  2%
                                                                               
server.log           :  1.78%   (831699904 => 14772423 bytes, server.log.zst) 
2025-05-12 06:51:53	 + zstd --threads=0 --rm fuzzer.log
2025-05-12 06:51:54	 
                                                                               
Read :  0 / 457 MB ==>  0%
                                                                               
fuzzer.log           :  1.50%   (479614611 => 7216703 bytes, fuzzer.log.zst) 
2025-05-12 06:51:54	 + '[' -f ']'
2025-05-12 06:51:54	 + zstd --threads=0 --rm
2025-05-12 06:51:54	 (\xb5/\xfd$����\x99\xe9\xd8Q+ exit 210
2025-05-12 06:51:54	 
2025-05-12 06:51:54	 real	11m4.063s
2025-05-12 06:51:54	 user	10m36.215s
2025-05-12 06:51:54	 sys	1m14.637s
2025-05-12 06:51:57	 + jobs
2025-05-12 06:51:57	 + pstree -aspgT
2025-05-12 06:51:57	 bash,1,1 -cset -o pipefail     && cd /workspace     && timeout -s 9 1h /run-fuzzer.sh 2>&1 | ts "$(printf '%%Y-%%m-%%d %%H:%%M:%%S
2025-05-12 06:51:57	   |-run-fuzzer.sh,1866,7 ch/docker/test/fuzzer/run-fuzzer.sh
2025-05-12 06:51:57	   |   `-pstree,1921,7 -aspgT
2025-05-12 06:51:57	   |-tee,9,1 main.log
2025-05-12 06:51:57	   `-ts,8,1 /usr/bin/ts %Y-%m-%d %H:%M:%S\011
INFO:root:Run failed
INFO:root:Result: 'failure', 'Logical error: 'Cannot find the original scope of the column 'properties_key'. Current scope: nested_query AS (SELECT DISTINCT objectId FROM data RIGHT JOIN (SELECT objectId FROM data) AS alias1386 ON ((((((0 OR isZeroOrNull(isNullable(0)) OR 0) OR 0 OR assumeNotNull(isZeroOrNull(materialize(0))) OR 0) <=> alias1386.name) OR (alias1386.properties_value = JSONCompactStringsEachRowWithNames)) AND (alias1386.properties_key = JSONCompactStringsEachRowWithNames)) AND (alias1386.JSONCompactStringsEachRowWithNames = `table`)) AND (alias1386.name = `table`) GROUP BY 1, isNullable(isNullable(toLowCardinality(1))) OR 0 QUALIFY isNullable(assumeNotNull(0)) AND (0 OR (assumeNotNull(isZeroOrNull(toLowCardinality(0))) OR isZeroOrNull(0 IS NOT NULL) OR 1)))'.'
Run action failed for: [AST fuzzer (amd_debug)] with exit code [1]
Run action done for: [AST fuzzer (amd_debug)]
{}

@serxa

serxa commented May 13, 2025

Copy link
Copy Markdown
Member

Quite a bit confused about the CI error. Most of them seems unrelated.

Yes, CI is currently experiencing issues. We are working on reducing the number of flaky tests. Don't worry about unrelated tests at the moment. Let me review the code...

Comment thread src/Core/BackgroundSchedulePool.cpp Outdated
// This prevents any further use of the pool (e.g., cancelDelayedTask) from within
// BackgroundSchedulePoolTaskInfo::deactivate(), avoiding use-after-free errors.
for (auto & task : delayed_tasks)
task.second->pool_shutdown = true;

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.

Here we access pool_shutdown without locking the corresponding schedule_mutex. This is a data race.

@serxa

serxa commented May 14, 2025

Copy link
Copy Markdown
Member

Although it is a viable approach presented in this PR. Could we just ensure that the TaskInfo object never lives longer than the pool? Because if TaskInfo is destroyed earlier, we have a dangling reference. I'm not sure 100%, but I believe the pool was designed to never be outlived by TaskInfo. So maybe we should better fix the usage pattern instead to avoid a dangling reference in the first place?

@VicoWu

VicoWu commented May 17, 2025 •

Copy link
Copy Markdown
Contributor Author

@serxa
Thanks for the insightful comment. I'm currently trying to deeply understand what we mean by "TaskInfo object never lives longer than the pool" and find the corresponding feasible implements. I think there are two interpretations of this idea:

  • Strict lifetime ownership — where the pool is required to physically destroy all TaskInfo objects upon its destruction.

  • Logical detachment model — where the pool ensures that, before it is destroyed, all tasks are in a deactivated/detached state, such that they are no longer referenced or managed by the pool.

Initially, I attempted the first approach, trying to ensure that the pool destructs all tasks directly. However, I encountered a logical paradox:

  • At the moment of task creation, a TaskInfo is owned by the TaskHolder only — the pool has not yet taken ownership. It's essentially in a detached or deactivated state.
  • Only after activation does the pool take shared ownership — transitioning the task to an attached or activated state.

So if we require the pool to destruct all tasks, we contradict the fact that tasks can exist without the pool initially holding them — which is a valid and necessary part of the current lifecycle.

That led me to re-read your comment carefully and reinterpret "TaskInfo object never lives longer than the pool`" in a slightly different way:

  • It’s not that the pool must physically delete all TaskInfos when it’s destroyed, but that the pool must logically release (i.e., deactivate/detach) all tasks before its own destruction — so that it holds no references and cannot schedule or execute them.

Under this model, it is perfectly safe for TaskInfo to outlive the pool as long as it's deactivated, and this aligns with the design goal of avoiding dangling references and use-after-free.

To support this, I verified that all methods in TaskInfo already check the deactivated flag, so calling deactivate() on all tasks during pool destruction is safe, necessary, and solves the core problem addressed by this PR.

Let me know if this interpretation makes sense. I'm happy to align the implementation accordingly.

@serxa

serxa commented May 18, 2025

Copy link
Copy Markdown
Member

All failed tests are unrelated and flaky

@serxa
serxa enabled auto-merge May 18, 2025 13:26
@serxa

serxa commented May 18, 2025

Copy link
Copy Markdown
Member

I have to change a changelog category because bugfix category implies a fixed tests or new tests added (it blocks merging). There were no fixed tests and it is perfectly fine for such a fix.

@serxa

serxa commented May 20, 2025

Copy link
Copy Markdown
Member

@VicoWu could you please trigger with empty commit git commit --allow-empty -m 'trigger CI'? It seems Ci doesn't notice description changes

@serxa serxa removed the pr-bugfix Pull request with bugfix, not backported by default label May 20, 2025
@serxa

serxa commented May 20, 2025 •

Copy link
Copy Markdown
Member

Oh, I think it was labeled. No need for triggering @VicoWu UPD. Label did not help. Please trigger CI.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 24, 2025
@serxa
serxa added this pull request to the merge queue May 27, 2025
@serxa

serxa commented May 27, 2025

Copy link
Copy Markdown
Member

Failed performance tests are unrelated

Merged via the queue into ClickHouse:master with commit afd43e1 May 27, 2025
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 27, 2025
azat added a commit to azat/ClickHouse that referenced this pull request Jun 9, 2025
There are multiple issues in the BackgroundSchedulePool, due to
BackgroundSchedulePoolTaskInfo holds raw reference to the pool, which is
wrong for multiple reasons, and there is no way to fix it properly
because we do not track all tasks in the BackgroundSchedulePool (even
inactive), and eventually this may lead to crash (during server
shutdown of background pools).

There were multiple attempts to fix it:

- ClickHouse#80069

  - It introduces deadlock [1]
  - And a UB due to usuing foreach and erase inside
  - But the main reason is that it does not fix all the issues, i.e.
    active() after the pool has been destroyed still leads to UB

  [1]: https://s3.amazonaws.com/clickhouse-test-reports/PRs/81398/c07d7ee6eb7c3d1d0c65649ea4b57f881571599c//stress_test_amd_debug/gdb.log

- previous version of this patch set

  - Introduces lock order inversion [2] and [3], since I tried the
    apprach that ClickHouse#80069 was been using - clean all jobs in the
    destructor of the pool

  - But, when it came to the test I found out that while
    clickhouse-server may use this pool correctly it is hard to do so
    without knowing how to, so after this I converted the
    raw reference of the BackgroundSchedulePool in
    BackgroundSchedulePoolTaskInfo to weak_ptr, to avoid any UBs

  [2]: https://s3.amazonaws.com/clickhouse-test-reports/PRs/81473/a0f20c2ad7efc19d698ceb0281e0a122ebef457e//stress_test_amd_tsan/stderr.log
  [3]: https://s3.amazonaws.com/clickhouse-test-reports/PRs/81473/6404951bfb5156b00a4aa5302d1c0ca8272a2c56//stress_test_amd_tsan/stderr.log

Also I've encapsulated the BackgroundSchedulePool and
BackgroundSchedulePoolTaskInfo more, to avoid any misuse.
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 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