Skip to content

logpuller: simplify region failure handling pipeline#5611

Closed
lidezhu wants to merge 5 commits into
ldz/refactor-puller02from
ldz/refactor-puller03
Closed

logpuller: simplify region failure handling pipeline#5611
lidezhu wants to merge 5 commits into
ldz/refactor-puller02from
ldz/refactor-puller03

Conversation

@lidezhu

@lidezhu lidezhu commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Issue Number: close #5612

What is changed and how it works?

This pull request simplifies the region failure handling pipeline in the logpuller component. By removing unnecessary concurrency primitives like errgroup and dedicated error channels, the implementation becomes more straightforward and easier to maintain. The changes focus on improving how cached errors are processed, ensuring efficient batch handling and proper resource management during shutdown.

Highlights

  • Pipeline Simplification: Removed the errCh channel and the errgroup usage in regionFailureHandler.Run, replacing them with a more direct polling and notification mechanism.
  • Error Handling Optimization: Refactored the error cache processing to use a ticker and a notification channel, reducing complexity and potential lock contention.
  • Testing Improvements: Added a new test file logservice/logpuller/region_failure_handler_test.go and removed outdated tests in subscription_client_test.go to reflect the new architecture.

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 handling of region failure processing so errors are drained more reliably and in batches.
    • Reduced the chance of missed or delayed error handling during cancellation or high error volume.
    • Tightened timestamp selection logic to better handle edge cases such as clock skew and stale state.
  • Tests

    • Added coverage for error-cache batching and handler draining behavior.
    • Added validation for timestamp resolution edge cases.

@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 release-note Denotes a PR that will be considered when it comes time to generate release notes. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. 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 wlwilliamx 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

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c4236690-af6a-4d20-9103-204e82dbabac

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The region failure handler's error caching pipeline is simplified: the errgroup-based dispatch stage with a separate errCh channel is removed, and Run now drains the errCache directly in batches via a ticker and a notify/ready() signal. New tests cover cache batching and drain behavior; stale dispatch tests are removed and a new resolved-target-timestamp test is added.

Changes

Region Failure Handler Simplification

Layer / File(s) Summary
errCache storage rework
logservice/logpuller/region_failure_handler.go
errCache drops errCh, dispatch, and dispatchBatch, replacing them with a buffered notify channel, a ready() accessor, and an errCacheBatchSize constant; newErrCache initializes slice capacity and the notify channel.
Run loop consumes cache directly
logservice/logpuller/region_failure_handler.go
Run replaces the errgroup-based dispatch/read goroutines with a single loop using a 50ms ticker and a handleCachedErrors closure that pops batches on tick or ready() signal, exiting on context cancellation or handler error; unused errgroup import removed.
New cache batching and drain tests
logservice/logpuller/region_failure_handler_test.go
Adds a regionErrorInfo test helper, table-driven TestErrCachePopBatch cases, and TestRegionFailureHandlerRunDrainsErrCacheWithoutDispatcher verifying drain-to-zero and context.Canceled exit.
Removed stale dispatch tests, added resolved-target-ts test
logservice/logpuller/subscription_client_test.go
Removes TestErrCacheDispatchWithFullChannelAndCanceledContext and TestErrCacheDispatchBatch; adds TestGetResolvedTargetTs covering getResolvedTargetTs timing/eligibility conditions.

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

Sequence Diagram(s)

sequenceDiagram
  participant Caller as errCache.add
  participant Cache as errCache
  participant Run as regionFailureHandler.Run
  participant Handler as handleError

  Caller->>Cache: append regionErrorInfo
  Cache->>Cache: non-blocking notify signal
  Note over Run: ticker (50ms) or notify
  Run->>Cache: popBatch(errCacheBatchSize)
  Cache-->>Run: batch of regionErrorInfo
  loop each item in batch
    Run->>Handler: handleError(item)
    Handler-->>Run: error or nil
  end
  Note over Run: exit on ctx.Done() or handleError failure
Loading

Possibly related PRs

  • pingcap/ticdc#4949: Both PRs modify the region error cache draining/dispatch mechanism in the same subsystem.
  • pingcap/ticdc#5419: Both PRs touch TestGetResolvedTargetTs and the getResolvedTargetTs helper logic in subscription_client_test.go.

Suggested labels: lgtm, approved

Suggested reviewers: asddongmen

Poem

A cache once waited for errCh's call,
Now hops are fewer, no dispatch at all!
With ready() and notify, the loop drains clean,
Batches of errors, popped serene.
Hop, hop, this rabbit's tests all pass —
Simpler pipes, less code mass! 🐇

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning subscription_client_test.go adds getResolvedTargetTs coverage, which appears unrelated to #5612's region failure handling scope. Move the target-ts test changes to a separate PR or explain why they are required for the region failure handling refactor.
Description check ⚠️ Warning The description covers the issue, change summary, and tests section, but required checklist, questions, and release note fields are left unfilled. Add the checklist selections, answer the performance/docs questions, and replace the release-note placeholder with a real note or None.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes remove errgroup/errCh and let the handler drain errCache directly, matching #5612's requested simplification.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title is concise and matches the main change: simplifying the region failure handling pipeline.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ldz/refactor-puller03

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/XL Denotes a PR that changes 500-999 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 regionFailureHandler to simplify error handling by removing the separate dispatcher goroutine and the errCh channel, instead processing cached errors in a single loop triggered by a ticker or a notification channel. The reviewer identified a potential performance issue where redundant wakeups on the r.cache.notify channel could cause high CPU usage and lock contention under high load, and suggested draining the notification channel in a non-blocking loop before processing the batch.

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_failure_handler.go
@lidezhu lidezhu marked this pull request as ready for review July 9, 2026 14:17
@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

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

