Skip to content

fix(colexec): prevent H0 aggregate spill panic on 4.2-dev - #32352

Merged
XuPeng-SH merged 3 commits into
matrixorigin:4.2-devfrom
gouhongshen:agent/issue-32233-4.2-dev-432acb43
Nov 9, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:4.2-devfrom
gouhongshen:agent/issue-32233-4.2-dev-432acb43

Conversation

@gouhongshen

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:

Related to #32233

What this PR does / why we need it:

On 4.2-dev, running the first scalar aggregate on a freshly created table
while the session holds a low debug agg_spill_mem threshold panics with a
nil pointer dereference and surfaces internal error 20101:

CREATE TABLE fresh_count (id INT);
INSERT INTO fresh_count VALUES (1);
SET @@agg_spill_mem = 256;
SELECT COUNT(*) FROM fresh_count;  -- panic in group.(*container).needSpill

Root cause

pkg/sql/colexec/group/helper.go needSpill() evaluates the debug
group-count mode (spillMem < 10000) by dereferencing ctr.hr.Hash.GroupCount()
without checking the container mode. An H0 container (no GROUP BY) never
builds the grouping hash table, so ctr.hr.Hash is nil and the call panics.
MergeGroup reaches the same call on its H0 merge path, which is why plain
SELECT COUNT(*) on a fresh table triggers it. Values of 10000 and above are
a byte threshold and were never affected.

This is the 4.2-dev counterpart of main PR #26736 (issue #26453):
generic group-spill partitioning requires the grouping hash table, H0 holds
exactly one aggregate group, and aggregates that bring their own H0 spill
behavior (such as ordered GROUP_CONCAT) keep spilling through their own
executors.

Exact change

  • pkg/sql/colexec/group/helper.go: needSpill() returns false for H0
    before either threshold branch; the analyzer memory accounting and the
    grouped (H8/HStr) threshold semantics are unchanged.
  • pkg/sql/colexec/group/group_test.go: ports of the fix: prevent H0 aggregate spill panic #26736 unit regressions:
    • TestH0NeverRequestsGenericGroupSpill: H0 requests no generic spill at
      the 256 group-count threshold and at a 10 KiB byte threshold with memory
      retained in the pool; SetMemUsed accounting is still published.
    • TestH0OrderedGroupConcatSpillsIndependently: an H0 ordered GROUP_CONCAT
      still spills (SpillRows > 0) with zero generic GroupSpillWriteCalls.
    • TestMergeGroupH0SkipsGenericSpillAndReuses: the real Group → MergeGroup
      H0 hand-off over multiple partial batches returns the correct scalar
      count, performs no generic spill, stays H0 with an empty hash, and resets
      cleanly between generations.
  • test/distributed/cases/qexec/group_h0_spill.sql + .result: BVT that
    creates a fresh one-row table, runs scalar COUNT at agg_spill_mem = 256
    and then at the normal 536870912 byte threshold on one connection, and
    resets the variable afterwards.

Issue-to-test proof (red/green)

  • With the 4.2-dev base helper.go restored, the three focused UTs panic with
    the reported runtime error: invalid memory address or nil pointer dereference at needSpill - the exact stack from issue [Bug]: 4.2-dev low aggregate spill threshold panics on fresh scalar COUNT #32233.
  • With the fix, the same tests pass; the grouped spill behavior exercised by
    the package's existing tests is unchanged and the full package passes under
    -race.
  • End-to-end SQL on a locally built mo-service from this branch
    (1 LOG / 1 TN / 1 CN on isolated ports): the issue's exact sequence returns
    1 for 3/3 fresh tables at agg_spill_mem = 256, 1 at 536870912, the
    grouped control returns 1 | 1, and an empty-input scalar COUNT returns
    0; no internal error or panic appears in the service log.

Test commands

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=600s \
  -run 'TestH0NeverRequestsGenericGroupSpill|TestH0OrderedGroupConcatSpillsIndependently|TestMergeGroupH0SkipsGenericSpillAndReuses' \
  ./pkg/sql/colexec/group            # red on base, green with fix
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=600s \
  -run 'TestH0NeverRequestsGenericGroupSpill|TestH0OrderedGroupConcatSpillsIndependently|TestMergeGroupH0SkipsGenericSpillAndReuses' \
  ./pkg/sql/colexec/group            # pass
.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=1200s \
  ./pkg/sql/colexec/group            # full package passes
.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=600s \
  -run TestRefreshGroupConcatMaxLenForPreparedCompileReuse \
  ./pkg/sql/compile                  # dependent package passes
GOWORK=off go build ./pkg/sql/colexec/group ./pkg/sql/compile   # clean
GOWORK=off go vet  ./pkg/sql/colexec/group ./pkg/sql/compile   # clean

The new BVT pair runs in the CI mo-tester matrix.

Residual risk

Low. agg_spill_mem values below 10000 are a debug group-count mode rather
than a byte threshold, and the guard adds an H0 early return before it; H8/HStr
grouping, distinct aggregate spilling rules and aggregate-owned spilling are
untouched. The .sql/.result BVT pair was compared against the observed
output on a local instance; the full mo-tester baseline remains a CI job.

Upstream context: main fixed the same defect in PR #26736 for issue #26453;
this PR carries that decision to 4.2-dev with the same regressions.

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to matrixorigin#32233

## What this PR does / why we need it:

`group.(*container).needSpill` evaluates the debug group-count mode
(`spillMem < 10000`) by reading `ctr.hr.Hash.GroupCount()` without a
container-mode check. H0 (no GROUP BY) containers never build the
grouping hash table, so the first scalar-aggregation query on a fresh
table panics with a nil pointer dereference when
`SET @@agg_spill_mem = 256`. MergeGroup reaches the same call through
its H0 merge path, so plain `SELECT COUNT(*)` on a newly created and
populated table returns internal error 20101 with the reported
`needSpill` stack on 4.2-dev.

This is the 4.2-dev counterpart of main PR matrixorigin#26736, which fixed issue
matrixorigin#26453 by returning early for H0 in `needSpill`, because generic
group-spill partitioning requires the grouping hash table while H0
holds exactly one aggregate group. Aggregate executors that provide
their own H0 spilling, such as ordered GROUP_CONCAT, keep their own
spill behavior.

Changes:

- `pkg/sql/colexec/group/helper.go`: `needSpill` returns false for
  H0 before both the group-count debug branch and the byte-threshold
  branch, keeping the analyzer memory accounting unchanged.
- `pkg/sql/colexec/group/group_test.go`: port the matrixorigin#26736 regressions -
  `TestH0NeverRequestsGenericGroupSpill` (H0 asks for no generic spill
  at the 256 group-count threshold and the 10 KiB byte threshold with
  memory still reported), `TestH0OrderedGroupConcatSpillsIndependently`
  (ordered GROUP_CONCAT still spills through its own executor with
  zero generic spill writes), and
  `TestMergeGroupH0SkipsGenericSpillAndReuses` (real Group -> MergeGroup
  H0 hand-off over multiple partial batches, correct scalar counts, no
  hash-table construction, clean operator reset/reuse).
- `test/distributed/cases/qexec/group_h0_spill.sql` + `.result`: BVT
  covering fresh-table scalar COUNT at the low threshold and the
  normal byte threshold on one connection, resetting `agg_spill_mem`.

Validation (isolated worktree on 4.2-dev base ebf03dc, Go 1.26.4,
repo CGo environment, `.agents/skills/mo-dev/scripts/mo-cgo-test`):

- Red/green: the three focused UTs panic with the reported nil pointer
  dereference in `needSpill` when the guard is reverted to the 4.2-dev
  base, and pass with the fix.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=600s`
  on the focused H0 tests: pass.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=1200s
  ./pkg/sql/colexec/group`: full package passes, grouped (H8/HStr) spill
  behavior unchanged.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -run
  TestRefreshGroupConcatMaxLenForPreparedCompileReuse ./pkg/sql/compile`:
  dependent package test passes.
- `GOWORK=off go build` and `go vet -mod=readonly` on
  `./pkg/sql/colexec/group ./pkg/sql/compile`: clean.
- End-to-end SQL on a locally built mo-service (1 LOG / 1 TN / 1 CN,
  isolated ports): the issue's exact sequence returns 1 for 3/3 fresh
  tables at `agg_spill_mem = 256`, 1 at 536870912, grouped control
  (1,1), empty-input count 0, no internal error.

The broader mo-tester BVT matrix runs in CI.
@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

XuPeng-SH commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 2b692dab842f8404c0cfba36a9ade98e549c6b04

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 2b692dab842f8404c0cfba36a9ade98e549c6b04

Assessment: approve

The H0 guard fixes the scalar MergeGroup panic at the existing spill owner without adding runtime state. Grouped thresholds, memory accounting and aggregate-owned spill remain intact. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Reviewed the complete delta, baseline behavior, affected consumers, spill ownership, regression oracles and linked discussion.

  • Isolation preflight and frozen-range git diff --check passed. Receipts, source fingerprints, exits and retained logs are reconciled in validation-record.json.

  • Frozen evidence reports successful build, UT, static analysis, coverage and proxy/pessimistic BVT checks.

  • Focused local tests stopped before compilation because cgo/libmo.so is missing. This environment failure is not a product-test result.

Limitations:

  • Local package tests and SQL execution were not completed. Raw CI test logs and author validation logs were unavailable; author-reported successes were not independently reproduced.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

🛑 Queue command cancelled

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

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

Independent review of all four changed files at 2b692da against 4.2-dev@ff8632534e7f3b010ae675457ae9d6ac9f1aad80. The H0 guard is at the correct ownership boundary: generic group spill needs the grouping hash, whereas scalar aggregation has no such hash. Memory accounting still runs before the guard; H8/HStr threshold semantics and aggregate-owned ordered GROUP_CONCAT spilling are preserved. I checked both Group/MergeGroup callers, the partial-result/reuse and cleanup oracles, and the public fresh-table COUNT regression. This is an ordinary focused bug fix, not a new spill design. No blocker found.

Evidence reused: exact-head green CI plus the reported focused red/green, owning-package race, dependent compile and real SQL controls. I did not rerun the package or a service locally.

@mergify

mergify Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

queue

🛑 The queue request has been cancelled: new commits were pushed

Details

@XuPeng-SH pushed to this pull request after queue was requested. Review the new commits and request it again.

@XuPeng-SH
XuPeng-SH merged commit cde3318 into matrixorigin:4.2-dev Nov 9, 2026

This branch was successfully deployed

No deployments
ci — 7a940a88 Deployed Nov 9, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants