Skip to content

control merge mem 3.0 - #22661

Merged
4 commits merged into
matrixorigin:3.0-devfrom
aptend:control-mem-3.0
Oct 24, 2025
Merged

4 commits merged into
matrixorigin:3.0-devfrom
aptend:control-mem-3.0

Conversation

@aptend

@aptend aptend commented Oct 22, 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

  • Refresh RSS memory usage periodically for merge scheduling

  • Improve memory cost estimation with larger safety margin

  • Sort layer zero objects by sort key for better merge efficiency

  • Rename option to clarify specialized merge memory handling


Diagram Walkthrough

flowchart LR
  A["Memory Throttler"] -->|"Add debounce refresh"| B["Periodic RSS Update"]
  A -->|"Rename option"| C["specializedForMerge"]
  D["Merge Scheduler"] -->|"Use new option"| C
  E["Layer Zero Merge"] -->|"Sort by sort key"| F["Better object ordering"]
  G["Merge Size Estimation"] -->|"Increase margin"| H["4x safety factor"]
Loading

File Walkthrough

Relevant files
Enhancement
resource_throttler.go
Add debounced RSS refresh for merge memory tracking           

pkg/common/rscthrottler/resource_throttler.go

  • Add mergeAvailDebounce field to debounce RSS refresh operations
  • Rename limitIsTheBoss option to specializedForMerge for clarity
  • Implement periodic RSS refresh (every 1 second) when specialized for
    merge
  • Use actual process memory info instead of just limit-based calculation
  • Simplify available memory calculation with max() helper
+24/-13 
scheduler.go
Update merge scheduler for new memory option                         

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

  • Update merge scheduler to use renamed WithSpecializedForMerge() option
  • Remove redundant PrintUsage() call from heartbeat handler
  • Keep Refresh() call for periodic memory refresh
+1/-2     
statLayerZero.go
Sort layer zero objects by sort key                                           

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

  • Add imports for sort, types, and compute packages
  • Sort layer zero objects by sort key zone map minimum value
  • Use type and scale information for proper comparison during sort
  • Only sort when sort key type is not T_any
+16/-0   
Bug fix
task.go
Increase merge size estimation safety margin                         

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

  • Increase GC safety margin multiplier from 2 to 4 in merge size
    estimation
  • Provides better memory cost estimation with larger buffer
+1/-1     

@qodo-code-review

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

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
⚪
Resource handle leak

Description: The RSS refresh path creates a process handle only once and never closes it, which may
leak OS resources if process.NewProcess allocates handles that require explicit closure.
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
🟢 Periodically refresh actual memory usage (RSS) so scheduling decisions reflect real
process memory.
Provide safer/larger margin in memory cost estimation for merges.
⚪ Improve memory control for merge scheduling under constrained environments (e.g., 25G
limit with 5G cache) to prevent uncontrolled usage.
Control merge executor memory by accounting for additional overhead sources 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 22, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Memory estimation relies on arbitrary multipliers

The memory cost estimation for merges relies on an arbitrary multiplier that was
doubled. Instead of adjusting this "magic number," a more robust, principled
estimation model should be developed based on an analysis of memory consumption
during merges.

Examples:

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

Solution Walkthrough:

Before:

func EstimateMergeSize(objs iter.Seq[*objectio.ObjectStats]) int {
    estSize := 0
    totalSize := 0
    for obj := range objs {
        // ... various estimations
        totalSize += int(obj.OriginSize()) / 2
    }
    // leave some margin for gc
    estSize += totalSize / 3 * 2 
    return estSize
}

After:

func EstimateMergeSize(objs iter.Seq[*objectio.ObjectStats]) int {
    // A principled model based on deeper analysis of memory consumption.
    // This would replace arbitrary multipliers with calculations based on:
    // - Sort key data types and sizes
    // - Number of objects and rows
    // - Compression ratios
    // - Observed peak memory usage from previous merges
    estSize := PrincipledMemoryEstimation(objs)
    return estSize
}
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a heuristic-based change and proposes a more robust, principled architectural improvement, which would significantly enhance system stability and resource management.

Medium
Possible issue
Fix race conditions in throttling logic

Fix two race conditions in the specializedForMerge logic. Use an atomic
CompareAndSwap for the debouncing logic to prevent concurrent RSS refreshes, and
ensure thread-safe initialization of 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()))
-			}
-
-			if info, err := m.proc.MemoryInfo(); err == nil {
-				rss = int64(info.RSS)
-				m.rss.Store(rss)
+		last := m.mergeAvailDebounce.Load()
+		if time.Duration(now-last) > time.Second {
+			if m.mergeAvailDebounce.CompareAndSwap(last, now) {
+				if m.proc == nil {
+					// Should be initialized in NewMemThrottler, but as a fallback:
+					m.proc, _ = process.NewProcess(int32(os.Getpid()))
+				}
+				if m.proc != nil {
+					if info, err := m.proc.MemoryInfo(); err == nil {
+						newRss := int64(info.RSS)
+						m.rss.Store(newRss)
+						rss = newRss
+					}
+				}
 			}
 		}
-
-		return max(0, limit-rss-reserved)
+		return max(0, limit-m.rss.Load()-reserved)
 	}
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies two race conditions in newly added code and proposes a valid fix using an atomic CompareAndSwap, which improves the correctness and robustness of the concurrent logic.

Medium
General
Optimize object sorting and filtering logic

Optimize object processing by filtering the objList for valid small objects
first, and then sorting the much smaller, filtered list. This improves
efficiency and avoids side effects from sorting the input slice in place.

pkg/vm/engine/tae/db/merge/statLayerZero.go [284-302]

 		objs := make([]*objectio.ObjectStats, 0, stats.Count)
-		typ := objList[0].SortKeyZoneMap().GetType()
-		scale := objList[0].SortKeyZoneMap().GetScale()
-		if typ != types.T_any {
-			sort.Slice(objList, func(i, j int) bool {
-				return compute.Compare(
-					objList[i].SortKeyZoneMap().GetMinBuf(),
-					objList[j].SortKeyZoneMap().GetMinBuf(),
-					typ,
-					scale,
-					scale,
-				) < 0
-			})
-		}
 		for _, obj := range objList {
 			if IsValidLayerZeroSmallObj(obj, opts) {
 				objs = append(objs, obj)
 			}
 		}
 
+		if len(objs) > 0 {
+			typ := objs[0].SortKeyZoneMap().GetType()
+			scale := objs[0].SortKeyZoneMap().GetScale()
+			if typ != types.T_any {
+				sort.Slice(objs, func(i, j int) bool {
+					return compute.Compare(
+						objs[i].SortKeyZoneMap().GetMinBuf(),
+						objs[j].SortKeyZoneMap().GetMinBuf(),
+						typ,
+						scale,
+						scale,
+					) < 0
+				})
+			}
+		}
+
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that sorting before filtering is inefficient and proposes an improved logic that filters first, which is a valid performance optimization and also avoids modifying the input slice.

Low
  • Update

@matrix-meow matrix-meow added size/S Denotes a PR that changes [10,99] lines and removed size/M Denotes a PR that changes [100,499] lines labels Oct 23, 2025
This pull request was closed.

This branch was previously deployed

1 inactive deployment
ci — e1fbee2a Deployed Oct 24, 2025 by ghost
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.

3 participants