Skip to content

Storages: use-after-free race between SegmentReadTaskScheduler and SegmentReaderPoolManager shutdown#10917

Merged
ti-chi-bot[bot] merged 2 commits into
pingcap:masterfrom
JaySon-Huang:fix/10903-scheduler-use-after-free
Jun 24, 2026
Merged

Storages: use-after-free race between SegmentReadTaskScheduler and SegmentReaderPoolManager shutdown#10917
ti-chi-bot[bot] merged 2 commits into
pingcap:masterfrom
JaySon-Huang:fix/10903-scheduler-use-after-free

Conversation

@JaySon-Huang

@JaySon-Huang JaySon-Huang commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: close #10903

Problem Summary:

During shutdown, SegmentReaderPoolManager::stop() destroys all reader_pools and their WorkQueue mutexes, but SegmentReadTaskScheduler's schedLoop background thread is still running. When schedLoop wakes from its 2ms sleep, it calls scheduleOneRound()SegmentReaderPoolManager::addTask() → accesses already-destroyed reader_pools, causing SIGSEGV (use-after-free).

What is changed and how it works?

Add a public `stop()` method to `SegmentReadTaskScheduler` that sets the stop flag and joins the background thread. Call it **before** `SegmentReaderPoolManager::stop()` in both production (`Server.cpp`) and test (`gtests_dbms_main.cpp`) shutdown paths.

- `SegmentReadTaskScheduler.h`: expose `stop()` as public method; rename `std::atomic<bool> stop` → `stop_flag` to avoid name collision
- `SegmentReadTaskScheduler.cpp`: implement `stop()`, destructor delegates to it
- `Server.cpp`: call `SegmentReadTaskScheduler::instance().stop()` before `SegmentReaderPoolManager::instance().stop()`
- `gtests_dbms_main.cpp`: same reorder

Also fix two minor typos along the way:
- `reapPeningPools` → `reapPendingPools` in class comment
- `max_free_threds` → `max_free_threads` in test main

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No code

Manual test: ./gtests_dbms --gtest_filter="DeltaMergeStoreTest.ReadLegacyStringDataCFTiny" — test passes and process exits cleanly without SIGSEGV.

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

None

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Improved shutdown stability by ensuring the segment read task scheduler stops before dependent reader pools are torn down, reducing risk of invalid task enqueuing during shutdown.
  • Tests
    • Corrected a thread-pool initialization parameter name in the test harness to ensure consistent setup and teardown behavior.

…ReaderPoolManager shutdown (pingcap#10903)

The schedLoop background thread could still be running when
SegmentReaderPoolManager::stop() destroyed all reader_pools and their
WorkQueue mutexes. Subsequent scheduleOneRound() calls would then
access already-destroyed objects, causing SIGSEGV.

Fix by adding a public stop() method to SegmentReadTaskScheduler
and calling it before SegmentReaderPoolManager::stop() in both
production (Server.cpp) and test (gtests_dbms_main.cpp) shutdown paths.

Also fix:
- rename std::atomic<bool> stop -> stop_flag to avoid name collision
- fix typo: reapPeningPools -> reapPendingPools in header comment
- fix typo: max_free_threds -> max_free_threads in test main
@ti-chi-bot ti-chi-bot Bot added release-note-none Denotes a PR that doesn't merit a release note. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Jun 24, 2026
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a public stop() method to SegmentReadTaskScheduler that sets a stop flag and joins the scheduler thread. This method is now called explicitly before SegmentReaderPoolManager::stop() in both the production server shutdown (Server.cpp) and the test harness teardown (gtests_dbms_main.cpp). The internal atomic flag is renamed from stop to stop_flag, task enqueuing after shutdown is prevented, and a typo in the thread-pool parameter name (max_free_threds) is corrected.

Changes

SegmentReadTaskScheduler shutdown ordering fix

Layer / File(s) Summary
SegmentReadTaskScheduler stop() API and state management
dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.h, dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.cpp
Declares and implements a new public stop() method that calls setStop() and joins sched_thread when joinable. The internal atomic member is renamed from stop to stop_flag; setStop()/isStop() are updated accordingly. The destructor now delegates to stop(). pushMergedTask is changed to check isStop() and discard re-queued tasks instead of pushing them after shutdown begins. A comment typo (reapPeningPoolsreapPendingPools) is also fixed.
Shutdown call sites: Server and test harness
dbms/src/Server/Server.cpp, dbms/src/TestUtils/gtests_dbms_main.cpp
Inserts DB::DM::SegmentReadTaskScheduler::instance().stop() before SegmentReaderPoolManager::stop() in both the Server::main SCOPE_EXIT and the gtests teardown block to prevent the scheduler loop from accessing destroyed reader pools. Also corrects max_free_thredsmax_free_threads in thread-pool initialization calls in the test harness.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

size/XS

Suggested reviewers

  • yongman
  • Lloyd-Pottiger
  • JinheLin

Poem

🐇 The scheduler once ran free,
past pools that had ceased to be.
Now stop() is called with care,
joining threads before the tear.
No more SIGSEGV in the air! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description check ✅ Passed The PR description covers all required sections: problem summary with issue number, detailed commit message explaining changes, completed checklist with unit tests and manual tests, and release notes.
Linked Issues check ✅ Passed The PR directly addresses issue #10903 by implementing the suggested fix: adding a public stop() method to SegmentReadTaskScheduler and reordering shutdown to call it before SegmentReaderPoolManager::stop() in both production and test paths.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fix the use-after-free race: refactoring SegmentReadTaskScheduler shutdown, reordering shutdown sequences in Server.cpp and test code, and fixing minor related typos.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title accurately summarizes the main shutdown race fix between the scheduler and reader pool manager.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.cpp (1)

37-43: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Drop re-queued merged tasks after scheduler stop.

stop() joins only sched_thread; the next shutdown step stops SegmentReaderPoolManager, and exiting readers can still call pushMergedTask() for unfinished work. Since no scheduler remains to drain merged_task_pool, guard pushMergedTask() on the stop flag so shutdown releases the task instead of retaining read resources until singleton teardown.

Suggested guard
-    void pushMergedTask(const MergedTaskPtr & p) { merged_task_pool.push(p); }
+    void pushMergedTask(const MergedTaskPtr & p)
+    {
+        if (isStop())
+            return;
+        merged_task_pool.push(p);
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.cpp` around
lines 37 - 43, The issue is that after stop() joins the scheduler thread, the
SegmentReaderPoolManager shutdown continues and exiting readers can still invoke
pushMergedTask(), which adds tasks to merged_task_pool that will never be
drained since the scheduler is no longer running. Guard the pushMergedTask()
method to check the stop flag before accepting new tasks; if the scheduler has
already been stopped, the method should drop or reject the task instead of
queuing it to prevent resources from being retained until singleton teardown.
🧹 Nitpick comments (1)
dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.h (1)

104-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Rename stop_flag to stopFlag.

This new member uses snake_case while the project guideline requires camelCase variables; update the declaration and the setStop() / isStop() references together.

Suggested rename
-    std::atomic<bool> stop_flag{false};
+    std::atomic<bool> stopFlag{false};
-    stop_flag.store(true, std::memory_order_relaxed);
+    stopFlag.store(true, std::memory_order_relaxed);

-    return stop_flag.load(std::memory_order_relaxed);
+    return stopFlag.load(std::memory_order_relaxed);

As per coding guidelines, Method and variable names should use camelCase (e.g., readBlock, totalBytes).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.h` at line
104, The member variable `stop_flag` in the SegmentReadTaskScheduler class uses
snake_case naming which violates the project's camelCase guideline for
variables. Rename `stop_flag` to `stopFlag` in the member declaration and update
all references to this variable throughout the class, including in the setStop()
and isStop() methods, to comply with the coding standards.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.cpp`:
- Around line 37-43: The issue is that after stop() joins the scheduler thread,
the SegmentReaderPoolManager shutdown continues and exiting readers can still
invoke pushMergedTask(), which adds tasks to merged_task_pool that will never be
drained since the scheduler is no longer running. Guard the pushMergedTask()
method to check the stop flag before accepting new tasks; if the scheduler has
already been stopped, the method should drop or reject the task instead of
queuing it to prevent resources from being retained until singleton teardown.

---

Nitpick comments:
In `@dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.h`:
- Line 104: The member variable `stop_flag` in the SegmentReadTaskScheduler
class uses snake_case naming which violates the project's camelCase guideline
for variables. Rename `stop_flag` to `stopFlag` in the member declaration and
update all references to this variable throughout the class, including in the
setStop() and isStop() methods, to comply with the coding standards.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f1e75f63-fdc9-4953-b79d-7c2e51022c84

📥 Commits

Reviewing files that changed from the base of the PR and between 96e3ff3 and 3c3badd.

📒 Files selected for processing (4)
  • dbms/src/Server/Server.cpp
  • dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.cpp
  • dbms/src/Storages/DeltaMerge/ReadThread/SegmentReadTaskScheduler.h
  • dbms/src/TestUtils/gtests_dbms_main.cpp

@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/retest

SegmentReader threads may call pushMergedTask() for unfinished work
after stop() has joined schedLoop. Since no scheduler remains to drain
merged_task_pool, guard the method with isStop() to discard tasks
instead of leaking them until singleton teardown.
@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/retest

@ti-chi-bot ti-chi-bot Bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Jun 24, 2026
@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/test pull-unit-next-gen

@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/test pull-integration-test

@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/retest

@JaySon-Huang JaySon-Huang changed the title fix: use-after-free race between SegmentReadTaskScheduler and SegmentReaderPoolManager shutdown Storages: use-after-free race between SegmentReadTaskScheduler and SegmentReaderPoolManager shutdown Jun 24, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: JinheLin, yongman

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Jun 24, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

[LGTM Timeline notifier]

Timeline:

  • 2026-06-24 06:20:39.450731158 +0000 UTC m=+101323.113956671: ☑️ agreed by yongman.
  • 2026-06-24 07:29:13.949339864 +0000 UTC m=+105437.612565377: ☑️ agreed by JinheLin.

@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/retest

@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/test pull-integration-test

1 similar comment
@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/test pull-integration-test

@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/hold

@ti-chi-bot ti-chi-bot Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jun 24, 2026
@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/unhold

@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jun 24, 2026
@JaySon-Huang

Copy link
Copy Markdown
Contributor Author

/cherry-pick release-nextgen-202603

@ti-chi-bot

Copy link
Copy Markdown
Member

@JaySon-Huang: once the present PR merges, I will cherry-pick it on top of release-nextgen-202603 in the new PR and assign it to you.

Details

In response to this:

/cherry-pick release-nextgen-202603

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the ti-community-infra/tichi repository.

@ti-chi-bot ti-chi-bot Bot merged commit 87da849 into pingcap:master Jun 24, 2026
11 checks passed
@ti-chi-bot

Copy link
Copy Markdown
Member

@JaySon-Huang: new pull request created to branch release-nextgen-202603: #10922.

Details

In response to this:

/cherry-pick release-nextgen-202603

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the ti-community-infra/tichi repository.

@JaySon-Huang JaySon-Huang deleted the fix/10903-scheduler-use-after-free branch June 25, 2026 03:21
ti-chi-bot Bot pushed a commit that referenced this pull request Jun 25, 2026
…gmentReaderPoolManager shutdown (#10917) (#10922)

close #10903\n\nAdd a public `stop()` method to `SegmentReadTaskScheduler` that sets the stop flag and joins the background thread. Call it **before** `SegmentReaderPoolManager::stop()` in both production (`Server.cpp`) and test (`gtests_dbms_main.cpp`) shutdown paths.

- `SegmentReadTaskScheduler.h`: expose `stop()` as public method; rename `std::atomic<bool> stop` → `stop_flag` to avoid name collision
- `SegmentReadTaskScheduler.cpp`: implement `stop()`, destructor delegates to it
- `Server.cpp`: call `SegmentReadTaskScheduler::instance().stop()` before `SegmentReaderPoolManager::instance().stop()`
- `gtests_dbms_main.cpp`: same reorder

Also fix two minor typos along the way:
- `reapPeningPools` → `reapPendingPools` in class comment
- `max_free_threds` → `max_free_threads` in test main\n\nCo-authored-by: JaySon-Huang <tshent@qq.com>
windtalker pushed a commit to windtalker/tiflash that referenced this pull request Jul 9, 2026
…gmentReaderPoolManager shutdown (pingcap#10917)

close pingcap#10903\n\nAdd a public `stop()` method to `SegmentReadTaskScheduler` that sets the stop flag and joins the background thread. Call it **before** `SegmentReaderPoolManager::stop()` in both production (`Server.cpp`) and test (`gtests_dbms_main.cpp`) shutdown paths.

- `SegmentReadTaskScheduler.h`: expose `stop()` as public method; rename `std::atomic<bool> stop` → `stop_flag` to avoid name collision
- `SegmentReadTaskScheduler.cpp`: implement `stop()`, destructor delegates to it
- `Server.cpp`: call `SegmentReadTaskScheduler::instance().stop()` before `SegmentReaderPoolManager::instance().stop()`
- `gtests_dbms_main.cpp`: same reorder

Also fix two minor typos along the way:
- `reapPeningPools` → `reapPendingPools` in class comment
- `max_free_threds` → `max_free_threads` in test main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note-none Denotes a PR that doesn't merit a release note. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SIGSEGV in SegmentReadTaskScheduler::schedLoop due to use-after-free race with SegmentReaderPoolManager::stop()

4 participants