Skip to content

perf(agg): local accumulator with deferred scatter for BatchFill/BatchMerge - #24260

Merged
mergify[bot] merged 10 commits into
matrixorigin:mainfrom
aunjgr:opt/agg-local-accumulator
May 3, 2026
Merged

mergify[bot] merged 10 commits into
matrixorigin:mainfrom
aunjgr:opt/agg-local-accumulator

Conversation

@aunjgr

@aunjgr aunjgr commented Apr 30, 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) 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:

  • Local accumulator uses XOR-folded hash with linear probing (255 slots fits in L1)
  • Deferred scatter-back with lastX caching minimizes vector.MustFixedColAsSlice calls
  • Zero unsafe in aggexec package — all pointer manipulation confined to vector.MustFixedColAsSlice in the vector package
  • *[AggBatchSize]T array pointer access for bounds-check elimination
  • Specialized non-generic Decimal64/128 executors (sum_decimal_fast.go) avoid type switches and interface boxing
  • Overflow checking conditional on type width (Decimal64→128 provably safe, Decimal128→128 checked when precision > 28)

Microbenchmark results (4096 rows, 64 groups):

  • SUM(int64): 45.8µs → 5.4µs (8.4x)
  • SUM(float64): 45.4µs → 5.3µs (8.6x)
  • SUM(decimal64): 19.3µs → 6.2µs (3.1x, specialized fast path)
  • AVG(int64): 37.5µs → 6.7µs (5.6x)
  • AVG(decimal64): 52.0µs → 19.6µs (2.7x)
  • COUNT(column): 11.3µs → 4.1µs (2.8x)
  • COUNT/Merge: 750ns → 110ns (6.8x)
  • MIN/MAX(int64): comparable to COUNT path

@aunjgr
aunjgr requested a review from ouyuanning as a code owner April 30, 2026 05:21
@qodo-code-review

Copy link
Copy Markdown
ⓘ 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.

This comment was marked as resolved.

aunjgr and others added 3 commits May 1, 2026 12:18
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]>

This comment was marked as resolved.

aunjgr and others added 2 commits May 2, 2026 17:55
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]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Comment thread pkg/container/vector/tools.go Resolved

@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.

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 IsConst branch 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=false path) with values near the precision limit to validate that overflow is correctly caught in the local buffer.

Minor observations (non-blocking)

  • countStarExec.Merge now delegates to BatchMerge, allocating a []uint64 per call. Not a hot path, but a slight regression for single-merge. Acceptable.
  • The chunkArr/PreExtend invariant (all state vecs must have capacity ≥ AggBatchSize) is maintained in GroupGrow and UnmarshalFromReader, 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]>
@aunjgr

aunjgr commented May 3, 2026

Copy link
Copy Markdown
Contributor Author

All three items addressed in 4cce7b2:

  1. lastX caching in sumavg2.go — Added to all 4 scatter-back loops (batchFillSum, batchFillAvg, and both decimal variants). Now consistent with count2/minmax2.

  2. localAddSafe documentation — Added comment documenting valid instantiations and the sizeof(S) > sizeof(A) invariant, with explicit warning about hypothetical [Decimal128, Decimal128].

  3. Test coverage — Added TestConstVectorAccumulator (const vector with SumInt64, MinInt64, SumDecimal64Fast) and TestDecimal256Overflow (verifies overflow is caught in the local buffer for the localAddSafe=false path).

@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.

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 batchFillAvg with >255 groups (only SUM and COUNT overflow paths are tested).
  • No test for BatchMerge with the new chunkArr paths.
  • 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.

@mergify

mergify Bot commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-03 16:47 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-05-03 16:47 UTC · at 4cce7b2dfbd78f35271b1500186fb6d95e41938f · squash

This pull request spent 13 seconds in the queue, including 1 second 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]
  • branch-protection-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/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants