Skip to content

control merge mem - #22682

Merged
mergify[bot] merged 3 commits into
matrixorigin:mainfrom
aptend:control-mem
Oct 27, 2025
Merged

mergify[bot] merged 3 commits into
matrixorigin:mainfrom
aptend:control-mem

Conversation

@aptend

@aptend aptend commented Oct 24, 2025 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #22638

What this PR does / why we need it:

  • refresh rss when checking available memory in merge scheduling
  • better memory cost estimation

PR Type

Enhancement, Bug fix


Description

  • Add specialized merge memory throttling with RSS refresh debouncing

  • Improve merge memory cost estimation calculation

  • Replace unsafe string access with safe vector methods

  • Refactor merge scheduler memory management configuration


Diagram Walkthrough

flowchart LR
  A["Memory Throttler"] -->|Add specializedForMerge| B["Merge-specific Mode"]
  B -->|Debounce RSS refresh| C["Accurate Memory Tracking"]
  D["Merge Scheduler"] -->|Use specialized throttler| B
  E["Memory Estimation"] -->|Adjust margin calculation| F["Better Cost Estimation"]
Loading

File Walkthrough

Relevant files
Enhancement
resource_throttler.go
Add merge-specialized memory throttling with debounced RSS refresh

pkg/common/rscthrottler/resource_throttler.go

  • Add mergeAvailDebounce field for debouncing RSS refresh in merge mode
  • Add specializedForMerge option to enable merge-specific memory
    tracking
  • Implement specialized Available() logic that refreshes RSS every
    second when in merge mode
  • Replace negative check with max() function for cleaner code
  • Add WithSpecializedForMerge() option function
+28/-5   
scheduler.go
Configure merge scheduler with specialized throttler         

pkg/vm/engine/tae/db/merge/scheduler.go

  • Replace WithAllowOutOfLimitAcquire() with WithSpecializedForMerge()
    option
  • Remove PrintUsage() call from heartbeat handler
  • Keep Refresh() call for memory state updates
+1/-2     
task.go
Improve merge memory cost estimation margin                           

pkg/vm/engine/tae/mergesort/task.go

  • Adjust merge size estimation margin from totalSize / 3 * 2 to
    totalSize / 2 * 3
  • Increases memory margin allocation for garbage collection overhead
+1/-1     
Bug fix
service_txn_event.go
Replace unsafe string access with safe methods                     

pkg/txn/trace/service_txn_event.go

  • Replace UnsafeGetStringAt() with GetStringAt() for safer vector access
  • Apply change to both method and value column reads
+2/-2     

@qodo-code-review

qodo-code-review Bot commented Oct 24, 2025 •

Copy link
Copy Markdown

You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Resource probing risk

Description: Updating RSS by reading process.MemoryInfo() on a debounce without error backoff or
context may introduce performance perturbation and potential timing side-channels on
memory usage; verify this frequent RSS probing under high concurrency does not expose
sensitive process characteristics or become abusable for DoS.
resource_throttler.go [184-198]

Referred Code
if m.options.specializedForMerge {
	now := time.Now().UnixNano()
	if time.Duration(now-m.mergeAvailDebounce.Load()) > time.Second {
		m.mergeAvailDebounce.Store(now)
		if m.proc == nil {
			m.proc, _ = process.NewProcess(int32(os.Getpid()))
		}

		if info, err := m.proc.MemoryInfo(); err == nil {
			rss = int64(info.RSS)
			m.rss.Store(rss)
		}
	}

	return max(0, limit-rss-reserved)
Ticket Compliance
🟡
🎫 #22638
🟢 Refresh/track actual RSS during merge to avoid oversubscription under limits like 25G
memory and 5G memory cache.
Improve memory cost/merge size estimation to include overhead/margins relevant to merge.
Ensure safety/stability during merge-related operations (avoid unsafe access that could
impact reliability).
⚪ Control merge executor memory by accounting for additional overhead such as memory cache
and vector pool.
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
⚪
No custom compliance provided

Follow the guide to enable custom compliance check.

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review

qodo-code-review Bot commented Oct 24, 2025 •

Copy link
Copy Markdown

You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Memory estimation margin calculation appears inverted

The suggestion points out that the memory estimation margin in EstimateMergeSize
was changed from totalSize / 3 * 2 (66%) to totalSize / 2 * 3 (150%). It
recommends verifying if this substantial increase is intentional, as it may lead
to over-allocating memory.

Examples:

pkg/vm/engine/tae/mergesort/task.go [337]
	estSize += totalSize / 2 * 3 // leave some margin for gc

Solution Walkthrough:

Before:

func EstimateMergeSize(objs iter.Seq[*objectio.ObjectStats]) int {
    estSize := 0
    totalSize := 0
    for obj := range objs {
        // ...
        totalSize += int(obj.OriginSize()) / 2
    }
    // margin is ~67% of totalSize
    estSize += totalSize / 3 * 2 
    return estSize
}

After:

func EstimateMergeSize(objs iter.Seq[*objectio.ObjectStats]) int {
    estSize := 0
    totalSize := 0
    for obj := range objs {
        // ...
        totalSize += int(obj.OriginSize()) / 2
    }
    // margin is 150% of totalSize
    estSize += totalSize / 2 * 3
    return estSize
}
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical logic change in memory estimation, where the margin is increased from ~67% to 150%, and rightly questions if this was an intentional inversion or a typo, which has a major impact on memory allocation.

High
Possible issue
Handle process creation error

Handle the error returned by process.NewProcess() to prevent a potential panic
when m.proc.MemoryInfo() is called on a nil m.proc.

pkg/common/rscthrottler/resource_throttler.go [184-199]

 if m.options.specializedForMerge {
     now := time.Now().UnixNano()
     if time.Duration(now-m.mergeAvailDebounce.Load()) > time.Second {
         m.mergeAvailDebounce.Store(now)
         if m.proc == nil {
-            m.proc, _ = process.NewProcess(int32(os.Getpid()))
+            var err error
+            m.proc, err = process.NewProcess(int32(os.Getpid()))
+            if err != nil {
+                logutil.Error("failed to create process", zap.Error(err))
+                return max(0, limit-rss-reserved)
+            }
         }
 
         if info, err := m.proc.MemoryInfo(); err == nil {
             rss = int64(info.RSS)
             m.rss.Store(rss)
         }
     }
 
     return max(0, limit-rss-reserved)
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential nil pointer dereference due to an unhandled error in code added by this PR, which could cause the application to crash.

Medium
General
Fix integer division order

Change the calculation from totalSize / 2 * 3 to totalSize * 3 / 2 to avoid
precision loss from integer division and ensure a more accurate memory
estimation.

pkg/vm/engine/tae/mergesort/task.go [337]

-estSize += totalSize / 2 * 3 // leave some margin for gc
+estSize += totalSize * 3 / 2 // leave some margin for gc
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out a potential precision loss due to integer division order in a line modified by the PR, improving the accuracy of the memory size estimation.

Low
  • Update

@mergify mergify Bot added the queued label Oct 27, 2025
@mergify
mergify Bot merged commit ae0a689 into matrixorigin:main Oct 27, 2025
@mergify mergify Bot removed the queued label Oct 27, 2025
fengttt pushed a commit to fengttt/matrixone that referenced this pull request May 7, 2026
- refresh rss when checking available memory in merge scheduling
- better memory cost estimation

Approved by: @XuPeng-SH, @zhangxu19830126

This branch was previously deployed

1 inactive deployment
ci — b902f49f Deployed Oct 27, 2025 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement Review effort 3/5 size/S Denotes a PR that changes [10,99] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants