Skip to content

[WIP] memory quota optimization #5589

Draft
lidezhu wants to merge 5 commits into
ldz/improve-log-puller052302from
ldz/puller-memory-quota
Draft

[WIP] memory quota optimization #5589
lidezhu wants to merge 5 commits into
ldz/improve-log-puller052302from
ldz/puller-memory-quota

Conversation

@lidezhu

@lidezhu lidezhu commented Jul 6, 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 6, 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 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 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: e969b7d1-83ea-4ded-bdef-d18fee1a8725

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 commented Jul 6, 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

@ti-chi-bot ti-chi-bot Bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Jul 6, 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 introduces a local memory quota controller (memoryQuotaController) for the log puller in TiCDC to manage memory usage of changefeed subscriptions and control admissions (e.g., pausing warming or freezing new scans) based on memory usage ratios. The feedback highlights critical issues and optimization opportunities: potential memory leaks in allowNewScan and acquireEvent where calling getOrCreateChangefeedStateLocked on removed subscriptions recreates and leaks state, a bug in acquireEvent where it should abort if the subscription is removed while blocked, and an optimization in regionEventHandler.Handle to store *memoryQuotaLease pointers directly instead of copying large regionEvent structs to reduce heap escapes and GC pressure.

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/memory_quota.go Outdated
Comment on lines +232 to +255
func (c *memoryQuotaController) allowNewScan(span *subscribedSpan) (bool, string) {
if span == nil || span.meta.isSystem() {
return true, ""
}

c.mu.Lock()
c.refreshLevelLocked()
level := c.level
state := c.getOrCreateChangefeedStateLocked(span.meta.ChangefeedID)
c.mu.Unlock()

if level == admissionFreezeAllNewScans {
return false, deferReasonMemoryFreeze
}
if level == admissionPauseWarming {
state.mu.Lock()
phase := state.phase
state.mu.Unlock()
if phase == changefeedPhaseWarming {
return false, deferReasonMemoryWarming
}
}
return true, ""
}

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

The allowNewScan method calls getOrCreateChangefeedStateLocked which creates a new changefeedQuotaState if it does not exist. If a subscription has already been removed, calling allowNewScan will recreate the state and put it back into c.changefeeds. Since removeSubscription is only called once when the subscription is removed, this recreated state will never be cleaned up, leading to a permanent memory leak. To fix this, check if the subscription is still active before accessing or creating the state.

func (c *memoryQuotaController) allowNewScan(span *subscribedSpan) (bool, string) {
	if span == nil || span.meta.isSystem() {
		return true, ""
	}

	c.mu.Lock()
	c.refreshLevelLocked()
	level := c.level
	state, ok := c.changefeeds[span.meta.ChangefeedID]
	if !ok {
		c.mu.Unlock()
		return true, ""
	}
	state.mu.Lock()
	if _, ok := state.spans[span.subID]; !ok {
		state.mu.Unlock()
		c.mu.Unlock()
		return true, ""
	}
	phase := state.phase
	state.mu.Unlock()
	c.mu.Unlock()

	if level == admissionFreezeAllNewScans {
		return false, deferReasonMemoryFreeze
	}
	if level == admissionPauseWarming {
		if phase == changefeedPhaseWarming {
			return false, deferReasonMemoryWarming
		}
	}
	return true, ""
}

Comment thread logservice/logpuller/memory_quota.go Outdated
Comment on lines +257 to +308
func (c *memoryQuotaController) acquireEvent(
ctx context.Context,
span *subscribedSpan,
bytes uint64,
) *memoryQuotaLease {
if span == nil || span.meta.isSystem() || bytes == 0 {
return nil
}

c.mu.Lock()
for c.used+bytes > c.capacity && c.used > 0 {
if ctx.Err() != nil {
c.mu.Unlock()
return nil
}
c.cond.Wait()
}
c.used += bytes
c.refreshLevelLocked()
state := c.getOrCreateChangefeedStateLocked(span.meta.ChangefeedID)

lease := &memoryQuotaLease{}
lease.release = func() {
c.mu.Lock()
if c.used >= bytes {
c.used -= bytes
} else {
c.used = 0
}
c.refreshLevelLocked()
c.cond.Broadcast()
c.mu.Unlock()

state.mu.Lock()
delete(state.leases, lease)
if state.memUsed >= bytes {
state.memUsed -= bytes
} else {
state.memUsed = 0
}
state.mu.Unlock()

c.onMemoryAvailable()
}

state.mu.Lock()
state.leases[lease] = span.subID
state.memUsed += bytes
state.mu.Unlock()
c.mu.Unlock()
return lease
}

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

The acquireEvent method calls getOrCreateChangefeedStateLocked which creates a new changefeedQuotaState if it does not exist. If a subscription has already been removed, calling acquireEvent will recreate the state and put it back into c.changefeeds, leaking it permanently. Additionally, if the subscription is removed while acquireEvent is blocked on c.cond.Wait(), it should abort and return nil instead of acquiring the quota. To fix this, check if the subscription is still active before the loop and after waking up from c.cond.Wait().

func (c *memoryQuotaController) acquireEvent(
	ctx context.Context,
	span *subscribedSpan,
	bytes uint64,
) *memoryQuotaLease {
	if span == nil || span.meta.isSystem() || bytes == 0 {
		return nil
	}

	c.mu.Lock()
	state, ok := c.changefeeds[span.meta.ChangefeedID]
	if !ok {
		c.mu.Unlock()
		return nil
	}
	state.mu.Lock()
	if _, ok := state.spans[span.subID]; !ok {
		state.mu.Unlock()
		c.mu.Unlock()
		return nil
	}
	state.mu.Unlock()

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

		state, ok = c.changefeeds[span.meta.ChangefeedID]
		if !ok {
			c.mu.Unlock()
			return nil
		}
		state.mu.Lock()
		if _, ok := state.spans[span.subID]; !ok {
			state.mu.Unlock()
			c.mu.Unlock()
			return nil
		}
		state.mu.Unlock()
	}
	c.used += bytes
	c.refreshLevelLocked()

	lease := &memoryQuotaLease{}
	lease.release = func() {
		c.mu.Lock()
		if c.used >= bytes {
			c.used -= bytes
		} else {
			c.used = 0
		}
		c.refreshLevelLocked()
		c.cond.Broadcast()
		c.mu.Unlock()

		state.mu.Lock()
		delete(state.leases, lease)
		if state.memUsed >= bytes {
			state.memUsed -= bytes
		} else {
			state.memUsed = 0
		}
		state.mu.Unlock()

		c.onMemoryAvailable()
	}

	state.mu.Lock()
	state.leases[lease] = span.subID
	state.memUsed += bytes
	state.mu.Unlock()
	c.mu.Unlock()
	return lease
}

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

Instead of copying the large regionEvent structs and taking their addresses (which causes them to escape to the heap and increases GC pressure), you can store the *memoryQuotaLease pointers directly in a slice. This is much more efficient and idiomatic.

	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, avoiding unnecessary struct dereferencing.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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