Repository navigation
perf(agg): local accumulator with deferred scatter for BatchFill/BatchMerge - #24260
Conversation
ⓘ You've reached your Qodo monthly free-tier limit. Reviews pause until next month — upgrade your plan to continue now, or link your paid account if you already have one. |
177d670 to
ecdbac0
Compare
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add 255-slot L1-resident open-addressing hash table to Decimal64 and Decimal128 specialized SUM/AVG executors. Accumulates into local buffers and defers scatter-back to final state, reducing random memory access. Microbenchmark: SumDecimal64Fast BatchFill 20.3µs → 6.6µs (3.1x). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…lice Replace chunkPtrs []unsafe.Pointer caching with chunkArr[T] helper that calls vector.MustFixedColAsSlice (unsafe confined to the vector package). Add lastX caching to scatter-back loops to avoid repeated slice lookups. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Ensure state vectors always have AggBatchSize backing capacity so that chunkArr's (*[AggBatchSize]T)(slice) conversion is valid. This affects the chunkSize==1 (scalar agg) path and single-chunk deserialization. Add TestLocalAccumulatorOverflow exercising the direct-scatter fallback when a BatchFill has >255 distinct groups (nSlots >= maxSlots path). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…d code Co-Authored-By: Claude Opus 4.6 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Multi-Angle Review
Overall
The two-phase local-accumulator approach is well-designed — 255-slot open-addressing hash table fits comfortably in L1, probe termination is guaranteed by always having at least one empty slot, and the overflow fallback to direct scatter prevents degenerate behavior. Benchmark numbers (3-8x) are credible given the cache-miss elimination.
Three issues should be addressed before merge:
1. Missing lastX caching in sumavg2.go scatter-back loops
count2.go and minmax2.go correctly cache the chunk pointer in scatter-back:
lastX := -1
var vals *[AggBatchSize]int64
for s := 0; s < nSlots; s++ {
x := int(g >> aggBatchSizeShift)
if x != lastX {
lastX = x
vals = chunkArr[int64](exec.state[x].vecs[0])
}
...
}But all 4 scatter-back loops in sumavg2.go (batchFillSum, batchFillAvg, and the decimal variants) call chunkArr unconditionally on every iteration:
for s := 0; s < nSlots; s++ {
sums := chunkArr[T](exec.state[x].vecs[0]) // redundant when x unchanged
...
}Up to ~254 redundant MustFixedColAsSlice calls per scatter-back. Please add lastX caching for consistency and to avoid the unnecessary overhead.
2. localAddSafe detection is fragile
var a A
switch any(a).(type) {
case types.Decimal64, types.Decimal128:
exec.localAddSafe = true
}This checks only the argument type A, not the A→S width relationship. The safety claim is:
- Decimal64→Decimal128: 255 × 10^18 < 10^38 ✓
- Decimal128→Decimal256: 255 × 10^38 < 10^76 ✓
This happens to be correct for current call sites ([Decimal64, Decimal128] and [Decimal128, Decimal256]), but a future instantiation of [Decimal128, Decimal128] would silently skip overflow checking.
Please add a comment at this site documenting the invariant (valid instantiations and required sizeof(S) > sizeof(A)), or restructure the check to verify the relationship directly.
3. Test coverage gaps
The TestLocalAccumulatorOverflow is good for the >255-group fallback path. Please consider adding:
- Const vector test: the
IsConstbranch in the local accumulator is untested — a single-value const vector with multiple groups would exercise it. - Decimal overflow edge case: test
Decimal256→Decimal256(the checked/localAddSafe=falsepath) with values near the precision limit to validate that overflow is correctly caught in the local buffer.
Minor observations (non-blocking)
countStarExec.Mergenow delegates toBatchMerge, allocating a[]uint64per call. Not a hot path, but a slight regression for single-merge. Acceptable.- The
chunkArr/PreExtendinvariant (all state vecs must have capacity ≥ AggBatchSize) is maintained inGroupGrowandUnmarshalFromReader, but has no runtime assertion. A debug-build check would reduce future regression risk. - The local accumulator pattern is copy-pasted across 7 functions. Understood as necessary for Go generics constraints in perf-critical code, but worth a brief comment in each linking to the others so a future editor knows to update all copies.
…ests - Add lastX caching to all 4 scatter-back loops in sumavg2.go - Document localAddSafe invariant (sizeof(S) > sizeof(A)) - Add TestConstVectorAccumulator (exercises IsConst branch) - Add TestDecimal256Overflow (exercises checked localAddSafe=false path) Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
All three items addressed in 4cce7b2:
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review: Approve ✓
High-quality performance PR. The L1-resident local accumulator with deferred scatter is well-suited to the problem — impressive 3-8x speedups across aggregation types. Edge cases (const vectors, nulls, overflow, >255 group fallback) are handled carefully, and the test coverage is solid.
Minor suggestions
1. Latent risk in decimalStateAddUnchecked for Decimal256
decimalStateAddUnchecked silently discards the error from Add256. While localAddSafe=false for Decimal256→Decimal256 means this path is currently unreachable, if someone later changes the localAddSafe logic, overflow errors would be silently swallowed. Consider panicking in the Decimal256 branch or adding a comment documenting why it's dead code.
2. countStarExec.Merge allocates per call
func (exec *countStarExec) Merge(...) error {
return exec.BatchMerge(next, groupIdx2, []uint64{uint64(groupIdx1 + 1)})
}This allocates a []uint64 on each Merge call. The old direct implementation was allocation-free. Consider restoring it if Merge is ever called in a hot loop.
3. Test coverage gaps
- No test for
batchFillAvgwith >255 groups (only SUM and COUNT overflow paths are tested). - No test for
BatchMergewith the newchunkArrpaths. - No test for null-heavy vectors (e.g., 50% nulls mixed with the overflow path).
4. Maintainability note
The local accumulator pattern is copy-pasted ~9 times (deliberate trade-off for performance over DRY — correct call). A brief comment listing all files that implement the pattern would help future maintainers apply changes consistently.
Merge Queue Status
This pull request spent 13 seconds in the queue, including 1 second running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #24097
What this PR does / why we need it:
Replace row-at-a-time scatter writes in aggregation kernels with a two-phase approach: accumulate into a 255-slot L1-resident open-addressing hash table, then scatter-back once per distinct group. This eliminates random cache misses on the chunked state arrays during the hot loop.
Key design decisions:
lastXcaching minimizesvector.MustFixedColAsSlicecallsunsafeinaggexecpackage — all pointer manipulation confined tovector.MustFixedColAsSlicein the vector package*[AggBatchSize]Tarray pointer access for bounds-check eliminationsum_decimal_fast.go) avoid type switches and interface boxingMicrobenchmark results (4096 rows, 64 groups):