Skip to content

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

Open
lidezhu wants to merge 3 commits into
ldz/refactor-puller01from
ldz/refactor-puller02
Open

logpuller: fix potential shutdown hang in paused region event push#5610
lidezhu wants to merge 3 commits into
ldz/refactor-puller01from
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 a service stops while waiting to resume.
    • Ensured blocked event pushes are released promptly during cancellation, making pause/resume behavior more reliable.
    • Updated related client and test setup to use the same event sink behavior consistently across scenarios.

@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
@ti-chi-bot

ti-chi-bot Bot commented Jul 9, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign charlescheung96 for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found 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

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

regionEventSink is updated to track a stopped state alongside paused, with a new stop() helper that broadcasts on the condition variable to release blocked Push callers during shutdown. The constructor no longer stores context; Run and Close invoke stop() accordingly. Tests and call sites are updated to match.

Changes

regionEventSink shutdown coordination

Layer / File(s) Summary
Sink state fields and constructor
logservice/logpuller/region_event_sink.go
Adds mu, cond, paused, and stopped fields; constructor no longer stores context and initializes cond after construction.
Push/Run/Close shutdown logic
logservice/logpuller/region_event_sink.go
Push exits early when stopped and its wait loop wakes on resume or shutdown; Run routes ctx.Done() and feedback through pause()/resume()/new stop(); Close calls stop() before closing the dynstream.
Constructor call site and test wiring
logservice/logpuller/subscription_client.go, logservice/logpuller/region_event_sink_test.go, logservice/logpuller/region_request_worker_test.go, logservice/logpuller/subscription_client_test.go
newRegionEventSink call drops the context argument; tests adopt a shared newTestRegionEventSink helper and add a test verifying context cancellation unblocks a paused Push.

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

Suggested reviewers: hongyunyan

Poem

A rabbit paused mid-hop one day,
stuck in a wait that wouldn't sway,
but now when shutdown comes to call,
cond.Broadcast wakes us all! 🐇
Hop free, dear goroutine, run and play. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The code addresses #5608 by letting paused pushes exit on stop while preserving normal pause/resume behavior.
Out of Scope Changes check ✅ Passed The changes stay within the sink shutdown fix, its tests, and the related client wiring needed to support it.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly matches the main change: making paused region event push shutdown-safe.
Description check ✅ Passed The description includes the issue number, problem statement, implementation summary, and test section, though the questions and release note remain unfilled.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ldz/refactor-puller02

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant