Skip to content

logpuller: fix potential shutdown hang in paused region event push#5610

Merged
ti-chi-bot[bot] merged 4 commits into
masterfrom
ldz/refactor-puller02
Jul 14, 2026
Merged

logpuller: fix potential shutdown hang in paused region event push#5610
ti-chi-bot[bot] merged 4 commits into
masterfrom
ldz/refactor-puller02

Conversation

@lidezhu

@lidezhu lidezhu commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Issue Number: close #5608

What is changed and how it works?

This pull request improves the reliability and shutdown behavior of the region event sink by making the paused push path interruptible. By introducing a 'stopped' atomic flag and refining the synchronization logic, the system can now gracefully handle shutdown signals even when event processing is temporarily paused due to flow control, preventing potential goroutine leaks or hangs.

Highlights

  • Interruptible Event Pushing: Introduced a 'stopped' state to the region event sink, allowing blocked push operations to exit immediately during shutdown instead of waiting for a resume signal.
  • Refactored Synchronization: Replaced context-based waiting in the 'Push' method with a more robust condition variable and atomic flag approach, simplifying the lifecycle management of the sink.
  • Encapsulated State Management: Consolidated pause, resume, and stop logic into dedicated helper methods to improve code readability and maintainability.

Check List

Tests

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

Questions

Will it cause performance regression or break compatibility?
Do you need to update user documentation, design documentation or monitoring documentation?

Release note

