Skip to content

fix: reduce RSS growth from dedupLoad sync.Map retention and flush convoy - #24387

Merged
mergify[bot] merged 21 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/dedupload-flush-convoy
May 20, 2026
Merged

mergify[bot] merged 21 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix/dedupload-flush-convoy

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) does this PR fix or relate to?

Fixes #24348

What this PR does / why we need it:

  • Replace sync.Map with sync.Mutex + plain map in dedupLoad so entries are fully reclaimed after deletion (sync.Map internal hash table never shrinks)
  • Each waiter now copies the loaded []byte result instead of sharing a reference, allowing the loadCall struct to be GC'd promptly without waiting for the slowest consumer
  • Change flushSemaphore from hardcoded capacity 4 to dynamic GOMAXPROCS/2 (clamped [4, 16]) to improve flush throughput on multi-core machines
  • Add 200ms timeout fallback to flushSemaphore acquisition so queued workers don't hold S3 write buffers indefinitely, avoiding convoy-induced RSS growth

What was the problem

PR #24309 introduced dedupLoad (cache stampede prevention) and flushSemaphore (thundering-herd protection). While these correctly prevent OOM in the sysbench insert-ignore scenario, under TPCC 10w/100t (100 terminals concurrent writes) they cause baseline RSS to grow from 31-36 GiB to 40-46 GiB:

  1. sync.Map never shrinks: Even after Delete, the internal hash table retains its peak size, causing monotonic memory growth under sustained load
  2. Shared []byte reference: All waiters hold a reference to loadCall.val, preventing GC until the slowest goroutine finishes — under 100 terminals this pins large metadata buffers in memory
  3. Flush convoy: With only 4 flush slots and 100 workers, 96 workers queue while holding their S3 write buffers (~hundreds of MB each), causing RSS to spike ~8-10 GiB

Combined with REPLACE INTO large transactions allocating 4+ GiB in mpool, RSS breaks 55 GiB and gets OOM-killed.

What this PR preserves

  • The optimizer selectivity guards from fix(plan): prevent OOM from non-selective secondary index range scans #24309 (root cause fix for non-selective secondary index scans) — untouched
  • The mpool leak fixes in group/exec2.go and mergeGroup.go — untouched
  • The pk_filter_base.go buffer overread fix — untouched
  • Cache stampede prevention semantics (only 1 goroutine loads per key)
  • Thundering-herd protection (concurrent flush limiting)

Test plan

  • TPCC 10w/100t: verify baseline RSS stays at 31-36 GiB (no longer inflates to 40-46 GiB)
  • Sysbench 1000w insert-ignore: verify no OOM regression (the optimizer guards still block non-selective index scans)
  • High-concurrency metadata load: verify dedupLoad still deduplicates correctly (only 1 I/O per cache key)

Ref #24348

🤖 Generated with Claude Code

…nvoy

The dedupLoad mechanism (introduced in matrixorigin#24309) used sync.Map which never
shrinks its internal hash table after Delete. Under TPCC 100-terminal
concurrency this caused monotonic memory growth. Additionally, all waiters
shared a single []byte reference, preventing GC until the slowest consumer
finished.

Replace sync.Map with mutex+map so entries are fully reclaimed on delete.
Each waiter now copies the result so the shared loadCall can be GC'd promptly.

The flushSemaphore (also from matrixorigin#24309) was hardcoded to 4 concurrent flushes.
With 100 workers hitting memory pressure, 96 would queue holding their S3
write buffers, causing RSS to spike ~8-10 GiB. Change to dynamic capacity
(GOMAXPROCS/2, clamped [4,16]) and add 200ms timeout fallback so queued
workers don't hold buffers indefinitely.

Approved by: @include-all

Ref matrixorigin#24348

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Three changes addressing real issues, but the implementation introduces new correctness/regression risks.

Blocking

1. Panic in load() permanently strands the dedup key (pkg/objectio/cache.go:259-265).

The original code used defer metaLoadGroup.Delete(key) so the entry was cleaned even on panic. The new code does:

call.val, call.err = load()
if call.err == nil {
    metaCache.Set(ctx, key, call.val, int64(len(call.val)))
}
close(call.done)

metaLoadMu.Lock()
delete(metaLoadCalls, key)
metaLoadMu.Unlock()

If load() or metaCache.Set panics, close(call.done) and the cleanup never run. The entry stays in the map forever; every future caller for that key blocks on a done channel that's never closed. This is a regression vs the original defer. Wrap with defer:

defer func() {
    metaLoadMu.Lock()
    delete(metaLoadCalls, key)
    metaLoadMu.Unlock()
}()

And defer close(call.done) so waiters wake even on panic (they get nil/zero result, which is fine for the panic-error path).

2. 200ms timeout fallthrough silently disables the convoy guard (pkg/sql/colexec/insert/insert.go:296-309).

On timeout, acquired stays false and the function proceeds into SyncAndFillBlockInfoBat without holding the semaphore. Under sustained pressure (queue 200ms deep, which is exactly the case the convoy guard was added for), the semaphore becomes effectively unbounded — reintroducing the thundering-herd mpool explosion that motivated the original 4-slot cap.

The PR body acknowledges this explicitly ("proceed without semaphore to avoid convoy-induced RSS growth"). The trade-off is real but the right shape is a degraded ceiling, not unbounded:

// Soft fallback: a second, larger semaphore.
var flushSoftSemaphore = make(chan struct{}, flushConcurrency()*2)

Or document the rationale and add a metric so operators can see when the bypass triggers. As-is, this PR can OOM the very workload that made #24309 necessary, just on a different machine shape.

No test covers the timeout branch — only the acquire path is exercised.

Correctness concerns

3. Per-waiter copy can increase peak RSS in the cache-stampede case (pkg/objectio/cache.go:251-256).

ObjectMeta and bloom filters are read-only views (pkg/objectio/meta_entry.go:17). The shared reference was correct. The PR's stated goal is "GC promptness" but change #1 (map shrinks on delete) already gives that — once the key is deleted from the map, the loadCall struct is unreferenced as soon as waiters return.

Under N=100 waiters on a 4 MB bloom filter, the new code allocates ~400 MB of duplicate buffers simultaneously. The leader still passes its own slice into metaCache.Set so its copy is the long-lived one; the waiter copies are short-lived but coincide. This is the opposite of the PR's intent for the exact contention pattern singleflight is for.

Suggest dropping change #2 entirely or limiting it to small payloads.

Hardening

4. flushConcurrency() upper bound 16 is unjustified (insert.go:42-50). On a 64-core box this is 4× the previous limit. If 4 was tuned for mpool budget, 16 may reintroduce mpool pressure. Add a code comment tying the number to mpool budget, or make it derived from mpool.GlobalCap() rather than a magic number.

5. flushConcurrency() reads GOMAXPROCS at package init. Containers using automaxprocs to update GOMAXPROCS post-init won't see the change. Minor; document or recompute lazily.

Verified safe

  • sync.Map → mutex+map singleflight semantics are preserved correctly: lock is held only for map ops, load() runs outside the lock, no nested-lock-order risk introduced. Contention is bounded.
  • No backward-compat issues; all changes are process-local.

Add explicit memory-cache capacity backpressure before DiskCache.Read converts disk bytes into CachedData. Keep DiskCache allocation on the default allocator so the gate is applied at the disk-cache layer instead of relying on S3FS/LocalFS allocator wrappers.

Co-authored-by: Copilot <[email protected]>

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found one more blocking risk in the current diff against main:

In pkg/sql/colexec/lockop/lock_op.go, getRetryWaitDuration() starts a bounded backend retry budget via backendRetryDeadline, but waitToRetryLock() waits for lockRetryHighMemorySlots before it enforces that deadline. Under high memory pressure, once the 16 slots are full, later retrying lock operations can sit on the channel wait longer than defaultMaxWaitTimeOnRetryBackendLock (or indefinitely while the statement context is still alive), so the new "bounded retry" guarantee no longer actually holds.

Concretely, waitToRetryLock() only selects on lockRetryHighMemorySlots and ctx.Done() while acquiring the slot; it checks time.Until(retryState.backendRetryDeadline) only after the slot is acquired. That means queueing behind the slot limiter is currently outside the retry budget.

I think slot acquisition needs to be deadline-aware too: either bound the channel wait by the remaining retry budget, or stop retrying once the deadline expires while waiting for a slot. Otherwise this can still keep backend-failed statements alive far past the intended 10s cap under sustained pressure.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I found one real regression in the current diff.

In pkg/objectio/cache.go, dedupLoad now removes metaLoadCalls[key] before closing call.done in the deferred cleanup. That creates a small but real window where the key is already absent from the map while existing waiters are still blocked on the old done channel. Any goroutine that already missed metaCache and enters dedupLoad in that gap will create a fresh loadCall and start a second load for the same key, which breaks the singleflight contract this helper is supposed to preserve.

The old implementation did not have this gap. Please close call.done while the key is still published (or otherwise make delete+close atomic from the perspective of new callers), then remove the map entry.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Latest update addresses the blockers I called out:

  • waitToRetryLock() now makes high-memory retry-slot acquisition deadline-aware, so the backend retry budget stays bounded even while queued on lockRetryHighMemorySlots.
  • dedupLoad now closes call.done before removing the map entry, so it avoids the singleflight gap and still cleans up correctly on panic/cancel.
  • The new targeted tests cover both fixes.

LGTM.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed from correctness, concurrency, memory-pressure handling, retry semantics, and test coverage. The changes look sound and the added tests cover the risky branches well.

@mergify

mergify Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-20 09:50 UTC · Rule: main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-05-20 10:59 UTC · at edb075b20c6ea397eefe80db0ed898154ce1e558 · squash

This pull request spent 1 hour 8 minutes 44 seconds in the queue, including 1 hour 8 minutes 15 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]
  • github-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 size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: [date 5.11]main tke regression: tpcc 100w 1000 terminal test cn oom

10 participants