This pull request simplifies the region failure handling pipeline in the logpuller component. By removing unnecessary concurrency primitives like errgroup and dedicated error channels, the implementation becomes more straightforward and easier to maintain. The changes focus on improving how cached errors are processed, ensuring efficient batch handling and proper resource management during shutdown.

Highlights

  • Pipeline Simplification: Removed the errCh channel and the errgroup usage in regionFailureHandler.Run, replacing them with a more direct polling and notification mechanism.
  • Error Handling Optimization: Refactored the error cache processing to use a ticker and a notification channel, reducing complexity and potential lock contention.
  • Testing Improvements: Added a new test file logservice/logpuller/region_failure_handler_test.go and removed outdated tests in subscription_client_test.go to reflect the new architecture.
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 CI was skipped as the PR was initially in draft status.
  • Gemini Code Assist identified potential performance issues related to redundant wakeups and lock contention, suggesting a drain loop for the notification channel.
  • The author has implemented structural changes to the error handling pipeline, likely addressing the identified performance concerns.

@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 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 simplifies the error handling mechanism in regionFailureHandler by removing the concurrent dispatcher goroutine and the intermediate errCh channel, instead directly draining the error cache in batches. The reviewer suggested removing the 50ms ticker in the Run loop, as the ready() channel notification is sufficient and removing the ticker would prevent unnecessary periodic wakeups and reduce idle CPU usage.

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_failure_handler.go

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

🧹 Nitpick comments (2)
logservice/logpuller/region_failure_handler.go (1)

201-206: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse errCacheBatchSize for the initial slice capacity.

The literal 1024 duplicates the newly added errCacheBatchSize constant; referencing the constant keeps the batch size and pre-allocation in sync if the value ever changes.

♻️ Proposed tweak
 func newErrCache() *errCache {
 	return &errCache{
-		cache:  make([]regionErrorInfo, 0, 1024),
+		cache:  make([]regionErrorInfo, 0, errCacheBatchSize),
 		notify: make(chan struct{}, 1),
 	}
 }
🤖 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_failure_handler.go` around lines 201 - 206, The
initial capacity in newErrCache duplicates the batch size value and should use
errCacheBatchSize instead of a hardcoded literal. Update the cache slice
allocation in newErrCache to reference errCacheBatchSize so the pre-allocation
stays in sync with the batching constant if it changes later.
logservice/logpuller/region_failure_handler_test.go (1)

40-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant/misleading expectedCalls assertion.

expectedN and expectedCalls are both compared against len(batch) and always hold the same value across every case, so require.Len(t, batch, tc.expectedCalls) duplicates the require.Equal(t, tc.expectedN, n) check. The expectedCalls name implies counting handleError invocations, but this test never calls handleError, which is misleading. Consider dropping the redundant field/assertion.

Also applies to: 108-112

🤖 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_failure_handler_test.go` around lines 40 - 46,
The test table in region_failure_handler_test is carrying a redundant and
misleading expectedCalls field that duplicates expectedN and is not tied to any
handleError invocation. Update the test cases and assertions in the relevant
test function so they only assert the meaningful batch size and cache
expectations, and remove the expectedCalls field plus the matching
require.Len(t, batch, ...) check; use the existing test symbols like expectedN,
expectedCache, and the batch-related assertion to keep the intent clear.
🤖 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.

Nitpick comments:
In `@logservice/logpuller/region_failure_handler_test.go`:
- Around line 40-46: The test table in region_failure_handler_test is carrying a
redundant and misleading expectedCalls field that duplicates expectedN and is
not tied to any handleError invocation. Update the test cases and assertions in
the relevant test function so they only assert the meaningful batch size and
cache expectations, and remove the expectedCalls field plus the matching
require.Len(t, batch, ...) check; use the existing test symbols like expectedN,
expectedCache, and the batch-related assertion to keep the intent clear.

In `@logservice/logpuller/region_failure_handler.go`:
- Around line 201-206: The initial capacity in newErrCache duplicates the batch
size value and should use errCacheBatchSize instead of a hardcoded literal.
Update the cache slice allocation in newErrCache to reference errCacheBatchSize
so the pre-allocation stays in sync with the batching constant if it changes
later.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 32641488-e12b-4885-8826-e33f66ab1056

📥 Commits

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

📒 Files selected for processing (3)
  • logservice/logpuller/region_failure_handler.go
  • logservice/logpuller/region_failure_handler_test.go
  • logservice/logpuller/subscription_client_test.go
💤 Files with no reviewable changes (1)
  • logservice/logpuller/subscription_client_test.go

@lidezhu lidezhu force-pushed the ldz/refactor-puller03 branch from 3b9edc2 to 91aa615 Compare July 9, 2026 15:29
@lidezhu lidezhu closed this Jul 9, 2026
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/XL Denotes a PR that changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant