Repository navigation
fix: reduce RSS growth from dedupLoad sync.Map retention and flush convoy - #24387
Conversation
…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 reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
aunjgr
left a comment
There was a problem hiding this comment.
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+mapsingleflight 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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
Co-authored-by: Copilot <[email protected]>
LeftHandCold
left a comment
There was a problem hiding this comment.
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 onlockRetryHighMemorySlots.dedupLoadnow closescall.donebefore 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.
Co-authored-by: Copilot <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
Merge Queue Status
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
|
What type of PR is this?
Which issue(s) does this PR fix or relate to?
Fixes #24348
What this PR does / why we need it:
sync.Mapwithsync.Mutex+ plainmapindedupLoadso entries are fully reclaimed after deletion (sync.Map internal hash table never shrinks)[]byteresult instead of sharing a reference, allowing theloadCallstruct to be GC'd promptly without waiting for the slowest consumerflushSemaphorefrom hardcoded capacity 4 to dynamicGOMAXPROCS/2(clamped [4, 16]) to improve flush throughput on multi-core machinesflushSemaphoreacquisition so queued workers don't hold S3 write buffers indefinitely, avoiding convoy-induced RSS growthWhat was the problem
PR #24309 introduced
dedupLoad(cache stampede prevention) andflushSemaphore(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:sync.Mapnever shrinks: Even afterDelete, the internal hash table retains its peak size, causing monotonic memory growth under sustained load[]bytereference: All waiters hold a reference toloadCall.val, preventing GC until the slowest goroutine finishes — under 100 terminals this pins large metadata buffers in memoryCombined with REPLACE INTO large transactions allocating 4+ GiB in mpool, RSS breaks 55 GiB and gets OOM-killed.
What this PR preserves
group/exec2.goandmergeGroup.go— untouchedpk_filter_base.gobuffer overread fix — untouchedTest plan
Ref #24348
🤖 Generated with Claude Code