Repository navigation
perf(window): optimize bounded RANGE aggregates - #27940
Conversation
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? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Request changes for two concrete issues found by exact-head review and counterexample testing:
-
[P1 correctness] Small unsigned RANGE keys do not satisfy the new sliding-path invariant.
boundedSlidingRangeFramenewly admitsT_uint8,T_uint16, andT_uint32, whilesearchLeft/searchRightstill compute their additive bounds with unchecked narrow arithmetic (col[rowIdx] + c). A focused exact-head reproducer with ascendinguint8order keys[252,253,254,255]andRANGE BETWEEN 2 PRECEDING AND 2 FOLLOWINGfails at key 254 with:internal error: invalid sliding window intervalThe expected SUM frames are
[759,1014,1014,762]. Exact base executes instead of returning this internal error, although its final two values are already wrong because the old evaluator shares the same wraparound bug. This PR therefore exposes a pre-existing unsafe boundary computation through a fast path that requires monotonic intervals.Please make additive bounds for uint8/16/32 overflow-safe with the same out-of-domain semantics used by
uint64RangeBound(preferred, because it fixes both evaluators), or exclude these types from the fast path until that is done. Add maximum-boundary ASC and DESC tests. -
[P2 performance] Cancellation sampling restarts at zero for every edge update.
Both new edge loops call
checkCanceled(proc, row-edgeStart). In the normal sliding case each update removes/adds one row, so the argument is always zero andvm.CancelCheckruns once or twice per output row instead of once per 1,024 work items. The outer row loop has already performed the prompt check.On the exact head, three-run M4 medians for the existing 80k-row
BenchmarkWindowBoundedRowsSumwere about 4.06 ms for widths 31/128/512/1024. Preserving the sampling interval across edge updates, with no aggregate change, reduced them to about 3.54-3.56 ms (roughly 12-13%). Please use a monotonic/shared work counter, or avoid restarting the inner sampler at zero while retaining periodic checks for large peer updates.
Validation on exact head df23c3f76899b8cff21ffd42cfc9a6bb2cab431e:
- full focused
aggexecandwindowpackages pass; - the uint8 counterexample fails deterministically on head;
- exact base/head A/B confirms the new internal-error regression;
- committed diff is clean and all substantive CI checks are green.
aptend
left a comment
There was a problem hiding this comment.
Deep-reviewed the full diff and review history at exact head df23c3f. The committed focused window/aggregate tests pass, but an unsigned-boundary counterexample deterministically fails with the new sliding-window invariant. The hot-path cancellation sampling also polls on every ordinary one-row edge move. Both issues need to be addressed before this optimization is safe to merge.
| switch orderVecs[0].Vec[0].GetType().Oid { | ||
| case types.T_bit, | ||
| types.T_int8, types.T_int16, types.T_int32, types.T_int64, | ||
| types.T_uint8, types.T_uint16, types.T_uint32, types.T_uint64, |
There was a problem hiding this comment.
T_uint8/T_uint16/T_uint32 are unsafe to admit here because their RANGE search branches still calculate the additive boundary with unchecked narrow arithmetic. For example, ascending uint8 keys [252,253,254,255] with SUM(key) OVER (ORDER BY key RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING) should produce [759,1014,1014,762]. At key 254, 254+2 wraps to 0, right moves behind runningRight, and this exact head returns internal error: invalid sliding window interval. Please route all unsigned widths through overflow-safe out-of-domain bound logic (like uint64RangeBound), with ASC/DESC max-boundary tests, or exclude these three types from the fast path.
There was a problem hiding this comment.
Current head uses unsignedRangeBound for uint8, uint16, and uint32 in both searchLeftWithLocation and searchRightWithLocation. Underflow and overflow now use the existing out-of-domain boundary semantics instead of wrapping. TestBoundedSlidingRangeSumUint8MaximumBoundary covers the stated ascending and descending maximum-boundary frames, and TestBuildRangeIntervalUnsignedBoundaries covers uint8/16/32/64 in both directions. The focused controlled-CGo run and the full window package both pass on e49a544.
| } | ||
|
|
||
| for row := ctr.runningLeft; row < left; row++ { | ||
| if err = checkCanceled(proc, row-ctr.runningLeft); err != nil { |
There was a problem hiding this comment.
Both edge samplers restart at zero on every peer transition. With distinct consecutive keys and RANGE 2 PRECEDING/2 FOLLOWING, each remove/add loop normally executes one iteration, so row-runningLeft and row-runningRight are always 0 and vm.CancelCheck runs about twice per output row instead of once per 1024 edge operations. This adds O(N) context polls to the hot path this PR is optimizing. Please carry a monotonic/shared edge-work counter across updates (while still polling inside large peer jumps), or rely on the outer check for single-edge moves.
There was a problem hiding this comment.
Current head keeps edgeWork outside the output-row loop and increments it for every removal and addition, so the cancellation sampler no longer restarts for ordinary one-row edge transitions while remaining active during large peer changes. The full window package passes with the controlled CGo test command on e49a544.
df23c3f to
e49a544
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review completed on exact head e49a544dcf9d95610cba2227e7a85fbe92a27b35 against base fb2868cd974d11695dc6b8c72a7d46d10ec36232. Decision: APPROVE.
I reviewed every changed hunk and traced the window evaluator, aggregate inverse state, output-chunk reuse, reset/free paths, public BVT, and prior review history.
The two previously requested blockers are closed:
- Narrow unsigned RANGE arithmetic now uses width-correct out-of-domain semantics for
uint8/uint16/uint32in both left and right searches. The maximum-boundary ASC/DESC regression proves the former internal-error path and the helper tests cover both domain ends for all unsigned widths. - Edge cancellation uses one monotonic work counter across add/remove loops, so ordinary one-row edge movement no longer invokes
vm.CancelCheckfor every row while large peer changes remain sampled and interruptible.
Correctness/counterexample review covered ASC/DESC, duplicate peers, NULL order and aggregate values, partition transitions, peer groups split across output chunks, zero/non-zero finite bounds, numeric domain boundaries, AVG count/null restoration, overflow/error cleanup, and unsafe shapes. Float, DISTINCT, multi-key RANGE, and TIMESTAMP/DST-fold cases remain on the ordinary evaluator. A temporary deterministic differential test ran 80 mixed fast-path cases against the ordinary evaluator and matched every value and NULL bit (TestReviewSlidingRangeDifferential, PASS); the temporary test was then removed.
Performance and unhappy paths also close: the algorithm is linear in edge updates plus one boundary search per peer, preserves O(1) retained aggregate state, does no new I/O/logging/goroutine/lock work, and frees the running state on partition replacement, error/cancel, Reset/Free, and final output. Exact-head substantive CI, UT/coverage/SCA, and BVT checks are green. This is a focused execution optimization and does not introduce a new API, wire/catalog format, or design surface.
No blocking correctness, performance, liveness, resource, compatibility, or test-quality finding remains.
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed exact head e49a544dcf9d95610cba2227e7a85fbe92a27b35 against merge-base fb2868cd974d11695dc6b8c72a7d46d10ec36232. I read every changed hunk across the window evaluator, inverse SUM/AVG state, RANGE boundary arithmetic, tests, benchmark, and BVT result.
The optimization remains fail-closed to finite single-key RANGE frames with safe numeric/date/time key types; floats, DISTINCT aggregates, timestamps, multi-key RANGE, and unsupported shapes retain the ordinary evaluator. Peer-boundary reuse is preserved across output chunks and reset at partition changes. The running aggregate has one owner and is released on completion, error/cancellation, reset, and free.
The previous blockers are closed. Narrow unsigned arithmetic now has width-correct overflow/underflow semantics in both left and right boundary searches, with ASC/DESC maximum-boundary coverage. Cancellation sampling now uses monotonic edge work within each output call, avoiding a poll per ordinary one-row move while keeping large peer updates interruptible. AVG inverse updates preserve sum, non-NULL count, and empty-frame NULL behavior for the admitted integer and Decimal64 states.
All 26 exact-head checks are terminal green. I found no blocking correctness, liveness, resource, compatibility, performance, or test-quality issue.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review of exact head bf2d8df: no blocking findings. Rechecked the rebased full patch and the post-approval delta from correctness, boundary arithmetic, cancellation, state lifecycle, and hot-path cost. The uint8/16/32/64 RANGE searches now map underflow and overflow to the correct insertion boundary for ASC and DESC without wrapping; focused tests cover both directions, zero offsets, and domain endpoints. Sliding SUM/AVG keeps count and NULL state consistent, rejects unsupported DISTINCT/float/narrow-decimal cases, reuses RANGE peer boundaries, and samples cancellation by cumulative edge work instead of restarting for each edge. Current exact-head CI is green. Local package execution was not used as evidence because this isolated macOS worktree lacks the matching cgo/libmo.dylib prerequisite.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-reviewed the actual current head 3207d2607e47222f6bfa419bdae888266f541aef after the late merge from main. No blocker.
The merge has no combined/conflict-resolution hunk in the window/aggregate implementation. I compared the complete effective patch before and after the merge: the stable patch-id is identical (b412ab19c1ca21f0813e743b0c991201b7f8f5b2). Therefore the prior correctness, boundary, cancellation, state-lifecycle, and hot-path conclusions still hold on the real current head: unsigned RANGE endpoints do not wrap, sliding SUM/AVG preserves empty/NULL/count state, unsupported shapes remain on the legacy evaluator, and edge cancellation remains cumulatively sampled.
The imported main changes include the separate hash-partition window work, but they do not alter this patch's bounded RANGE selection or aggregate inverse state. Q1 — one sliding aggregate state is owned by the current partition and freed on replacement/error/reset/free; Q2 — no new goroutine/channel/lock wait is introduced and cancellation remains bounded; Q3 — time is linear in peer-boundary searches plus edge movement and retained state is O(1). CI is running on the merged head; per request I did not wait for it.
## What type of PR is this? - [ ] API-change - [ ] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Fixes matrixorigin#13008 ## What this PR does / why we need it: Finite `RANGE` window frames were evaluated by rebuilding the complete aggregate frame for every output row. The workload in matrixorigin#13008 has only 10,960 distinct order keys across 20,971,520 rows, so the same frame was refilled thousands of times for each peer group. This PR: - evaluates eligible finite, single-key `RANGE` frames with a retained sliding aggregate; - searches and updates frame boundaries once per peer group, while still emitting one result per row; - adds exact add/remove support for `AVG` over safe integer, unsigned, bit, and Decimal64 states; - avoids the generic 256-slot `BatchFill` setup for single-group sliding updates; - keeps float, `DISTINCT`, timestamp/DST-fold, and other unsafe shapes on the existing evaluator; - removes the `@bvt:issue#13008` skip and restores the expected public SQL result; - adds correctness, partition/peer/output-chunk, NULL, cancellation/cleanup, and benchmark coverage. ### Performance Environment: - Apple M4, 10 logical CPUs (`GOMAXPROCS=10`) - macOS 15.5 (24F74), arm64 - Go `go1.26.4 darwin/arm64` - base `main@33af6ae` - local single-node deployment using `etc/launch/launch.toml` - exact issue fixture: 20,971,520 rows - end-to-end timing uses `/usr/bin/time -p` real time and includes SQL client connection overhead Issue query: ```sql select avg(d) over ( order by d range between 2 preceding and 2 following ) from td limit 10; ``` End-to-end MatrixOne result: | Version / scenario | Real time | | --- | ---: | | Original issue report (`0015299`) | about 5 hours | | Optimized, original `LIMIT 10` query | 1.13-1.68 s, median 1.54 s | | Optimized, consume all 20,971,520 window results | 2.38-2.58 s | The historical issue result and current `main` are not directly comparable, so no speedup ratio is derived from the 5-hour report. A controlled same-version benchmark was also added: 80,000 sorted `int32` rows, identical `RANGE 2 PRECEDING / 2 FOLLOWING` frame, timer excluding setup and sort, three runs per case with the median reported. | Peer rows per order key | Old row-by-row evaluator | Optimized | Speedup | | ---: | ---: | ---: | ---: | | 1 | 70.73 ms/op | 14.21 ms/op | 5.0x | | 16 | 980.71 ms/op | 4.79 ms/op | 205x | | 64 | 3.886 s/op | 4.30 ms/op | 903x | For the exact issue fixture, the old evaluator is estimated to perform about 289.1 billion aggregate `Fill` operations. The sliding evaluator performs about 41.9 million edge add/remove operations, a theoretical aggregate-work reduction of about 6,893x. ### Validation - `./pkg/sql/colexec/aggexec` full unit tests: passed - `./pkg/sql/colexec/window` full unit tests: passed - focused RANGE correctness and cancellation tests: passed - `go vet` for both owning packages: passed - `make build`: passed - `window.sql` BVT on the optimized binary: 1106/1106 passed, 0 failed, 0 ignored (25.077 s) --------- Co-authored-by: XuPeng-SH <[email protected]>
## What type of PR is this? - [ ] API-change - [ ] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Fixes matrixorigin#13008 ## What this PR does / why we need it: Finite `RANGE` window frames were evaluated by rebuilding the complete aggregate frame for every output row. The workload in matrixorigin#13008 has only 10,960 distinct order keys across 20,971,520 rows, so the same frame was refilled thousands of times for each peer group. This PR: - evaluates eligible finite, single-key `RANGE` frames with a retained sliding aggregate; - searches and updates frame boundaries once per peer group, while still emitting one result per row; - adds exact add/remove support for `AVG` over safe integer, unsigned, bit, and Decimal64 states; - avoids the generic 256-slot `BatchFill` setup for single-group sliding updates; - keeps float, `DISTINCT`, timestamp/DST-fold, and other unsafe shapes on the existing evaluator; - removes the `@bvt:issue#13008` skip and restores the expected public SQL result; - adds correctness, partition/peer/output-chunk, NULL, cancellation/cleanup, and benchmark coverage. ### Performance Environment: - Apple M4, 10 logical CPUs (`GOMAXPROCS=10`) - macOS 15.5 (24F74), arm64 - Go `go1.26.4 darwin/arm64` - base `main@33af6ae` - local single-node deployment using `etc/launch/launch.toml` - exact issue fixture: 20,971,520 rows - end-to-end timing uses `/usr/bin/time -p` real time and includes SQL client connection overhead Issue query: ```sql select avg(d) over ( order by d range between 2 preceding and 2 following ) from td limit 10; ``` End-to-end MatrixOne result: | Version / scenario | Real time | | --- | ---: | | Original issue report (`0015299`) | about 5 hours | | Optimized, original `LIMIT 10` query | 1.13-1.68 s, median 1.54 s | | Optimized, consume all 20,971,520 window results | 2.38-2.58 s | The historical issue result and current `main` are not directly comparable, so no speedup ratio is derived from the 5-hour report. A controlled same-version benchmark was also added: 80,000 sorted `int32` rows, identical `RANGE 2 PRECEDING / 2 FOLLOWING` frame, timer excluding setup and sort, three runs per case with the median reported. | Peer rows per order key | Old row-by-row evaluator | Optimized | Speedup | | ---: | ---: | ---: | ---: | | 1 | 70.73 ms/op | 14.21 ms/op | 5.0x | | 16 | 980.71 ms/op | 4.79 ms/op | 205x | | 64 | 3.886 s/op | 4.30 ms/op | 903x | For the exact issue fixture, the old evaluator is estimated to perform about 289.1 billion aggregate `Fill` operations. The sliding evaluator performs about 41.9 million edge add/remove operations, a theoretical aggregate-work reduction of about 6,893x. ### Validation - `./pkg/sql/colexec/aggexec` full unit tests: passed - `./pkg/sql/colexec/window` full unit tests: passed - focused RANGE correctness and cancellation tests: passed - `go vet` for both owning packages: passed - `make build`: passed - `window.sql` BVT on the optimized binary: 1106/1106 passed, 0 failed, 0 ignored (25.077 s) --------- Co-authored-by: XuPeng-SH <[email protected]>
## What type of PR is this? - [ ] API-change - [ ] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Fixes matrixorigin#13008 ## What this PR does / why we need it: Finite `RANGE` window frames were evaluated by rebuilding the complete aggregate frame for every output row. The workload in matrixorigin#13008 has only 10,960 distinct order keys across 20,971,520 rows, so the same frame was refilled thousands of times for each peer group. This PR: - evaluates eligible finite, single-key `RANGE` frames with a retained sliding aggregate; - searches and updates frame boundaries once per peer group, while still emitting one result per row; - adds exact add/remove support for `AVG` over safe integer, unsigned, bit, and Decimal64 states; - avoids the generic 256-slot `BatchFill` setup for single-group sliding updates; - keeps float, `DISTINCT`, timestamp/DST-fold, and other unsafe shapes on the existing evaluator; - removes the `@bvt:issue#13008` skip and restores the expected public SQL result; - adds correctness, partition/peer/output-chunk, NULL, cancellation/cleanup, and benchmark coverage. ### Performance Environment: - Apple M4, 10 logical CPUs (`GOMAXPROCS=10`) - macOS 15.5 (24F74), arm64 - Go `go1.26.4 darwin/arm64` - base `main@33af6ae` - local single-node deployment using `etc/launch/launch.toml` - exact issue fixture: 20,971,520 rows - end-to-end timing uses `/usr/bin/time -p` real time and includes SQL client connection overhead Issue query: ```sql select avg(d) over ( order by d range between 2 preceding and 2 following ) from td limit 10; ``` End-to-end MatrixOne result: | Version / scenario | Real time | | --- | ---: | | Original issue report (`0015299`) | about 5 hours | | Optimized, original `LIMIT 10` query | 1.13-1.68 s, median 1.54 s | | Optimized, consume all 20,971,520 window results | 2.38-2.58 s | The historical issue result and current `main` are not directly comparable, so no speedup ratio is derived from the 5-hour report. A controlled same-version benchmark was also added: 80,000 sorted `int32` rows, identical `RANGE 2 PRECEDING / 2 FOLLOWING` frame, timer excluding setup and sort, three runs per case with the median reported. | Peer rows per order key | Old row-by-row evaluator | Optimized | Speedup | | ---: | ---: | ---: | ---: | | 1 | 70.73 ms/op | 14.21 ms/op | 5.0x | | 16 | 980.71 ms/op | 4.79 ms/op | 205x | | 64 | 3.886 s/op | 4.30 ms/op | 903x | For the exact issue fixture, the old evaluator is estimated to perform about 289.1 billion aggregate `Fill` operations. The sliding evaluator performs about 41.9 million edge add/remove operations, a theoretical aggregate-work reduction of about 6,893x. ### Validation - `./pkg/sql/colexec/aggexec` full unit tests: passed - `./pkg/sql/colexec/window` full unit tests: passed - focused RANGE correctness and cancellation tests: passed - `go vet` for both owning packages: passed - `make build`: passed - `window.sql` BVT on the optimized binary: 1106/1106 passed, 0 failed, 0 ignored (25.077 s) --------- Co-authored-by: XuPeng-SH <[email protected]>
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #13008
What this PR does / why we need it:
Finite
RANGEwindow frames were evaluated by rebuilding the complete aggregate frame for every output row. The workload in #13008 has only 10,960 distinct order keys across 20,971,520 rows, so the same frame was refilled thousands of times for each peer group.This PR:
RANGEframes with a retained sliding aggregate;AVGover safe integer, unsigned, bit, and Decimal64 states;BatchFillsetup for single-group sliding updates;DISTINCT, timestamp/DST-fold, and other unsafe shapes on the existing evaluator;@bvt:issue#13008skip and restores the expected public SQL result;Performance
Environment:
GOMAXPROCS=10)go1.26.4 darwin/arm64main@33af6ae3c0c23e4f277137460577ea64678f7ecfetc/launch/launch.toml/usr/bin/time -preal time and includes SQL client connection overheadIssue query:
End-to-end MatrixOne result:
0015299)LIMIT 10queryThe historical issue result and current
mainare not directly comparable, so no speedup ratio is derived from the 5-hour report. A controlled same-version benchmark was also added: 80,000 sortedint32rows, identicalRANGE 2 PRECEDING / 2 FOLLOWINGframe, timer excluding setup and sort, three runs per case with the median reported.For the exact issue fixture, the old evaluator is estimated to perform about 289.1 billion aggregate
Filloperations. The sliding evaluator performs about 41.9 million edge add/remove operations, a theoretical aggregate-work reduction of about 6,893x.Validation
./pkg/sql/colexec/aggexecfull unit tests: passed./pkg/sql/colexec/windowfull unit tests: passedgo vetfor both owning packages: passedmake build: passedwindow.sqlBVT on the optimized binary: 1106/1106 passed, 0 failed, 0 ignored (25.077 s)