Skip to content

perf: avoid redundant work in string grouping - #31022

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
LeftHandCold:codex/group-string-batch-cost-20261024
Oct 24, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
LeftHandCold:codex/group-string-batch-cost-20261024

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #31024.

This scoped grouping optimization does not complete the broader benchmark or
bounded-domain aggregation work.

What this PR does / why we need it:

Ordinary GROUP BY allocated a 256-element group-ID scratch array for every
input chunk even though only dynamic grouping used it. Passing the array through
aggregate interfaces made it escape: an 8,192-row ordinary group call allocated
an unnecessary 65,536 bytes in 32 allocations. Allocate the chunk scratch only
for dynamic grouping, retaining its original lifetime and synthetic-row masking.

Flat raw MySQL string keys also repeated vector/type/collation/null dispatch per
row during sizing and grouping-aware encoding. Read the physical vector and
nullable bitmap once per column. Keep the same domain byte, uint32 length,
value bytes, padding, NULL match mask, overflow checks and pre-publication
allocation admission. CHAR, Unicode collation, const and grouping-sidecar
vectors retain their existing paths. No new persistent buffer, cache, worker,
protocol or storage format is introduced.

Validation on main 870f21d0877d1b4329bc84a36ca39dd07b2cbc36:

  • Both owning packages, scoped vet and configured incremental lint pass.
  • New independent key-byte/Insert/Find and COUNT/SUM tests cover nonzero offsets,
    composite and binary keys, wide values, NULL descriptors that must not be read,
    and a synthetic row in a 256+3 tail. Deliberately broken offset/masking variants
    fail their intended assertions.
  • Existing CHAR/UCA/const/grouping, capacity, spill/retry, reuse and publication
    tests pass. The same tests pass on the original production code.
  • ABBA microbenchmarks confirm the exact ordinary-group allocation reduction;
    dynamic grouping is unchanged. Raw key preparation/encoding is 38–42% faster
    in the measured shapes, with zero allocations; CHAR fallback is stable.

For real-query attribution, the exact four changed files were applied to the
frozen five-change benchmark source 1d8d1cec81aebce7300f9fde469ce118ab0731fc,
producing 008961e7e86fcba1742329c99e8f85495c560dce. Both changed production
files were identical between that source and the delivery main base before this
patch. This avoids attributing unrelated intervening main changes to this PR.

The same 9,999,997-row JSONBench STORED table and all five unchanged queries ran
in A/B/B/A order, four warmups and five timed executions per query per block
(ten measured samples per variant/query). Each owned engine/client/validator
unit used four cores, a 12 GiB hard limit and no swap; MO used the same 3 GiB CN
cache and 4 GiB Go memory setting. Profiling was separate from these timings.

Query Baseline median (s) Candidate median (s) Wall change Whole-unit CPU change
Q1 0.179753 0.118730 -33.95% -29.39%
Q2 1.354638 1.186975 -12.38% -11.80%
Q3 0.726372 0.703259 -3.18% -2.60%
Q4 0.458259 0.446040 -2.67% -1.53%
Q5 0.631308 0.620115 -1.77% -0.43%

All 180 complete outputs passed source-oracle checks; schema, 64 physical
objects, executable/native identities and resource limits stayed fixed. Q1/Q2
sample ranges are separated; small Q3/Q5 differences overlap and are not claimed
as robust gains. Whole-unit peaks were 5.219/2.952/3.077/2.874 GiB in ABBA order,
with zero memory events or swap. The last baseline peak is below the candidate
peaks, so this PR does not claim a universal reduction in whole-service peak
memory. It reduces the specifically measured allocation source.

The optional schema/query profile is tracked separately in
https://github.com/matrixorigin/mo-benchmark/pull/137. No schema or SQL rewrite is
part of this kernel PR. Q4/Q5 still have separate scan/conversion costs; this
patch does not establish that the broader mainstream-engine gap is closed.

Retained proof SHA256s: focused validation
47dc2a4ea206315b9815e020311fc10fc2dde713e88458ec49742d9dd473a849;
real-query ABBA
4ec2f5b2141391abc999ed8226223c5d8d2464902b305ccbf72781d3e2690a19.
Baseline/candidate executable SHA256s are
a47fd5e05e7065356e6d31da97ca83b04aea6bf68b27954e4d804827432f9752 and
034299c674c41185aa44a46acce0b04ee2a03f2101f7929ca2cee637b62bb421.

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

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

代码审查结论:建议通过,未发现需要 Request Changes 的确定性问题。审查 HEAD:7796269dc511ee3ae0f0f77c08d80e1e2dc950dc;merge-base:3878a13ef00fc85b1bced8a58a4f7d17df848806。

设计与范围:这是两个现有热路径的局部性能修复,不是新的聚合算法或资源管理框架。生产改动仍在原 Group 和字符串键编码 owner 内,未引入长期缓存、共享 scratch、状态机、协议或存储格式变化,普通修复无需另立架构设计文档。

核对内容:

  • 普通 GROUP BY 不再分配只供 DynamicGrouping 使用的 scratch;动态分组仍在原 mini-batch 生命周期内分配,并在 preflight 和实际 BatchFill 两处使用相同的 synthetic-row masking。尾批 n<256、容量失败后同 offset 重试不会访问 nil/过短 scratch。
  • 字符串快路径谓词与原 canonicalization 对齐:仅 MySQL string、非 CHAR、非 Unicode collation、非 const、无 grouping sidecar。JSON/数组和需规范化的字符串仍走原路径。
  • 对照了 prepare/encode/Insert/Find:domain byte、uint32 长度、原始值、16-byte padding、NULL 的 zValues 和非零 start offset 保持一致。NULL 先判断再读取 descriptor,不会读取 NULL 行的无效 varlena 地址。
  • sizing 的溢出检查、keyBuffer admission 和 publication 顺序没有被绕过;未发现 append 超出预估导致绕开内存账户的新路径。
  • 阅读全部新增测试与相关既有 CHAR/UCA/const/grouping、容量和重试测试。新 byte oracle 独立拼出编码,COUNT/SUM 验证覆盖 256+3 的 synthetic tail;没有靠大规模 UT 或定时等待证明边界。

Q1–Q3:临时 scratch 仍由调用生命周期/GC 管理,iterator 的 accounted scratch 继续由原 owner 释放;没有新增等待;每块 scratch 至多 256 个 uint64,编码容量继续由原 sizing/admission 控制。

性能结论限定:能确认实现删除了普通分组的这处分配和逐行重复 dispatch。作者 ABBA 的 Q1/Q2 收益与机制相符,但本次未独立重跑 JSONBench,不能将其表述为所有查询或全服务峰值内存都下降。

验证:本次完成全 diff/调用链/边界审查及 diff --check;作者报告的 UT/benchmark 结果不冒充本次执行。检查到 UT 和 SCA 是 checkout 阶段 gnutls_handshake 失败,尚未执行测试,不构成该补丁的代码失败证据。同 HEAD 的新 run 40075364835 仍在进行,不能称完整 CI 已通过。

当前认证账号也是作者,GitHub 不允许自审 Approve;以 COMMENT 记录“代码层面建议通过”,不替代 CI 门禁,也未执行合并。

XuPeng-SH pushed a commit that referenced this pull request Oct 24, 2026
…1032)

## 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 #31031

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

Short string-to-DECIMAL coefficients currently use full-width arithmetic
for every digit. Accumulate coefficients of at most 18 ASCII digits in a
uint64 instead: their maximum is below 10^18, so the high word is zero
and no intermediate can overflow. Keep the existing 19–38-digit path,
byte validation, empty input and exact error contract. Parsing, sign,
scale, rounding, overflow and warnings remain with the existing callers.
This adds 13 production lines and no allocations or shared state.

Validation on main `3878a13e`: both baseline and candidate pass the same
helper boundary tests and 13 neighboring/consumer tests, including
rounding carry and precise clamp warnings. Both changed owning packages,
gofmt, vet and configured incremental lint pass. Paired microbenchmarks
reduce 16/18-digit construction from 105.15/117.00 ns to 10.715/11.820
ns; 19/38-digit controls remain comparable. All four allocate zero
bytes.

