Skip to content

fix: throttle CN S3 writes under memory pressure - #24268

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
LeftHandCold:fix-cn-s3-oom-throttle
May 4, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
LeftHandCold:fix-cn-s3-oom-throttle

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented May 3, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

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

Which issue(s) this PR fixes:

Fixes #24267

What this PR does / why we need it:

This PR reduces CN OOM risk for large LOAD DATA / INSERT SELECT workloads that write through the CN S3 path.

The observed OOM case loaded a large CSV with PARALLEL 'TRUE' and immediately copied the data into another wide table containing vecf32(1024), text, and json columns. The CN RSS crossed the CNFlushS3 soft budget and approached the cgroup limit while pinned memory remained low, which means the normal insert.ToWriteS3 path was not applying enough backpressure before feeding batches into CNS3DataWriter.

Changes:

  • Add RSS-aware hard-limit checks to AcquirePolicyForCNFlushS3, including already reserved memory.
  • Add a forced refresh path so S3 insert memory checks can use current RSS instead of waiting for the normal refresh interval.
  • Make insert.ToWriteS3 reserve memory against CNMemoryThrottler before writing each batch.
  • When the CN S3 memory budget is exhausted, flush the current S3 writer state, append the generated block-info rows to the insert result, release the reservation, and retry once.
  • Expose a CNS3Writer.SyncAndFillBlockInfoBat helper to support safe partial flushes without changing final insert result semantics.

Testing

  • go test ./pkg/common/rscthrottler ./pkg/sql/colexec/insert ./pkg/sql/colexec ./pkg/objectio/ioutil -count=1

Add RSS-aware CNFlushS3 throttling and flush S3 insert writers when the CN memory budget is exhausted.

Co-authored-by: Copilot <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Throttle CN S3 writes under memory pressure with RSS-aware limits

🐞 Bug fix ✨ Enhancement

Grey Divider

Walkthroughs

Description
• Add RSS-aware hard-limit checks to CN S3 memory throttling policy
• Implement forced refresh path for current RSS memory checks
• Reserve memory against throttler before writing S3 batches
• Flush S3 writer state when memory budget exhausted, retry once
• Expose helper method for safe partial S3 writer flushes
Diagram
flowchart LR
  A["S3 Insert Write"] --> B["acquireS3WriteMemory"]
  B --> C["ForceRefresh Throttler"]
  C --> D["Acquire Memory"]
  D -->|Success| E["Write Batch"]
  D -->|Fail| F["flushS3WriterOnMemoryPressure"]
  F --> G["SyncAndFillBlockInfoBat"]
  G --> H["Release Memory"]
  H --> I["Retry Acquire"]
  I -->|Success| E
  E --> J["Track s3MemGranted"]
  J --> K["Release on Completion"]
Loading

Grey Divider

File Changes

1. pkg/common/rscthrottler/resource_throttler.go ✨ Enhancement +38/-4

Add RSS-aware memory acquisition with forced refresh

• Add ForceRefresh() method to bypass refresh interval checks
• Refactor Refresh() to call internal refresh(force bool) method
• Implement acquireWithinRSSLimit() function with RSS-aware hard-limit checks
• Include already reserved memory in RSS limit calculations
• Update AcquirePolicyForCNFlushS3() to use new RSS-aware acquisition logic

pkg/common/rscthrottler/resource_throttler.go


2. pkg/common/rscthrottler/resource_throttler_test.go 🧪 Tests +51/-0

Add tests for CN S3 flush memory policy

• Add comprehensive test suite for AcquirePolicyForCNFlushS3()
• Test denial when RSS already crosses limit
• Test denial when projected RSS with reservation crosses limit
• Test successful acquisition and memory reservation

pkg/common/rscthrottler/resource_throttler_test.go


3. pkg/sql/colexec/insert/insert.go ✨ Enhancement +85/-2

Integrate S3 memory throttling into insert pipeline

• Initialize S3 memory throttler and tracking variables in Prepare()
• Add acquireS3WriteMemory() method to reserve memory before batch writes
• Implement flushS3WriterOnMemoryPressure() to flush writer and retry on exhaustion
• Add forcedRefresh() helper to call ForceRefresh() when available
• Call releaseS3MemGrant() on completion and error paths
• Integrate memory acquisition into S3 write pipeline

pkg/sql/colexec/insert/insert.go


View more (3)
4. pkg/sql/colexec/insert/insert_test.go 🧪 Tests +75/-0

Add tests for S3 insert memory acquisition

• Add testS3MemThrottler mock implementing throttler interface
• Test successful memory acquisition with forced refresh
• Test memory flush and retry behavior on exhaustion
• Verify memory grant tracking and release

pkg/sql/colexec/insert/insert_test.go


5. pkg/sql/colexec/insert/types.go ✨ Enhancement +12/-0

Add S3 memory grant tracking to container

• Add s3MemGranted field to track reserved memory amount
• Add s3MemThrottler field to store throttler reference
• Implement releaseS3MemGrant() helper method
• Call releaseS3MemGrant() in Reset() and Free() methods

pkg/sql/colexec/insert/types.go


6. pkg/sql/colexec/s3util.go ✨ Enhancement +24/-0

Add safe partial flush helper for S3 writer

• Add SyncAndFillBlockInfoBat() method for safe partial flushes
• Sync writer and take results without changing final semantics
• Expand object stats to batch for block info rows
• Support memory-pressure-triggered flushes with result preservation

pkg/sql/colexec/s3util.go


Grey Divider

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented May 3, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider


Action required

1. S3 memory grant leaks 🐞 Bug ☼ Reliability
Description
insert_s3 returns early on multiple error paths without releasing already-acquired CN S3 memory
reservations, leaving the global throttler's reserved memory elevated until Reset/Free runs. This
can throttle or fail unrelated concurrent workloads after a failed S3 insert.
Code

pkg/sql/colexec/insert/insert.go[R152-158]

+			if err = insert.acquireS3WriteMemory(proc, analyzer, input.Batch.Size()); err != nil {
+				insert.ctr.state = vm.End
+				return vm.CancelResult, err
+			}
  		err = insert.ctr.s3Writer.Write(proc.Ctx, input.Batch)
  		if err != nil {
  			insert.ctr.state = vm.End
Evidence
Reservations are added by acquireS3WriteMemory (incrementing s3MemGranted after a successful
Acquire). Several error returns in insert_s3 (and in flushS3WriterOnMemoryPressure when
SyncAndFillBlockInfoBat fails) do not call releaseS3MemGrant; release is only guaranteed on the
success path in insert_s3 and in Reset/Free.

pkg/sql/colexec/insert/insert.go[130-177]
pkg/sql/colexec/insert/insert.go[191-254]
pkg/sql/colexec/insert/types.go[98-147]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
With the new S3 write memory reservations (`s3MemGranted`), several error returns in `insert_s3()` (e.g., `ChildrenCall` error, `Write` error, `flushTailBatch` error) return without releasing the reservation. Additionally, `flushS3WriterOnMemoryPressure()` returns errors from `SyncAndFillBlockInfoBat`/`Append` without releasing. This can leave the global throttler in a reserved state until `Reset/Free` happens.
### Issue Context
`releaseS3MemGrant()` exists and is called on the success path and in `Reset/Free`, but not on these early error exits. After a failure, other pipelines can see reduced availability because the reservation remains.
### Fix Focus Areas
- pkg/sql/colexec/insert/insert.go[130-177]
- pkg/sql/colexec/insert/insert.go[191-254]
- pkg/sql/colexec/insert/types.go[98-147]
### Suggested change
- In `insert_s3()`, ensure any return with `err != nil` calls `insert.releaseS3MemGrant()` before returning.
- A straightforward approach: in each explicit error branch, call `insert.releaseS3MemGrant()` before `return`.
- Or add a function-level `defer` that releases only when returning an error (careful to not release on the normal success path where the reservation is intentionally held until Eval completes).
- In `flushS3WriterOnMemoryPressure()`, if `SyncAndFillBlockInfoBat` or `Append` returns an error, release the grant before returning the error (since the caller aborts on that error anyway).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. ForceRefresh per-batch overhead ☑ 🐞 Bug ➹ Performance
Description
insert.acquireS3WriteMemory forces a throttler refresh before each batch Acquire, and
memThrottler.ForceRefresh bypasses refreshMaxInterval so the refresh path (cgroup/memory sampling +
Info log) runs every batch. This can add significant CPU/syscall overhead and produce high-volume
refresh logs on large INSERT/LOAD DATA workloads.
Code

pkg/sql/colexec/insert/insert.go[R191-201]

+func (insert *Insert) acquireS3WriteMemory(proc *process.Process, analyzer process.Analyzer, size int) error {
+	if insert.isMemoryTable() || insert.ctr.s3MemThrottler == nil || size <= 0 {
+		return nil
+	}
+
+	ask := int64(size)
+	forcedRefresh(insert.ctr.s3MemThrottler)
+	if _, ok := insert.ctr.s3MemThrottler.Acquire(ask); ok {
+		insert.ctr.s3MemGranted += ask
+		return nil
+	}
Evidence
The insert S3 path calls forcedRefresh before each Acquire, which will invoke ForceRefresh when the
underlying throttler is memThrottler. ForceRefresh calls refresh(true), which bypasses the interval
guard and always executes the full refresh body and its deferred Info log.

pkg/sql/colexec/insert/insert.go[191-224]
pkg/common/rscthrottler/resource_throttler.go[101-165]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`forcedRefresh()` is executed for every S3 batch write and will call `memThrottler.ForceRefresh()`, which bypasses the refresh interval and runs the full refresh body (cgroup + RSS sampling) and its deferred Info log each time. This can cause substantial overhead and excessive log volume for large inserts.
### Issue Context
The PR intentionally wants "current RSS" for memory checks, but doing a full refresh + Info log per batch is much more frequent than the prior 10s refresh cadence.
### Fix Focus Areas
- pkg/sql/colexec/insert/insert.go[191-224]
- pkg/common/rscthrottler/resource_throttler.go[101-165]
### Suggested change
- Only force refresh when needed (e.g., when the last refresh age exceeds a small sub-interval like 100–500ms, or only after an `Acquire` denial).
- Prevent `ForceRefresh()` from emitting an Info log every time (e.g., log only on non-forced refresh, or downshift forced-refresh logs to Debug / sample them).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Copilot AI 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.

Pull request overview

This PR introduces tighter CN-side memory backpressure for the “write-to-S3 from CN” insert/load path to reduce OOM risk under high RSS scenarios (e.g., large LOAD DATA / INSERT SELECT into wide rows).

Changes:

  • Adds RSS-aware hard-limit logic (including already reserved memory) to the CNFlushS3 memory throttler, plus a forced-refresh option.
  • Makes insert.ToWriteS3 reserve CNFlushS3 memory per input batch and (on pressure) partially flushes S3 writer state, appends block-info rows, releases the reservation, and retries.
  • Adds CNS3Writer.SyncAndFillBlockInfoBat to support partial flushes while preserving insert result semantics.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
pkg/sql/colexec/s3util.go Adds SyncAndFillBlockInfoBat helper for partial S3 writer flushes that produce block-info batches.
pkg/sql/colexec/insert/types.go Tracks and releases CNFlushS3 memory reservations on Reset/Free.
pkg/sql/colexec/insert/insert.go Reserves throttler memory before S3 writes; flushes writer on pressure; adds forced refresh support.
pkg/sql/colexec/insert/insert_test.go Adds unit tests for the new S3 write memory acquisition/retry behavior.
pkg/common/rscthrottler/resource_throttler.go Adds ForceRefresh and RSS-aware acquire policy for CNFlushS3.
pkg/common/rscthrottler/resource_throttler_test.go Adds tests covering the new CNFlushS3 RSS-limit acquisition behavior.
Comments suppressed due to low confidence (1)

pkg/common/rscthrottler/resource_throttler.go:165

  • ForceRefresh() currently runs the full refresh(true) logic (total memory + cgroup + process RSS) and emits an Info log on every call. With the new S3 path calling forced refreshes frequently, this can become extremely expensive and noisy. Consider making ForceRefresh cheaper (e.g., refresh RSS only) and/or keeping the logging and heavyweight total/cgroup refresh behind an interval even when forced.
func (m *memThrottler) Refresh() {
	m.refresh(false)
}

func (m *memThrottler) ForceRefresh() {
	m.refresh(true)
}

func (m *memThrottler) refresh(force bool) {
	last := m.lastRefresh.Load()
	now := time.Now().UnixNano()

	if !force && time.Duration(now-last) <= refreshMaxInterval {
		return
	}

	m.lastRefresh.Store(now)

	var (
		err    error
		cgroup uint64
		info   *process.MemoryInfoStat

		total uint64
	)

	defer func() {
		logutil.Info(
			fmt.Sprintf("%s-Refresh", MemoryThrottlerLogHeader),
			zap.String("detail", m.String()),
			zap.Error(err),
		)
	}()

	total = objectio.TotalMem()
	cgroup, err = memlimit.FromCgroup()

	if cgroup != 0 && cgroup < total {
		m.actualTotalMemory.Store(cgroup)
	} else if total != 0 {
		m.actualTotalMemory.Store(total)
	} else {
		m.actualTotalMemory.Store(math.MaxInt64)
		logutil.Info(
			fmt.Sprintf("%s-Refresh", MemoryThrottlerLogHeader),
			zap.String("err", "cannot get the total memory, unlimited"),
		)
	}

	// if the const limit option is set, we should not change the limit.
	if m.options.constLimit < 0 {
		m.limit.Store(int64(float64(m.actualTotalMemory.Load()) * m.limitRate))
	}

	if m.proc == nil {
		m.proc, _ = process.NewProcess(int32(os.Getpid()))
	}

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

	m.cgroup.Store(cgroup)
	m.total.Store(total)
}

Comment thread pkg/sql/colexec/insert/insert.go Resolved
Comment thread pkg/sql/colexec/insert/insert.go Resolved
Comment thread pkg/sql/colexec/insert/insert.go Resolved
Comment thread pkg/sql/colexec/insert/insert.go Resolved
Avoid reserving full input batches for normal CN S3 writes and only force-refresh RSS after acquire misses. Keep pipeline flush conservatively accounted because async sink jobs can retain multiple staged batches.\n\nCo-authored-by: Copilot <[email protected]>
@mergify

mergify Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-04 12:19 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-05-04 12:19 UTC · at 46ef0191c4a0b4c28a2aa5ec6d28c3d9e40d55ad · squash

This pull request spent 15 seconds in the queue, including 2 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage

This branch was previously deployed

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

Labels

kind/bug Something isn't working kind/enhancement size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CN OOM during large LOAD DATA and INSERT SELECT S3 writes

6 participants