Please refer to [Release Notes Language Style Guide](https://pingcap.github.io/tidb-dev-guide/contribute-to-tidb/release-notes-style-guide.html) to write a quality release note.

If you don't think this PR needs a release note then fill it with `None`.

Summary by CodeRabbit

  • Bug Fixes
    • Improved shutdown handling for paused event delivery, preventing hangs when stopping during a paused state.
    • Ensured Push operations unblock promptly on run cancellation, improving pause/resume reliability.
  • Tests
    • Added coverage to verify cancellation unblocks paused event pushes and that the sink exits cleanly.
    • Centralized test sink setup and updated related tests/bench scaffolding to use consistent sink behavior.

@ti-chi-bot

ti-chi-bot Bot commented Jul 9, 2026

Copy link
Copy Markdown

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@ti-chi-bot ti-chi-bot Bot added do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. release-note Denotes a PR that will be considered when it comes time to generate release notes. labels Jul 9, 2026
@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@lidezhu, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 48 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: eb36af59-551e-42ae-b006-fcad7c002370

📥 Commits

Reviewing files that changed from the base of the PR and between 52d0c39 and 9ba978b.

📒 Files selected for processing (1)
  • logservice/logpuller/region_event_sink_test.go
📝 Walkthrough

Walkthrough

regionEventSink now tracks shutdown separately from pause state and broadcasts on shutdown to release blocked Push callers. Construction, production wiring, test helpers, and cancellation coverage are updated.

Changes

regionEventSink shutdown coordination

Layer / File(s) Summary
Sink state and construction
logservice/logpuller/region_event_sink.go
Adds explicit paused/stopped coordination and initializes the condition variable without storing a context.
Push, Run, and Close shutdown flow
logservice/logpuller/region_event_sink.go
Push exits when stopped, paused waits can terminate on shutdown, Run stops on cancellation, and Close stops before closing the stream.
Call-site and test integration
logservice/logpuller/subscription_client.go, logservice/logpuller/*_test.go
Updates sink construction, centralizes test setup, adds cancellation-unblocking coverage, and includes a merge-conflict marker in the test file.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Poem

A rabbit paused beside the stream,
Then shutdown broke the waiting dream.
A broadcast rang, the lock let go,
And hopping workers sprang below. 🐇

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The template is only partially filled; it lacks selected tests, answers to the questions, and a proper release note or None. Add the test type used, answer the performance and documentation questions, and replace the release-note placeholder with a real note or None.
Out of Scope Changes check ⚠️ Warning A merge-conflict marker remains in region_event_sink_test.go, which is unrelated to the fix and should not be in the PR. Remove the unresolved conflict marker and any stray conflict artifacts from the test file before merging.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: preventing shutdown hangs in paused region event push.
Linked Issues check ✅ Passed The changes add a stop flag and unblock paused pushes on shutdown, matching the graceful-shutdown fix in #5608.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ldz/refactor-puller02

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.

@ti-chi-bot ti-chi-bot Bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Jul 9, 2026

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request refactors the synchronization mechanism in regionEventSink from using sync.Cond to channel-based coordination (resumeCh and stopCh) to manage pause and resume feedback. It also adds a new test to verify that context cancellation unblocks the Push method. The review feedback suggests optimizing the Push method by keeping the fast path extremely lightweight (using a simple atomic load) and only executing the select statement when the sink is actually paused, avoiding unnecessary CPU overhead on the critical hot path.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread logservice/logpuller/region_event_sink.go
@lidezhu lidezhu marked this pull request as ready for review July 9, 2026 13:21
@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 9, 2026
@lidezhu

lidezhu commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

/gemini summary

@lidezhu

lidezhu commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

/gemini review

@lidezhu

lidezhu commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

This pull request improves the reliability and shutdown behavior of the region event sink by making the paused push path interruptible. By introducing a 'stopped' atomic flag and refining the synchronization logic, the system can now gracefully handle shutdown signals even when event processing is temporarily paused due to flow control, preventing potential goroutine leaks or hangs.

Highlights

  • Interruptible Event Pushing: Introduced a 'stopped' state to the region event sink, allowing blocked push operations to exit immediately during shutdown instead of waiting for a resume signal.
  • Refactored Synchronization: Replaced context-based waiting in the 'Push' method with a more robust condition variable and atomic flag approach, simplifying the lifecycle management of the sink.
  • Encapsulated State Management: Consolidated pause, resume, and stop logic into dedicated helper methods to improve code readability and maintainability.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Activity
  • The pull request was created by lidezhu.
  • Automated bots (ti-chi-bot, coderabbitai) performed initial checks and provided configuration instructions.
  • The author requested a summary and review from the AI assistant.
  • A review comment was provided suggesting optimizations for the 'Push' method's hot path, which the author has addressed in the current implementation.

@lidezhu lidezhu changed the title logpuller: make paused event pushing interruptible logpuller: fix potential shutdown hang in paused region event push Jul 9, 2026

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@logservice/logpuller/region_event_sink_test.go`:
- Around line 134-136: The test setup in
TestRegionEventSinkRunCancelUnblocksPush creates a cancellable context but does
not guarantee cleanup if the test exits early. Add a deferred cancel()
immediately after context.WithCancel in this test so the sink.Run(ctx) goroutine
is always unblocked and cannot leak on failure; keep the change localized to the
test helper flow around context creation and cancellation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 56c63e45-522b-4931-9155-9c07ed766ad2

📥 Commits

Reviewing files that changed from the base of the PR and between f2167b3 and 48aa828.

📒 Files selected for processing (5)
  • logservice/logpuller/region_event_sink.go
  • logservice/logpuller/region_event_sink_test.go
  • logservice/logpuller/region_request_worker_test.go
  • logservice/logpuller/subscription_client.go
  • logservice/logpuller/subscription_client_test.go

Comment on lines +134 to +136
func TestRegionEventSinkRunCancelUnblocksPush(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Defer cancel() to avoid leaking Run on early test failure.

If the test fails before Line 163, the goroutine running sink.Run(ctx) can remain blocked on feedback. Add defer cancel() immediately after creating the context. As per coding guidelines, **/*_test.go: Prefer focused deterministic tests; see docs/agents/testing.md before adding or changing tests.

Proposed fix
 func TestRegionEventSinkRunCancelUnblocksPush(t *testing.T) {
 	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
 
 	ds := newMockRegionEventSinkStream()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestRegionEventSinkRunCancelUnblocksPush(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
func TestRegionEventSinkRunCancelUnblocksPush(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
🤖 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 `@logservice/logpuller/region_event_sink_test.go` around lines 134 - 136, The
test setup in TestRegionEventSinkRunCancelUnblocksPush creates a cancellable
context but does not guarantee cleanup if the test exits early. Add a deferred
cancel() immediately after context.WithCancel in this test so the sink.Run(ctx)
goroutine is always unblocked and cannot leak on failure; keep the change
localized to the test helper flow around context creation and cancellation.

Source: Coding guidelines

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request refactors the regionEventSink to manage its lifecycle and flow-control states (paused, stopped) more robustly, removing the context from the struct and introducing helper methods for pausing, resuming, and stopping. It also adds tests to verify that context cancellation unblocks pending push operations. A critical issue was identified in the Run loop where reading from the closed feedback channel of s.ds without checking the ok status can result in an infinite busy loop and high CPU usage during shutdown.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread logservice/logpuller/region_event_sink.go
Base automatically changed from ldz/refactor-puller01 to master July 10, 2026 09:42
@ti-chi-bot ti-chi-bot Bot added size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. and removed size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Jul 10, 2026
@lidezhu lidezhu force-pushed the ldz/refactor-puller02 branch from 48aa828 to 52d0c39 Compare July 10, 2026 10:00
@ti-chi-bot ti-chi-bot Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. labels Jul 10, 2026

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🤖 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.

Inline comments:
In `@logservice/logpuller/region_event_sink_test.go`:
- Line 137: Remove the stray “<<<<<<< HEAD” merge-conflict marker from
region_event_sink_test.go and resolve any related conflict remnants, including
“=======” and “>>>>>>>” markers, while preserving the intended test code so the
package compiles.
- Around line 159-162: Replace the regionEventSink literal in both subtests with
newTestRegionEventSink(ds), since stopCh was removed and the helper also
initializes cond consistently.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d8a3cb28-28fc-41fd-a3bd-fb8966d187e3

📥 Commits

Reviewing files that changed from the base of the PR and between 48aa828 and 52d0c39.

📒 Files selected for processing (5)
  • logservice/logpuller/region_event_sink.go
  • logservice/logpuller/region_event_sink_test.go
  • logservice/logpuller/region_request_worker_test.go
  • logservice/logpuller/subscription_client.go
  • logservice/logpuller/subscription_client_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • logservice/logpuller/subscription_client_test.go
  • logservice/logpuller/region_request_worker_test.go
  • logservice/logpuller/subscription_client.go

Comment thread logservice/logpuller/region_event_sink_test.go Outdated
Comment thread logservice/logpuller/region_event_sink_test.go
@lidezhu

lidezhu commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

/test all

@lidezhu

lidezhu commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

/retest

@ti-chi-bot ti-chi-bot Bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Jul 13, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: asddongmen, hongyunyan

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:
  • OWNERS [asddongmen,hongyunyan]

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 Jul 13, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-07-13 03:29:15.490556246 +0000 UTC m=+597941.526651312: ☑️ agreed by hongyunyan.
  • 2026-07-13 09:08:01.014338155 +0000 UTC m=+618267.050433211: ☑️ agreed by asddongmen.

@lidezhu

lidezhu commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

/retest

@ti-chi-bot ti-chi-bot Bot merged commit 61e002d into master Jul 14, 2026
25 checks passed
@ti-chi-bot ti-chi-bot Bot deleted the ldz/refactor-puller02 branch July 14, 2026 07:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

logpuller: paused region event push can block graceful shutdown

3 participants