Skip to content

[WIP] memory quota optimization#5584

Closed
lidezhu wants to merge 23 commits into
masterfrom
ldz/puller-memory-quota
Closed

[WIP] memory quota optimization#5584
lidezhu wants to merge 23 commits into
masterfrom
ldz/puller-memory-quota

Conversation

@lidezhu

@lidezhu lidezhu commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Issue Number: close #xxx

What is changed and how it works?

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

@ti-chi-bot

ti-chi-bot Bot commented Jul 5, 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/needs-linked-issue 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 5, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 5, 2026

Copy link
Copy Markdown

[FORMAT CHECKER NOTIFICATION]

Notice: To remove the do-not-merge/needs-linked-issue label, please provide the linked issue number on one line in the PR body, for example: Issue Number: close #123 or Issue Number: ref #456.

📖 For more info, you can check the "Contribute Code" section in the development guide.

@ti-chi-bot

ti-chi-bot Bot commented Jul 5, 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 nongfushanquan 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 5, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

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: 76c30793-6dc1-4e71-87e1-6bf5a0f46cd1

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
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ldz/puller-memory-quota

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/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Jul 5, 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 log puller's resource control and request scheduling in TiCDC, introducing a local memory quota controller and a decentralized, priority-based store scheduler with per-store request workers and local request caches. The review feedback highlights several critical improvements: guarding against a divide-by-zero panic in requestedStore, preventing an infinite rescheduling loop for stopped subscriptions in regionFailureHandler, checking for context cancellation early in acquireEvent, and using the loop's context in the scheduler. Additionally, the reviewer suggests removing dead code in regionFailureHandler and optimizing memory allocations in regionEventHandler by storing quota leases directly.

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 on lines +105 to +106
regionRequestWorkerPerStore := scheduler.config.RegionRequestWorkerPerStore
perWorkerQueueSize := pendingRegionRequestQueueSize / int(regionRequestWorkerPerStore)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

If regionRequestWorkerPerStore is configured as 0, perWorkerQueueSize := pendingRegionRequestQueueSize / int(regionRequestWorkerPerStore) will panic with a divide-by-zero error. We should guard against this by ensuring regionRequestWorkerPerStore is at least 1.

	regionRequestWorkerPerStore := scheduler.config.RegionRequestWorkerPerStore
	if regionRequestWorkerPerStore == 0 {
		regionRequestWorkerPerStore = 1
	}
	perWorkerQueueSize := pendingRegionRequestQueueSize / int(regionRequestWorkerPerStore)

Comment on lines +82 to +84
}
r.cache.add(errInfo)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

If the subscription is already stopped (errInfo.subscribedSpan.stopped.Load() is true), and UnlockRange returns false, we should not add the error to r.cache. Doing so causes handleError to reschedule the region request for a stopped subscription, leading to an infinite loop of rescheduling and reporting. Returning early when the subscription is stopped prevents this.

	if errInfo.subscribedSpan.stopped.Load() {
		return
	}
	r.cache.add(errInfo)

Comment on lines +266 to +267
c.mu.Lock()
for c.used+bytes > c.capacity && c.used > 0 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

In acquireEvent, if the context ctx is already cancelled when the function is called, it might still allocate memory quota and return a lease if c.used+bytes <= c.capacity (since the loop is skipped). We should check ctx.Err() at the beginning of the lock block to prevent acquiring quota on a cancelled context.

Suggested change
c.mu.Lock()
for c.used+bytes > c.capacity && c.used > 0 {
c.mu.Lock()
if ctx.Err() != nil {
c.mu.Unlock()
return nil
}
for c.used+bytes > c.capacity && c.used > 0 {

// Run is the only consumer of storeAvailable, so Len > 0 means this
// GetWithContext will not block.
if s.storeAvailable.Len() > 0 {
store, ok, err := s.storeAvailable.GetWithContext(context.Background())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using context.Background() instead of the loop's ctx in GetWithContext prevents the call from being interrupted if ctx is cancelled. Even if Len() > 0 makes it unlikely to block under normal conditions, using ctx is much safer and ensures robust shutdown behavior.

Suggested change
store, ok, err := s.storeAvailable.GetWithContext(context.Background())
store, ok, err := s.storeAvailable.GetWithContext(ctx)

type errCache struct {
sync.Mutex
cache []regionErrorInfo
errCh chan regionErrorInfo

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The errCh channel, along with dispatchBatch and dispatch methods in errCache, are completely unused in the new implementation because failureHandler.Run directly pops and processes batches from r.cache.popBatch inline. Removing this dead code will improve maintainability.

Comment on lines +139 to +144
quotaEvents := make([]*regionEvent, 0, len(events))
for _, event := range events {
event := event
if event.memoryQuota != nil {
quotaEvents = append(quotaEvents, &event)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Defining quotaEvents as []*regionEvent and taking the address of a loop-local copy of event (event := event) causes these local copies to escape to the heap because releaseMemoryQuota is called asynchronously inside the consumeKVEvents callback. Since we only need to release the memory quota, we can store *memoryQuotaLease directly in a quotaLeases slice, avoiding any heap allocation of regionEvent copies.

	quotaLeases := make([]*memoryQuotaLease, 0, len(events))
	for _, event := range events {
		if event.memoryQuota != nil {
			quotaLeases = append(quotaLeases, event.memoryQuota)
		}

Comment on lines +170 to +174
releaseMemoryQuota := func() {
for _, event := range quotaEvents {
event.releaseMemoryQuota()
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Update releaseMemoryQuota to release the leases directly from the quotaLeases slice.

Suggested change
releaseMemoryQuota := func() {
for _, event := range quotaEvents {
event.releaseMemoryQuota()
}
}
releaseMemoryQuota := func() {
for _, lease := range quotaLeases {
lease.Release()
}
}

@lidezhu lidezhu closed this Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do-not-merge/needs-linked-issue 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. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant