Skip to content

perf(shuffle): reduce pool contention - #26160

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/shuffle-pool-contention
Jul 25, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/shuffle-pool-contention

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Improvement

What this PR does / why we need it

Reduce contention in the shared shuffle pool without changing shuffle backpressure or buffering limits:

  • account only batches changed by each union instead of rescanning the whole bucket
  • shard batch memory tracking to remove the global accounting mutex
  • shard recycled batches by the local holder bound, with two padded embedded slots per shard
  • keep recycle lookup O(1) independently of the global shuffle bucket count
  • let a cold holder shard warm once without allowing a previously hot bucket to monopolize the cache

The recycle capacity remains exactly 2 * maxHolders. Sharding follows the local concurrency bound rather than bucketNum, which can grow as stage nodes times DOP in multi-CN plans.

This is complementary to the allocator/mmap work in #26143 and is kept separate so both changes can be reviewed, measured, and reverted independently.

Related to #26132.
Follow-up to #26143.

Which issue(s) this PR fixes

None. #26143 already owns the closing reference for #26132.

Testing

  • focused recycle/accounting/error-path stress under -race -count=50
  • go test -race ./pkg/sql/colexec/shuffle
  • go test ./pkg/sql/colexec/shuffle ./pkg/sql/compile ./pkg/vm/pipeline ./pkg/vm
  • go test -race ./pkg/vm/pipeline
  • go build ./pkg/sql/colexec/shuffle
  • go vet ./pkg/sql/colexec/shuffle
  • benchmark matrix covering 16/128/1024 buckets, fixed-worker concurrency, single-CN, multi-CN, drain-all, round-robin, and phased skew

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner July 24, 2026 15:51
@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 →

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Blocking review finding (GitHub does not allow this account to request changes on its own PR):

The per-bucket recycle cache can be permanently starved by an inactive bucket.

batchPoolCount enforces one global readyLimit, but getBatchFromPoolLocked(bucket) can only take from that bucket while putBatchToPoolLocked discards as soon as the global count is full. A legal phased/skewed input therefore behaves as follows:

  1. bucket A returns readyLimit batches and fills the entire global allowance;
  2. A becomes idle and bucket B becomes active;
  3. B cannot take any of A's schema-compatible buffers, so every Union allocates a new batch;
  4. when B returns that batch, the unchanged global count is still at the limit, so B immediately cleans it;
  5. this allocate/discard cycle repeats until the whole ShufflePool generation is destroyed.

The old global pool reused those buffers across buckets. There is no in-generation eviction, quota, or steal path that breaks the new cycle. This is reachable for range/sorted or otherwise phase-skewed shuffle inputs and directly contradicts this performance PR's goal.

Please preserve the global bound while preventing one inactive bucket from monopolizing it—for example with bounded cross-bucket stealing or a fair per-bucket reservation—and add a deterministic phase-skew regression that fills one bucket's cache and then proves another bucket reuses rather than repeatedly allocates/discards. The current cache-bound and concurrent accounting tests set every batch's default ShuffleIDX to 0, so they do not exercise this case.

I otherwise traced the pool lifecycle and found no additional blocker: holder finalization excludes concurrent cleanup, producer shutdown is joined before release, ready batches and recycle storage remain bounded, error-path ownership is preserved, and incremental accounting covers the mutable tail plus appended batches. Fresh local full shuffle -race, 50x focused stress, compile/vm/pipeline tests, build, vet, and diff checks passed at f3d045e633.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Fixed the blocking cross-bucket recycle starvation in 016260bfd2.

The cache still prefers the current bucket, but on a local miss it now performs a bounded scan and uses TryLock to steal a schema-compatible batch from another bucket. This preserves the global readyLimit, restores reuse after skew/phase changes, and cannot create a symmetric bucket-lock wait cycle. Memory tracking maps are also initialized lazily instead of allocating all 64 maps for every ShufflePool.

Added a deterministic production-path regression that fills bucket 0 to the global recycle limit, writes to bucket 1, and proves that bucket 1 receives one of bucket 0s cached batches. The test failed at the previous head f3d045e633 and passes with the fix.

