Skip to content

Conversation

@wlwilliamx
Copy link
Collaborator

@wlwilliamx wlwilliamx commented Jan 29, 2026

What problem does this PR solve?

Issue Number: close #4064

What is changed and how it works?

When the Kafka sink exits unexpectedly (for example, downstream topic missing), DispatcherManager previously kept running dispatchers and could continue buffering events into the sink path. This can lead to unbounded memory growth, GC CPU spikes, and eventually OOM.

This PR closes DispatcherManager proactively when sink.Run(ctx) returns with a non-cancel error, which stops all dispatchers and releases sink resources (including sarama) instead of allowing further buffering. The sink error is reported to maintainer before closing to avoid being lost due to context cancellation.

Check List

Tests

  • Unit test
  • Manual test (N/A)

Questions

Will it cause performance regression or break compatibility?

No. It improves stability by preventing runaway buffering and GC thrash after sink failures, and only changes error handling behavior when the sink goroutine exits unexpectedly.

Do you need to update user documentation, design documentation or monitoring documentation?

No.

Release note

Fix TiCDC Kafka sink memory/CPU runaway by closing DispatcherManager when the sink exits with error, preventing unbounded buffering and OOM.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling and reporting when sink components fail unexpectedly, ensuring maintainer visibility of critical failures.
    • Improved graceful shutdown behavior during sink errors with proactive resource cleanup.
  • Tests

    • Added test coverage for sink error handling scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

If sink.Run exits with error, close DispatcherManager to stop dispatchers and release sink resources (e.g. sarama) instead of allowing unbounded buffering.
@ti-chi-bot ti-chi-bot bot added the release-note Denotes a PR that will be considered when it comes time to generate release notes. label Jan 29, 2026
@ti-chi-bot
Copy link

ti-chi-bot bot commented Jan 29, 2026

[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 lidezhu 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

@ti-chi-bot ti-chi-bot bot added the size/L Denotes a PR that changes 100-499 lines, ignoring generated files. label Jan 29, 2026
@gemini-code-assist
Copy link

Summary of Changes

Hello @wlwilliamx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the stability of TiCDC's Kafka sink by introducing robust error handling. Previously, an unexpectedly failing Kafka sink could lead to severe resource exhaustion, including out-of-memory errors and CPU spikes, as the system continued to buffer events. The changes ensure that upon detecting a non-recoverable sink error, the DispatcherManager gracefully shuts down, preventing further event buffering and immediately reporting the issue, thus safeguarding the system's overall health and performance.

Highlights

  • Proactive Sink Error Handling: The DispatcherManager now proactively closes itself when the underlying Kafka sink exits with a non-cancellation error (e.g., missing topic, authentication failure). This prevents continued buffering of events into a failed sink, which could lead to unbounded memory growth and Out-Of-Memory (OOM) errors.
  • Immediate Error Reporting: A new mechanism ensures that critical sink errors are reported to the maintainer immediately upon detection, even if the manager's context is subsequently canceled during shutdown. This prevents important error messages from being lost.
  • New Unit Test for Error Scenarios: A new unit test, TestDispatcherManagerCloseOnSinkError, has been added to validate the correct behavior of the DispatcherManager when the sink encounters an unexpected error and triggers a proactive shutdown.

🧠 New Feature in Public Preview: You can now enable Memory 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.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2026

📝 Walkthrough

Walkthrough

Added centralized exit handling for sinks in the dispatcher manager, introducing new methods to gracefully handle sink errors, report them to the maintainer via heartbeat, and trigger proactive shutdown when the sink exits unexpectedly or encounters non-cancellation errors.

Changes

Cohort / File(s) Summary
Exit Handling Implementation
downstreamadapter/dispatchermanager/dispatcher_manager.go
Added runSinkWithExitHandling method to wrap sink execution with error propagation and proactive shutdown. Added reportErrorToMaintainer method to enqueue visible error messages (with timestamp, node, error code) to maintainer via heartbeat queue when sink exits with error. On sink exit, distinguishes between normal context cancellation, error conditions, and unexpected exits.
Exit Handling Tests
downstreamadapter/dispatchermanager/dispatcher_manager_test.go
Added errorSink mock type implementing Sink interface to simulate sink errors. Introduced TestDispatcherManagerCloseOnSinkError test verifying that DispatcherManager closes itself when sink returns non-cancellation error.

Sequence Diagram

sequenceDiagram
    participant DM as DispatcherManager
    participant Sink as Sink
    participant HQ as Heartbeat<br/>Queue
    participant Maint as Maintainer

    DM->>Sink: runSinkWithExitHandling()
    activate Sink
    Sink->>Sink: Run()
    Sink-->>DM: returns error
    deactivate Sink

    alt Context Cancelled
        DM->>DM: return (normal shutdown)
    else Non-Nil Error
        DM->>HQ: reportErrorToMaintainer()
        HQ->>HQ: enqueue error message<br/>(time, node, code, msg)
        HQ->>Maint: notify
        DM->>DM: close manager
    else No Error (Unexpected)
        DM->>DM: log unexpected exit
        DM->>DM: close manager
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Hoppy times ahead, I'd say!
When sinks exit in the wrong way,
We catch the error, report with care,
And close things down—no wasteful despair!
CPU pegging? Not today, hooray! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: proactively closing DispatcherManager when sink exits to prevent OOM, which directly addresses the linked issue.
Description check ✅ Passed The description includes all required template sections: issue number (close #4064), detailed explanation of the problem and solution, test coverage (unit test), answers to compatibility/documentation questions, and a release note.
Linked Issues check ✅ Passed The code changes fully address issue #4064 by preventing unbounded buffering and resource exhaustion when Kafka sink fails by closing DispatcherManager proactively and reporting errors to maintainers.
Out of Scope Changes check ✅ Passed All changes are focused and in-scope: added sink exit handling, error reporting to maintainer, and corresponding unit test to verify behavior when sink exits with error.

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

✨ Finishing touches
  • 📝 Generate docstrings

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 and usage tips.

@ti-chi-bot
Copy link

ti-chi-bot bot commented Jan 29, 2026

@wlwilliamx: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
pull-error-log-review 24f86f9 link true /test pull-error-log-review

Full PR test history. Your PR dashboard.

Details

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 kubernetes-sigs/prow repository. I understand the commands that are listed here.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

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 effectively addresses a potential OOM issue by ensuring the DispatcherManager closes proactively when a sink exits unexpectedly. The introduction of runSinkWithExitHandling and reportErrorToMaintainer is a solid approach to make the error handling more robust and prevent the loss of critical error information during shutdown. The new unit tests also provide good coverage for the added functionality. I have a few suggestions to further refine the implementation by removing a redundant error handling call, using a standardized timestamp format for better machine readability, and ensuring all unexpected sink exits are consistently reported as errors.

Comment on lines +524 to +526
} else {
log.Error("sink exited without error", zap.Stringer("changefeedID", e.changefeedID))
}

Choose a reason for hiding this comment

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

high

When the sink exits unexpectedly without an error, the code logs an error but doesn't report it to the maintainer. This is inconsistent with the case where the sink exits with an error. An unexpected exit, even without an error, is a failure condition for the changefeed that should be reported for better observability. I suggest creating and reporting an error in this case as well.

} else {
		err := errors.ErrUnexpected.GenWithStack("sink exited without error")
		log.Error("sink exited unexpectedly without returning an error",
			zap.Stringer("changefeedID", e.changefeedID),
			zap.Error(err))
		e.reportErrorToMaintainer(err)
	}

// manager proactively.
func (e *DispatcherManager) runSinkWithExitHandling(ctx context.Context) {
err := e.sink.Run(ctx)
e.handleError(ctx, err)

Choose a reason for hiding this comment

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

medium

The call to e.handleError(ctx, err) is redundant given that e.reportErrorToMaintainer(err) is called below to handle the same error. The comment for reportErrorToMaintainer correctly notes that it's a pre-emptive report to avoid losing the error due to a race with context cancellation, which is a risk with the handleError -> collectErrors path. Removing this line will simplify the logic and prevent potential double-reporting of the error.

var message heartbeatpb.HeartBeatRequest
message.ChangefeedID = e.changefeedID.ToPB()
message.Err = &heartbeatpb.RunningError{
Time: time.Now().String(),

Choose a reason for hiding this comment

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

medium

Using time.Now().String() for timestamps is not ideal as the format is not standardized and can be difficult for other systems to parse. It's better to use a standard format like time.RFC3339Nano. Using UTC is also a best practice to avoid timezone-related issues.

		Time:    time.Now().UTC().Format(time.RFC3339Nano),

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.

TiCDC Kafka sink: missing topic keeps changefeed in warning (expected) but pegs CPU/memory

1 participant