Actual JSONBench validation uses 9,999,997 complete documents, the same
qualified clustered STORED table, four CPUs and a 12 GiB no-swap cap.
A/B/B/A, four warmups plus five samples per query/block: **all 180
complete outputs pass**. The performance baseline includes the grouping
optimization from #31022; the causal candidate adds only this
coefficient change. The delivery diff is independently based on main.

| Query | Base median | Candidate median | CPU change |
|---|---:|---:|---:|
| Q1, control | 95.338 ms | 89.592 ms | +0.13% |
| Q2, control | 1210.107 ms | 1181.660 ms | -1.50% |
| Q3 | 559.870 ms | 389.926 ms | -27.87% |
| Q4 | 288.780 ms | 266.437 ms | -13.35% |
| Q5 | 476.347 ms | 428.217 ms | -16.85% |

Q3/Q4/Q5 latency decreases are 30.35%/7.74%/10.10%, with separated
sample ranges. Q1/Q2 changes are not attributed to this patch. Candidate
peaks are 3.13/3.00 GiB; every block has zero limit/OOM/swap events and
stable schema/count/objects and executable/native identities. This is
bounded validation, not a universal memory-safety or overall
benchmark-completion claim; Q5 still trails the retained ClickHouse lane
by about 12.85x.

Evidence fingerprints: unit/static `3885e170…`; causal build
`7fc36daf…`; full SQL ABBA `1d13c630…`. No query rewrite, table-layout
change or benchmark harness is included in this PR.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 7796269dc511ee3ae0f0f77c08d80e1e2dc950dc

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: 7796269dc511ee3ae0f0f77c08d80e1e2dc950dc

Assessment: approve

Reviewed the complete four-file delta and affected grouping, join and DISTINCT callers. The design preserves existing ownership: ordinary grouping avoids unused scratch, while the guarded string fast path preserves key grammar, NULL handling, allocation admission and canonicalization fallbacks. No actionable defects found.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Verified the frozen head, merge-base, clean source and changed files against Git objects. Reviewed retry/spill, cleanup, chunk boundaries, constants, grouping markers and CHAR/Unicode fallbacks.

  • New tests exercise exact key bytes and capacities, nonzero offsets, unreadable NULL descriptors, duplicate lookup, and real Group execution across a partial final chunk with synthetic rows. Existing canonicalization and allocation/retry tests remain applicable.

  • Reused successful exact-head x86 UT, arm64 SCA, UT coverage, shared build, PROXY BVT and PESSIMISTIC BVT results. CI Required completed successfully at 2026-10-24T11:39:33Z. Repository test selection includes both changed packages; skipped and earlier failed checks were not counted as passes.

  • Static evidence audit passed: checks/1792843589415418500-2.json with evidence-audit-v2.log. git diff --check passed: checks/1792843565472485607-2.json with diff-check.log. Both receipts identify the assigned head and empty source delta.

  • Performance analysis supports removing ordinary grouping's per-chunk allocation and repeated raw-string dispatch. Dynamic grouping retains bounded scratch and retry lifetime; fallbacks add a per-column predicate. No new I/O, locks, goroutines or persistent caches are introduced.

  • Assessment, detailed review and evidence reconciliation are retained under /home/xupeng/.local/state/mo-bot/jobs/869df59bc8b6c12b46d862a4/attempt-1.

Limitations:

  • No local Go tests or SQL benchmarks were rerun. Validation reuses frozen CI conclusions; individual CI logs and retained local worker gates were not supplied.

  • Author-reported benchmark improvements lack accessible raw artifacts in the supplied evidence. No numerical speedup or universal memory reduction is independently certified.

  • The complete linked issue #31024 text was unavailable; its contract was assessed from the frozen PR description.

  • The initial static audit rejected only a missing terminal newline in change.patch. The corrected audit confirmed no substantive difference; both receipts and logs were retained.

@mergify mergify Bot added the queued label Oct 24, 2026
@mergify

mergify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-24 12:09 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-10-24 12:23 UTC · at 7796269dc511ee3ae0f0f77c08d80e1e2dc950dc

This pull request spent 13 minutes 49 seconds in the queue, with no time running CI.

Reason

Pull request #31022 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance]: ordinary grouping allocates dynamic-only scratch and repeats raw string key dispatch

3 participants