Benchmark on Apple M4 (BenchmarkShufflePoolRecycleCachePhasedBuckets, 200x baseline / 1000x fixed):

  • previous head: 568-1514 ns/op, 323-327 B/op, 3 allocs/op
  • fixed head: 124-154 ns/op, 0 B/op, 0 allocs/op

Fresh validation after the final edit:

  • focused cache/accounting/error-path tests under -race -count=50
  • full ./pkg/sql/colexec/shuffle under -race
  • shuffle + compile + vm/pipeline + vm package tests
  • shuffle build and vet
  • benchmark -count=5
  • full diff/check and Q1-Q3 ownership, wait-for, and boundedness audit

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Blocking re-review finding (this account still cannot submit Request Changes on its own PR): the recycle-cache fix is performance-overfit to the 2-bucket case.

The 2-bucket regression is valid, but getBatchFromPoolLocked now linearly probes up to bucketNum-1 other batchLocks on every local miss. In production this ratio is not bounded: compile sets bucketNum = shuffle stage CN count * DOP, while the local pool is created with maxHolders = local Mcpu and readyLimit = 2 * maxHolders. Thus an 8-CN/DOP-16 shuffle has 128 buckets, 16 holders, and only 32 cached batches; drain-all paths can be even more extreme (maxHolders=1). Sequential/range bucket visitation puts donors behind the target in the scan order and makes a miss O(bucketNum).

I reproduced this with overlay-only benchmarks against the same code paths, without modifying the PR tree. Apple M4, 100000x, 5 runs:

scenario 1caebd5fea (global recycle pool, memory sharding retained) current 016260bfd2
128 buckets / 16 holders, round-robin pool path 14.4-15.2 ns/op 195.8-198.1 ns/op
16 fixed workers, parallel pool path 168.0-179.2 ns/op 220.6-224.0 ns/op
production tryWrite/getLastBatch/return path, 128 buckets 174.4-179.2 ns/op 416.7-439.7 ns/op

At 1024 buckets the current round-robin pool path is 1.78-1.81 us/op versus about 18 ns/op on the original global pool. The current code removes the allocation loop from f3d045e633, but replaces it with an O(bucketNum) CPU loop; it is still substantially worse than the state before the per-bucket recycle commit, including in the nominal fixed-worker contention case.

Recommendation: keep 18fb740cdf and 1caebd5fea, but drop/rework f3d045e633 plus the linear steal. The safest evidence-backed fix is to restore the global bounded recycle pool (the sharded memory accounting already removes the expensive accounting lock contention), retain a generalized cross-bucket reuse regression, and replace the 2-bucket-only benchmark with at least: single-CN bucketNum==holders, multi-CN bucketNum>>holders, drain-all, phased skew, round-robin, and parallel fixed-worker cases. Do not merge the current head based on the existing benchmark.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Resolved the blocking re-review in 64aaafecfd without retaining the 2-bucket overfit.

The final recycle design uses maxHolders fixed shards with two embedded, cache-line-padded slots per shard. It has no global recycle mutex, no bucketNum-sized pool array, no global count that a stale bucket can monopolize, and no cross-bucket scan. A cold shard may allocate once to warm; subsequent phase changes among buckets mapped to that holder shard reuse the same buffer. Total capacity remains exactly 2 * maxHolders.

Apple M4, 1,000,000 iterations, 5 runs, all final cases at 0 B/op and 0 allocs/op:

scenario comparison final 64aaafecfd
recycle round-robin, 16 buckets — 13.83-14.21 ns/op
recycle round-robin, 128 buckets old linear-steal head: 195.8-198.1 ns/op 13.89-15.97 ns/op
recycle round-robin, 1024 buckets old linear-steal head: 1.78-1.81 us/op 13.92-15.41 ns/op
recycle pool, 16 fixed workers global-pool 1caebd5fea: 172.2-175.6 ns/op 5.98-10.28 ns/op
parallel tryWrite/getLast/return, 16 workers global-pool 1caebd5fea: 276.2-284.3 ns/op 171.4-179.4 ns/op
round-robin tryWrite, 128 buckets old linear-steal head: 416.7-439.7 ns/op 185.9-193.5 ns/op
phased tryWrite, 128 buckets — 178.9-180.1 ns/op
drain-all tryWrite, 128 buckets — 182.0-182.8 ns/op

The committed matrix also includes the 1024-bucket full tryWrite path. Its roughly 1.10 us/op is dominated by the existing scan of all selection slots; the isolated recycle path remains about 14-15 ns from 16 through 1024 buckets, so this PR no longer introduces bucket-count-dependent recycle work.

Added deterministic coverage for single-CN, multi-CN, drain-all, every-bucket reuse, cold-shard warmup, concurrent two-workers-per-shard reuse, total worker-bound capacity, memory-accounting shards, and allocation-error ownership.

Final Q1-Q3 audit:

  • Q1: every cached batch is owned by exactly one recycle shard, BatchSet, or consumer; full-shard admission and final cleanup both forget accounting and clean exactly once.
  • Q2: the only nested production order is bucket lock to one recycle-shard lock; memory and recycle locks are never nested, cleanup holds only one shard at a time, and there is no reverse edge.
  • Q3: recycle storage is 2 * maxHolders; ready queues retain their existing limits; tracking entries are removed on every clean/discard path.

Fresh final validation passed: focused -race -count=50, full shuffle -race, shuffle/compile/vm/pipeline/vm tests, pipeline -race, build, vet, diff check, and the full benchmark matrix. No remaining blocker found.

@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Jul 24, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

做了一轮 correctness / robustness / unhappy-path review,这版我没看到新的问题。重点看了 4 件事:\n\n1. tryWrite -> BatchSet.Union -> syncBatchSetFrom(oldLength-1) 的增量记账假设是否成立:Union 只会修改旧 tail 和新 append 的 batch,这条链条是闭合的。\n2. recycle cache 从全局 slice 改成按 maxHolders 分片后,ownership / cleanup 是否仍然 exactly-once:put/get/cleanBatchPool/cleanupLocked 这几条路径都闭合,没有双清理或遗漏释放。\n3. fixed-bucket / drain-all 的等待与终止条件:producer、consumer、ending waiter、ready credit 的释放链都还能收敛,没有看到新 hang path。\n4. memory shard 的 current/peak 统计:分片 map + 原子累计/峰值更新没有打破边界和 cleanup 对称性。\n\nGitHub 不允许对自己的 PR 直接 approve,所以这里留评论代替:目前看 LGTM。

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

重新按当前 head 做了一轮 correctness / robustness / unhappy-path 复核,结论没变:当前这版我没有看到新的高置信 blocker。

重点又过了一遍这几条链:

  1. recycle shard 的 ownership / cleanup(put/get/cleanBatchPool/cleanupLocked)
  2. fixed-bucket 与 drain-all 的 ready credit / final-drain / wakeup 路径
  3. syncBatchSetFrom(oldLength-1) 的增量记账假设
  4. memory shard 的 current/peak 统计一致性

包级 GOFLAGS=-mod=mod go test -race ./pkg/sql/colexec/shuffle 当前 head 也还是过的。

因为这是你的 PR,GitHub 不允许我直接 self-approve,所以这里继续用 comment 代替:当前看还是 LGTM。

@XuPeng-SH
XuPeng-SH requested a review from gouhongshen July 25, 2026 01:20
@XuPeng-SH
XuPeng-SH merged commit 36f8b76 into matrixorigin:main Jul 25, 2026
41 of 43 checks passed
@XuPeng-SH
XuPeng-SH deleted the perf/shuffle-pool-contention branch July 25, 2026 01:24
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [x] Improvement

## What this PR does / why we need it

Reduce contention in the shared shuffle pool without changing shuffle
backpressure or buffering limits:

- account only batches changed by each union instead of rescanning the
whole bucket
- shard batch memory tracking to remove the global accounting mutex
- shard recycled batches by the local holder bound, with two padded
embedded slots per shard
- keep recycle lookup O(1) independently of the global shuffle bucket
count
- let a cold holder shard warm once without allowing a previously hot
bucket to monopolize the cache

The recycle capacity remains exactly `2 * maxHolders`. Sharding follows
the local concurrency bound rather than `bucketNum`, which can grow as
stage nodes times DOP in multi-CN plans.

This is complementary to the allocator/mmap work in matrixorigin#26143 and is kept
separate so both changes can be reviewed, measured, and reverted
independently.

Related to matrixorigin#26132.
Follow-up to matrixorigin#26143.

## Which issue(s) this PR fixes

None. matrixorigin#26143 already owns the closing reference for matrixorigin#26132.

## Testing

- focused recycle/accounting/error-path stress under `-race -count=50`
- `go test -race ./pkg/sql/colexec/shuffle`
- `go test ./pkg/sql/colexec/shuffle ./pkg/sql/compile ./pkg/vm/pipeline
./pkg/vm`
- `go test -race ./pkg/vm/pipeline`
- `go build ./pkg/sql/colexec/shuffle`
- `go vet ./pkg/sql/colexec/shuffle`
- benchmark matrix covering 16/128/1024 buckets, fixed-worker
concurrency, single-CN, multi-CN, drain-all, round-robin, and phased
skew
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [x] Improvement

## What this PR does / why we need it

Reduce contention in the shared shuffle pool without changing shuffle
backpressure or buffering limits:

- account only batches changed by each union instead of rescanning the
whole bucket
- shard batch memory tracking to remove the global accounting mutex
- shard recycled batches by the local holder bound, with two padded
embedded slots per shard
- keep recycle lookup O(1) independently of the global shuffle bucket
count
- let a cold holder shard warm once without allowing a previously hot
bucket to monopolize the cache

The recycle capacity remains exactly `2 * maxHolders`. Sharding follows
the local concurrency bound rather than `bucketNum`, which can grow as
stage nodes times DOP in multi-CN plans.

This is complementary to the allocator/mmap work in matrixorigin#26143 and is kept
separate so both changes can be reviewed, measured, and reverted
independently.

Related to matrixorigin#26132.
Follow-up to matrixorigin#26143.

## Which issue(s) this PR fixes

None. matrixorigin#26143 already owns the closing reference for matrixorigin#26132.

## Testing

- focused recycle/accounting/error-path stress under `-race -count=50`
- `go test -race ./pkg/sql/colexec/shuffle`
- `go test ./pkg/sql/colexec/shuffle ./pkg/sql/compile ./pkg/vm/pipeline
./pkg/vm`
- `go test -race ./pkg/vm/pipeline`
- `go build ./pkg/sql/colexec/shuffle`
- `go vet ./pkg/sql/colexec/shuffle`
- benchmark matrix covering 16/128/1024 buckets, fixed-worker
concurrency, single-CN, multi-CN, drain-all, round-robin, and phased
skew
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [x] Improvement

## What this PR does / why we need it

Reduce contention in the shared shuffle pool without changing shuffle
backpressure or buffering limits:

- account only batches changed by each union instead of rescanning the
whole bucket
- shard batch memory tracking to remove the global accounting mutex
- shard recycled batches by the local holder bound, with two padded
embedded slots per shard
- keep recycle lookup O(1) independently of the global shuffle bucket
count
- let a cold holder shard warm once without allowing a previously hot
bucket to monopolize the cache

The recycle capacity remains exactly `2 * maxHolders`. Sharding follows
the local concurrency bound rather than `bucketNum`, which can grow as
stage nodes times DOP in multi-CN plans.

This is complementary to the allocator/mmap work in matrixorigin#26143 and is kept
separate so both changes can be reviewed, measured, and reverted
independently.

Related to matrixorigin#26132.
Follow-up to matrixorigin#26143.

## Which issue(s) this PR fixes

None. matrixorigin#26143 already owns the closing reference for matrixorigin#26132.

## Testing

- focused recycle/accounting/error-path stress under `-race -count=50`
- `go test -race ./pkg/sql/colexec/shuffle`
- `go test ./pkg/sql/colexec/shuffle ./pkg/sql/compile ./pkg/vm/pipeline
./pkg/vm`
- `go test -race ./pkg/vm/pipeline`
- `go build ./pkg/sql/colexec/shuffle`
- `go vet ./pkg/sql/colexec/shuffle`
- benchmark matrix covering 16/128/1024 buckets, fixed-worker
concurrency, single-CN, multi-CN, drain-all, round-robin, and phased
skew

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/enhancement size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants