Skip to content

perf(aggexec): use dense accumulators for small Decimal64 SUM/AVG groups - #31419

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/perf-decimal64-dense-sum-r5
Nov 9, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/perf-decimal64-dense-sum-r5

Conversation

@VioletQwQ-0

@VioletQwQ-0 VioletQwQ-0 commented Oct 27, 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:

Related performance parent: issue #30518. This scoped candidate does not close the parent investigation.

What this PR does / why we need it:

Grouped Decimal64 SUM/AVG currently builds and probes a local hash table even when its aggregate state already provides a small dense group-ID range. For non-DISTINCT Decimal64 fast executors with exactly one state chunk and 1–256 groups, this change accumulates sums and non-NULL counts in fixed local arrays, records touched groups, and scatters each touched result once. DISTINCT keeps its existing path, and other state shapes keep their general accumulation algorithm. After the DISTINCT dispatch, a constant-NULL vector returns before either helper is selected; the general and dense helpers no longer repeat that check. Non-constant vectors avoid the full constant-NULL predicate at the entry.

Public return types, Decimal256 dispatch, unchecked Decimal128 accumulation and checked finalization semantics, state serialization, merge behavior, and input ownership are unchanged. No scratch-S optimization or COUNT DISTINCT repair is included.

The three existing R5 differential regressions are retained, with empty-input/zero-group cases added to the same suite. They cover offsets, unmatched rows, constants, NULLs, 255/256/257 groups, multiple state chunks, growth across the admission boundary, input preservation, and cancellation of an unchecked near-limit prefix. Existing merge, legacy wire-format/DISTINCT, rounding and Decimal256 tests supply adjacent coverage. The canonical AVG numeric BVT now checks grouped SUM/AVG on both sides of the boundary. Its pre-existing AVG string expectation is aligned with main's existing scale rule (input scale 2 + 4 = 6); this changes a stale fixture expectation, not product semantics. Existing metadata expectations are preserved.

Validation and evidence

Rebase to main

Rebased onto main 0f6c07639604c40d7ca880cb63d1d282239def08; the rebased PR head is 883f4249b462bee3cd2ce0a2c134d2f35dc3b20a. git range-diff matched the three original non-merge commits, and the test-cleanup merge and author attribution were retained. On Go 1.27.1 darwin/arm64 with native libraries rebuilt for this source, focused Decimal64 dense and constant-NULL state tests passed normally and under -race; git diff --check passed. The measurements and earlier qualification below retain their stated historical baselines; no new reward or MCTS measurement was run. Current-head CI and normal review remain pending.

Historical performance evidence — not measurements of this main-based head

Frozen historical baseline 68e642fdc533e96ed8f83ac44659119ad8be97af versus R5 a87d2290ba566f77298d15e5955d25a01aaf3d4b:

Original reward query Median paired elapsed reduction
1 client, BR/RB 7.14%
10 clients, BR/RB 10.29%

All four paired server-CPU comparisons decreased. Both products were rebuilt with identical Go 1.27.1/CGo/native inputs, effective build settings and invocation; all 484 original-input requests passed their checks (400 timed, 80 warmup, 4 calibration). These are reward-query results on that historical baseline, not full-MCTS gains, recovered paper performance, or correctness qualification.

In a separate older kernel microbenchmark, the 8192-row/100-group case improved by a median 30.98% across three retained pairs. The 1-row/257-group fallback control changed by a median +0.79% elapsed, with mixed directions; both arms recorded 0 B/op and 0 allocs/op. No microbenchmark matrix was rerun for this port.

Exact revision and focused validation

  • Base M: 533e95796177d9eacdc909059ccf72b7ddd3ba5f.
  • Head H: 8d74e63cfd61ef64fd3f8eb096df5af5d358e347. This is the head bound to the focused evidence below; the pre-rebase test-cleanup merge was dde4662aba5234b5616519daead5721413392f31 and the subsequent C change was ca7f67b09660ca37891494f061980194c6d52f05.
  • Toolchain: Go 1.27.1, darwin/arm64, GOEXPERIMENT=simd, GOWORK=off, readonly modules. CPU native libraries were rebuilt from M and passed the repository provenance verifier; the same unchanged native artifacts were used for M/H qualification. Local default Go 1.26.4 was not used.
  • Focused normal tests: 42 named aggexec roots, -count=1; selected/run/pass identities checked, no skips.
  • Relevant race: 16 named roots, -race -count=1; selected/run/pass identities checked, no skips.
  • Real SQL: independently checked SUM/AVG/NULL/constants/DISTINCT/joins/input preservation across seven fixtures; widened SUM, explicit CAST clamping with warning 1264, and recovery after an expected SQL error.
  • M and H: changed canonical BVT compared twice on each owned service with table teardown checked between runs; existing sum_decimal256_precision.test compared successfully. SQL and ISCP readiness were checked, and both services closed normally. Case/result bytes were copied unchanged to test-owned paths because this installed mo-tester rewrites dotted directory names while locating .result; it was not modified.
  • Incremental go vet ./pkg/sql/colexec/aggexec, git diff --check, and joint semantic/self-review of this exact four-file diff.

These are focused developer checks on macOS, not full package/race qualification or CI/QA acceptance. Full MCTS and S/S+R5 integration were not run.

Open qualification gates

A prior Linux qualification hit an unresolved COUNT DISTINCT native allocator failure, now tracked in #31732. Full race qualification is also incomplete. Follow-up baseline controls retained a native failure while other controls passed, but the first corrupting write and its relationship to R5 remain unresolved. Baseline failure, identical DISTINCT source, or non-reproduction in another condition do not exonerate this candidate. All prior failed evidence is retained; no restricted memory diagnostic was replayed. A confirmed independent correctness repair belongs in a separate PR.

Limited reward confirmation on the newer main baseline

The finite confirmation freezes main at baa83f4b96e56ec214f92c68f7b56539b9e0fa45 and measures the GitHub PR merge tree 26dad7fbc63d8df9bac9a68754ae044f0de969db, whose parents are that main and PR head 8d74e63cfd61ef64fd3f8eb096df5af5d358e347. The merge tree differs from main only by this PR's four files; the single runtime source difference is the Decimal64 optimization. The PR head itself was not rewritten.

Clients Order Main → merge elapsed (s) Main → merge MO CPU (s) Elapsed reduction
1 BR 5.511 → 5.124 33.588 → 30.573 7.02%
1 RB 5.373 → 4.951 32.734 → 29.591 7.85%
10 BR 4.920 → 4.594 34.530 → 31.320 6.63%
10 RB 4.946 → 4.535 34.584 → 31.222 8.31%

Median paired elapsed reduction was 7.43% for 1 client and 7.47% for 10 clients; median paired MO CPU reduction was 9.29% and 9.51%, respectively. All four elapsed and CPU comparisons improved. These two pairs per client support continued investigation, not a full-MCTS or paper-performance claim.

Both Linux/amd64 binaries used Go 1.27.1 with identical effective Go/CGo settings, native libraries, build invocation and binary build metadata; native inputs were freshly built from the frozen main and passed provenance verification. The original 30-million-row reward input and checks were reused. All 484 recorded requests passed: 400 timed, 80 warmup and 4 calibration; eight-table pre/post oracles, resource gates, service close, evidence readback and exact-owner lock release passed. No extra samples were selected.

The first preparation attempt stopped at source-tree verification before any build or reward request because the archive omitted a gitlink. Its failed evidence was sealed, and the corrected import was independently checked against the exact main tree before this campaign.

QA required: yes. R5-specific qualification and normal review remain required. The COUNT DISTINCT issue is tracked separately in #31732 per the requester's decision and is not an additional merge prerequisite; its root cause and relation to R5 remain unresolved. Normal review may still raise any concrete candidate-related defect. Exact-head CI, applicable qualification, performance disposition and normal review remain required; no full-MCTS benefit is claimed.

Test-cleanup merge and performance disposition

The #5 change only modifies sum_decimal_dense_test.go; sum_decimal_fast.go is unchanged from 8d74e63c…. Before the merge, the exact #5 test-file blob was applied as a Go overlay on the clean parent using Go 1.27.1 on darwin/arm64 with verified native provenance. The three dense regression roots passed normally and under -race (61 test pass events per run, no skips); all 12 benchmark cases completed a one-iteration cleanup smoke run. After merge, the test-file Git blob equals the validated overlay. This is source-equivalence validation; the binaries were built before the merge commit and are not claimed to contain its VCS identity. Current-head CI remains the authoritative CI gate.

Historical local controls reported constant-NULL +5.19% and sequential groups +0.88% for PR 8d74e63c… locally merged with main 802376360c…. The original raw comparison and complete build identity were not independently verified; these remain historical signals, not current-head measurements.

Constant-NULL follow-up C: validation and performance disposition

The pre-rebase commit ca7f67b09660ca37891494f061980194c6d52f05 adds only the early non-DISTINCT constant-NULL dispatch and its state-transition regression. Its product source is byte-identical to the Ubuntu C overlay; the committed regression test is byte-identical to the test portion of that overlay fixture. The Ubuntu measurements used a common baa83f4b… source base with B/R/C product overlays, not the exact final PR commit or a release binary. B's Decimal64 SUM source matches the original branch base; R's matches dde4662a…. Go 1.27.1/linux-amd64, identical CGo/native, GOAMD64=v3 and GOEXPERIMENT=simd were used. Six interleaved rounds were pre-specified; all 108 case/version samples are retained.

Control R vs B elapsed C vs R elapsed
Constant NULL, dense +5.92% [+5.49%, +6.36%] -17.26% [-17.64%, -16.87%]
Constant NULL, fallback +5.70% [+5.19%, +6.20%] -17.08% [-17.71%, -16.44%]
Sequential groups -36.03% [-38.07%, -33.92%] -0.06% [-4.40%, +4.47%]

Intervals are paired, two-sided 95% t intervals. Each operation processes 8,192 rows in 32 BatchFill calls; the dense constant-NULL B/R medians were approximately 112.0/118.65 ns per operation. Production frequency and SQL-level cost are unknown. The two NULL shapes and three other controls met the pre-specified C criteria; sequential groups remain INCONCLUSIVE, with an upper bound above the original +1% criterion. The requester accepts this limited uncertainty for normal review given the measured NULL benefit, other controls and bounded code inspection; this does not imply maintainer acceptance, a full performance pass, or a claim that C cannot regress in a real workload. No favorable samples were added or excluded.

The final C worktree content was tested on Go 1.27.1/darwin-arm64 with verified native provenance: focused SUM/AVG and dense/state-transition normal and -race runs each recorded 246 pass events including subtests, with zero skips. Incremental vet, lint, gofmt and git diff --check passed. Tests ran before committing and their source and test file hashes were verified equal to ca7f67b…; this is content-bound evidence, not an exact-commit VCS-stamped test binary. Earlier SQL/BVT evidence remains bound to 8d74e63c…; no new real SQL or reward execution was performed for C. Final-head CI and normal review remain required. Full MCTS and S/S+R5 were not run.

The old dde4662a… CI included an HNSW vector BVT failure, a canceled SCA job and coverage blocked by a missing producer; its cause and relationship to this PR are not determined. New-head CI must be assessed independently.

Independent local qualification and open regressions

The PR source 8d74e63cfd was merged locally with MatrixOne main 802376360c; these checks do not resolve the historical COUNT DISTINCT allocator failure tracked in #31732. The owner aggregate and group suites passed under -race on that merge. Two allocation-sensitive aggregate tests were skipped by their existing race guards and passed separately without instrumentation.

A full aggregate AddressSanitizer run passed on clean main and the main-merged PR with the test-only cleanup in the follow-up PR. Three allocation-count tests were run separately without instrumentation because sanitizer bookkeeping changes those counts. The prebuilt native libraries were not rebuilt with sanitizer instrumentation. Repeated COUNT DISTINCT tests and the selected DISTINCT sanitizer suite did not reproduce a corrupting write; the historical failure remains unresolved. The original fixed-width commands, binary bindings and logs are retained locally, but have not been published as attachments.

The matched local 22-case control matrix for the PR found slower signals. A separate six-pair, one-second-per-case confirmation measured constant-NULL batches at +5.19% (95% interval +4.99% to +5.31%) and sequential groups at +0.88% (+0.14% to +1.21%) versus clean main. Each operation uses 8,192 rows in 256-row calls. Component wins in other shapes do not waive these regressions.

A private, dense-only NULL correction improved the constant-NULL control by 8.39% but still showed sequential +0.89% and endpoint +0.36% in separate confirmations. Its independent SF10 Q1/Q18 comparison measured Q1 −2.82% (95% interval −5.04% to −0.30%) and Q18 +0.69% (−2.15% to +4.77%). These measurements are for the corrected local revision, not the current PR head. The correction has not passed the no-regression gate and has not been added to the PR.

The local TPC-H comparison used eight physical cores, a 16 GiB CN cache and a 32 GiB whole-application budget. All 12 scored arms passed the recorded memory and host gates; the first cold execution was excluded. The worker executed and drained queries without verifying inputs, schemas, rows or results or computing checksums. SF100 was not run locally.

Mergify's previous branch-update check reported that it needs authorization to modify the fork's head branch. The test-only cleanup in follow-up #5 is now merged into this branch; its merge commit is dde4662aba5234b5616519daead5721413392f31. Current-head CI and normal review remain required; the allocator report is tracked independently in #31732.

Further local dispatch experiment — rejected

A general-path-first revision (6db8b143f0, not on this PR) was compared directly with the main-merged PR source plus the separate test cleanup (5bba376c9e). The 22-case owner matrix found no slower signal relative to the PR and improved its constant-NULL control by 13.02%. That did not establish end-to-end acceptance: the full local SF10 Q1–Q22 comparison found Q8 +3.22% (95% interval +1.98% to +4.76%) and Q21 +1.94% (+0.41% to +2.79%). A separate six-pair Q8/Q21 run with nine warm calls per arm independently confirmed Q21 +1.80% (+1.01% to +2.46%). This candidate is rejected.

Q8's longer standalone-context check had a −1.03% paired median with an interval from −3.21% to +3.98%; it does not reproduce or invalidate the full-suite Q8 result because query warm-up order differs. A full-prefix Q8 repeat was stopped after the independent Q21 regression already rejected the candidate; its partial timings are not used as acceptance evidence. In separate warm Q21 CPU profiles, both binaries spent the largest sample shares in the same hash-probe and decompression functions. Scan filtering accounted for 3.39% of baseline samples and 3.78% of candidate samples; its function entry moved by 32 bytes relative to a 64-byte instruction-cache line even though its source did not change. Q21 uses COUNT(*) rather than SUM. These observations are consistent with an indirect code-placement or runtime effect but do not identify a proven cause; each profile is a separate sampled run. All scored arms ran locally with the cold execution excluded and without input, schema, row or result verification.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Could an aggexec/memory-lifecycle maintainer review the following evidence and advise whether the remaining COUNT DISTINCT allocator risk blocks this PR? The reviewed PR head is 8d74e63cfd61ef64fd3f8eb096df5af5d358e347; it remains Draft and the known native failure is not considered resolved.

Direct path and remaining uncertainty. The historical TestCountDistinctUnmarshalAcrossAccountedArenaGrowth/fixed-width constructs countColumnExec for int64 with DISTINCT and its BatchFill goes through COUNT's argument path, rather than the new Decimal64 SUM/AVG dense receiver. Source and target use separate executor state but share the test's pool/account. The historical isolated fixed-width invocation selects that subcase in its own test process. This narrows direct execution; it does not exclude indirect allocator, process-layout, or other effects and does not establish that the old R5 and later B failures share a cause.

Retained failures and controls. On the historical B/R5 pair (68e642fd…/a87d2290…), the isolated fixed-width ordinary test passed once on B and aborted once on R5 during source-fill preflight. The historical ordinary binary SHA256 values were 1e248d0cf5f6e5c7cb48983a5b3614facdfa46cf57c2c60f281c8703d8b0b42c (B) and 94e3c58378b93352699b7e3e185039919707600d9e3a7cbadce76b1ece57c20f (R5). A later, separately built B test binary (c9ba2a86f6a78978cac2d6e566c2abadd9d28c0878c5a31899f8749856980c66) aborted during source release in an allocation-only condition that did not insert target nodes; other one-shot controls passed. Neither the last free nor the fact that B also failed proves the cause or exonerates R5.

The PR's later text says the original report lacks a failing command or log. We have locally sealed commands, binary bindings and raw logs for the historical isolated B/R5 runs and the separate B observation; they have not yet been attached publicly. Please distinguish the unavailable public artifact or any different original report from the records that exist locally. The historical process's actual libc mapping and allocator symbol binding remain unverified.

Patch and current validation. The dense path accepts non-DISTINCT Decimal64 fast executors with one nonempty state of at most 256 groups and assumes callers supply valid admitted group IDs. Its local arithmetic uses the existing unchecked Decimal128 addition; input is read-only. Current-head CI checked out 8d74e63c… and completed the aggexec -race -short package stage and non-race coverage job; the accessible CI artifacts do not preserve each selected root's individual pass event. These results do not discharge the native failure or full qualification.

Two additional items remain visible in the PR: the new dense tests leave registered test pools behind, with cleanup proposed separately in fork follow-up #5, and later local controls report constant-NULL and sequential-group slowdowns. The full-SF10 timing experiments disclosed in the description did not verify inputs or results and should not be treated as validated workload correctness. The earlier reward-query pairs remain positive but do not erase those signals or establish full-MCTS improvement.

Please advise on two decisions: (1) do the patch's bounds, dispatch and validation support its correctness, subject to resolving the test-cleanup issue? (2) does the unresolved historical COUNT native failure still block merge? If an exception is considered, please explicitly identify the remaining risk, rationale, responsible owner and follow-up rather than treating an approval as proof that the failure was fixed.

VioletQwQ-0 commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Ubuntu performance controls and the NULL follow-up

A finite Linux/amd64 comparison on Go 1.27.1 (GOAMD64=v3, GOEXPERIMENT=simd) used the same fixture, native inputs and build settings for B, R and C. The common source base is baa83f4b96e56ec214f92c68f7b56539b9e0fa45; B's Decimal64 SUM source matches the original 533e9579 base; R overlays the Decimal64 SUM source from the then-current PR head dde4662aba5234b5616519daead5721413392f31. These are source-overlay test binaries on the common base, not full PR-head release binaries.

Each benchmark operation processes 8,192 rows in 32 BatchFill calls. Six interleaved B/R/C rounds were fixed in advance; each version/case used a separate one-second benchmark invocation. The table reports paired log-mean elapsed changes and two-sided 95% t intervals; negative is faster.

Input R vs B C vs R
Constant NULL, dense state +5.92% [+5.49%, +6.36%] -17.26% [-17.64%, -16.87%]
Constant NULL, fallback state +5.70% [+5.19%, +6.20%] -17.08% [-17.71%, -16.44%]
Sequential groups -36.03% [-38.07%, -33.92%] -0.06% [-4.40%, +4.47%]

For the constant-NULL dense control, B/R median elapsed was approximately 112.0/118.65 ns per 8,192-row operation, an increase of about 6.65 ns/op in this fixture. This microbenchmark does not establish production frequency or a SQL-level cost. The earlier +0.88% sequential control lacks a fully verified build/fixture identity and cannot be treated as the same comparison. The prior 7.43%/7.47% elapsed improvements in this description concern the reward query, not full MCTS; the two kinds of percentage cannot be added or netted.

At measurement time C was an uncommitted experimental source overlay; it is now included in this PR as commit ca7f67b09660ca37891494f061980194c6d52f05. The measured binaries are source overlays on the common base, not binaries built from that commit. It adds vectors[0].IsConst() && vectors[0].IsConstNull() after the DISTINCT branch and moves the helper NULL checks to the entry. The complete NULL predicate remains in use; the extra constant-class check is not by itself treated as proof of regression. Five of the six pre-specified shape checks pass, while sequential groups remain inconclusive because the C-vs-R interval exceeds the pre-specified +1% upper bound. No samples were excluded or added. The six sequential samples in ns/op, in round order, were:

Version 1 2 3 4 5 6
B 31234 31183 31233 31217 31011 31155
R 19685 19669 19832 19769 21122 19608
C 19717 19658 19701 21128 19756 19653

The slower samples occur once in each version. Read-only inspection of the measured binaries confirms that C's non-constant entry skips the full NULL call and associated entry spills; the dense helpers use the same stack allocation, and the source-mapped group loop differs by an additional NOP after address/branch normalization. No first-order cause for the two samples was established. Host load/CPU/I/O snapshots are coarse and do not prove or exclude interference; per-run cgroup memory peaks were unavailable.

B/R/C focused normal tests and C race each recorded 246 pass events, including subtests, with no skips. This is focused overlay evidence, not complete CI or SQL/MCTS qualification. At the time of this measurement the previous head's required CI had failed; the current PR head and CI status must be assessed separately. COUNT DISTINCT remains tracked separately in #31732; its cause and relation to R5 remain unresolved.

The requester accepts the remaining sequential-control uncertainty for normal review, given the measured NULL benefit and the other controls. The original +1% criterion remains unmet and the result remains inconclusive; this decision does not imply maintainer acceptance or a measured real-workload benefit for C. Final-head CI and normal code review remain required.

@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 4, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 883f4249b462bee3cd2ce0a2c134d2f35dc3b20a

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: 883f4249b462bee3cd2ce0a2c134d2f35dc3b20a

Assessment: approve

The bounded dense path reuses existing aggregate state and arithmetic while retaining the necessary general fallback. Reported historical gains justify the narrow specialization. No actionable defects remain within the accepted scope.

Model: gpt-6.1-sol / max

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

Validation:

  • Reviewed all four changed files, five discussion entries, linked issues and affected owners/consumers.

  • Reused attributed current-head normal/race results and latest successful build, UT, SCA, coverage and active BVT statuses.

  • Static source/oracle audit passed; checks/1793767342479570376-3.json matches static-audit.log. Review and evidence records are retained.

Limitations:

  • No fresh local Go, SQL or performance runs; raw execution logs and historical Git objects were unavailable.

  • Current-head speedup is unmeasured; the sequential-control comparison remains inconclusive under the accepted scope.

  • The historical COUNT DISTINCT native abort remains unresolved and separately tracked in #31732.

@mergify

mergify Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

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

Reviewed all four changed files and the surrounding Fill/BatchFill/state consumers. The dense helper is limited to one nonempty state chunk with at most 256 groups; zero/unmatched/NULL rows, offsets, constants, the 256-to-257 transition and unchecked Decimal128 accumulation remain consistent with row-wise Fill. DISTINCT and larger states retain their existing paths, and the input remains read-only.

No blocking findings. Reused latest-head green CI and the source-bound differential/race and SQL evidence described in the PR. The historical performance/qualification limitations remain limitations, not claims of full-workload acceptance. No new local tests or benchmarks were run.

@XuPeng-SH

XuPeng-SH commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 883f4249b462bee3cd2ce0a2c134d2f35dc3b20a

New discussion was assessed; the previous review remains unchanged.

@XuPeng-SH
XuPeng-SH merged commit 843929f into matrixorigin:main Nov 9, 2026
XuPeng-SH pushed a commit that referenced this pull request Nov 9, 2026
…32357)

## 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 #31175
Related to #31179

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


**Design.**
`docs/design/20261108-pattern-matching-effective-collation.md` (revision
r5, SHA256
`c37413e83c10d49cd71153d22b2066733d3ecc1f2a543b14b50b830c9ecbba42`,
revised in `b9d08296ef` after the rebase onto `c99234dcf4`) records the
problem evidence, invariants, MySQL/ICU/UCA precedent and alternatives,
ownership and data flow, resource budgets and boundaries,
compatibility/rollout, and the validation map for the complete change.
r5 corrects r4's validation-map fold-fully expectation with engine
bounds measured during the post-approval implementation: exact fold
emission grows quadratically with run length, and the regexp2 route's
binding engine bound for long fold runs is its compiled
backtracking-state limit (4,096 tracks — a 40-rune fold run compiles at
1,439 tracks and is admitted; an 80-rune run compiles past the bound),
so the round-14 four-alternative comment-bearing shape raises the
bounded resource-limit error under `i` even after deduplication, and
fold-fully proofs relocate to below-bound regexp2 shapes and to the RE2
route at the original scale. No invariant, ownership decision, budget
value, or error family changes; r4's independent design-only PASS
(SHA256
`c31aef6c201f712c72aca88c59149d6805f1b99fddad9d2a0cde724021edc098`)
remains the base. r4 had resolved the r3 finding (equal effective
inline-option state before deduplication; an intervening unscoped setter
makes a duplicate ineligible, so `^(?:ss|(?i)a|ss)$` keeps both `ss`
branches) and carried forward the r3 resolutions of the two r2 findings
(capture/backreference/option-aware dedup eligibility; the
resource-limit error contract with planned public-path BVT proof).
Design r5 passed the independent design-first review, and the production
deltas are implemented in head `bd80b57137` on top of the r5 design
commit. Revision r6 (2026-11-09) records the resolution of the
implementation review's P1 on the r5 head: the alternative-deduplication
prepass is linear and carries its own charged work bound (4 MiB) —
construct marks land on the innermost branch in O(1) with close-time
flag folding into the enclosing branch, and each alternation closure
tracks its most recent unscoped-setter branch incrementally — so many
identical siblings and deeply nested groups cannot perform quadratic
work before the rewrite budgets are initialized; abandoning the prepass
returns the source pattern unchanged, deferring to the approved
expansion budgets with no new SQL-visible outcome. It extends
`docs/design/regexp-icu-compatibility.md` (issue #28305), whose
admission/cache/budget layer this change threads case folding through.

**Problem.** `LIKE`, `ILIKE`, `REGEXP`/`REGEXP_LIKE` and `FIND_IN_SET`
ignored the effective collation and compared byte-wise. Under the
default `utf8mb4_general_ci` (and under an explicit `utf8mb4_unicode_ci`
column) `'a' LIKE 'A'` returned 0 and `WHERE name LIKE 'alice%'` missed
`'Alice'`, while MySQL returns 1 for both — and while `=`/`IN` and
`LOCATE`/`INSTR`/`POSITION` on the same data already honored the
collation. Pattern operators therefore disagreed with their sibling
operators, and `LIKE 'prefix%'` index range scans could return different
rows than folded scans.

**Root causes closed by this PR.**

1. The LIKE executor and FIND_IN_SET ran byte-wise matchers and the
regexp engine ran case-sensitively; none of the pattern operators
consulted the operands' resolved collation (column COLLATE, expression
COLLATE, session default, `_binary` introducer, `CAST(x AS BINARY)`).
2. Collation-correct matching needs more than per-character caseless
flags: `utf8mb4_general_ci` folds by MySQL's weight table,
`utf8mb4_unicode_ci` compares UCA 4.0.0 primary weights per character,
and ci REGEXP needs Unicode full case folding (`ß`↔`ss`) that
per-character orbits cannot express.
3. The planner rewrote `col LIKE 'prefix%'` into byte-ordered
`prefix_eq`/`=` filters, which return different rows than
collation-folded LIKE.
4. Constant folding truncated planner-built binary→text conversions
whose target width is `-1` (every non-empty constant folded to `''`) and
re-marked folded `CAST(x AS BINARY)` literals as binary-introducer
domains, losing a winning case-insensitive collation.
5. Aggregating the matchers into collation resolution exposed implicit
ci-column vs `CAST(x AS BINARY)` ties (equal coercibility 2) to the
resolver's version check, raising error 1267 where base behavior and
MySQL compare byte-wise; `find_in_set`'s overload registration also cast
binary operands to utf8 `varchar`, erasing the binary string domain for
non-constant operands.
6. Constant `CAST(x AS BINARY)`, `BINARY 'x'` and `binary(x)` presented
a coercible literal's coercibility (4) instead of MySQL's IMPLICIT
coercibility (2) for cast results: folding replaces the cast with a
literal that keeps only its type, and the `binary()` function fell
through to the default rank. A case-insensitive column then strictly
outranked the binary operand and the planner converted it to
case-insensitive text, flipping `vc LIKE BINARY 'a%'` / `vc LIKE
CAST('a%' AS BINARY)` / `BINARY vc LIKE 'a%'` to case-insensitive
(surfaced by `operator/mysql_compat_string_binary_comparison`).

**What changes.**

- `pkg/common/collation/wildcard.go` (new): collation-aware LIKE matcher
— general_ci weight folding, UCA per-character weights, `_`/`%`/ESCAPE
handling, bounded multi-`%` segment matching with cancellation.
- `pkg/sql/plan/function/func_builtin_regexp.go`,
`regexp_casefold.go`/`regexp_casefold_tables.go` (new), `regexp_icu.go`:
LIKE/ILIKE/REGEXP/REGEXP_LIKE resolve the operands' collation (including
the ESCAPE argument; `REGEXP_LIKE` resolves from subject and pattern);
ci collations route LIKE through the weighted matcher and REGEXP through
an exact, bounded full-fold pattern rewrite (byte-identical below its
budgets; per-character caseless orbit above them); the binary/ci mix
keeps MySQL's error 3995 in both operand orders, and malformed-pattern
verdicts are always taken from the source pattern as written.
- `pkg/sql/plan/function/func_binary.go`: FIND_IN_SET honors the
resolved collation (weighted whole-key membership, unpadded comparison;
trailing spaces stay significant).
- `pkg/sql/plan/collation_expression.go`: expression-level collation
resolution covers the pattern matchers; a scoped pairwise tie rule
(`patternBinaryCollationAdmission` + `pairwiseBinaryTieWinner`) restores
the base behavior for implicit ci-column vs binary-CAST predicates only
— the binary operand wins the equal-implicit-rank tie,
LIKE/ILIKE/FIND_IN_SET compare byte-wise, REGEXP keeps 3995, and
text-text conflicts still raise 1267. Binary-domain cast results are
stamped with MySQL's IMPLICIT coercibility (2) so the tie rule, not a
rank-4 literal default, decides them.
- `pkg/sql/plan/base_binder.go`: `CAST(x AS BINARY)`/`BINARY 'x'` carry
IMPLICIT coercibility from creation; the stamp rides the expression
type, so constant folding (which preserves the type wholesale) cannot
drop it.
- `pkg/sql/plan/opt_misc.go`: for case-insensitive columns the planner
keeps the LIKE predicate instead of rewriting it to byte-ordered
`prefix_eq`/`=` filters, so scan and index paths return the same rows.
- `pkg/sql/plan/function/func_cast.go`,
`pkg/sql/plan/rule/constant_fold.go`: negative-width conversion targets
no longer truncate folded constants, and a folded binary-CAST literal
keeps the selected text domain when an explicit ci collation won the
resolution.
- `pkg/sql/plan/function/list_builtIn.go`: `find_in_set` uses the
domain-preserving overload registration.

**Issue-to-test proof.** Every reproduction row from #31175 and the
preserved #31179 report is pinned: `'a' LIKE 'A'`/`'ABC' LIKE
'abc'`/`'abc' REGEXP 'ABC'`/`'abc' REGEXP '[A-Z]+'` now return 1; the
`ci1`/`uci2` table rows match folded `LIKE 'alice%'` and `REGEXP
'^alice'`; `FIND_IN_SET('A','a,b')` = 1; explicit `utf8mb4_unicode_ci`
column and literal COLLATE cases agree across `=`/IN/LIKE/REGEXP;
binary/case-sensitive controls (`_bin` collations, `_binary` domains)
stay byte-wise; `LOCATE`/`INSTR`/`POSITION`/`FIND_IN_SET` neighbors keep
their behavior.

- UT: `pkg/common/collation` (weights, segments, boundaries),
`pkg/sql/plan` (resolution/admission matrix incl. CAST and prepared
shapes, executor routing over real typed batches, fold/cast
preservation, folded-`CAST(x AS BINARY)`/`BINARY 'x'`/`binary()`
coercibility regression test) and `pkg/sql/plan/function` (fold rewrite
tables/orbits, matcher routing, error shapes).
`pkg/sql/plan/build_show_desc_oracle_test.go` fixture spellings now
differ beyond letter case, because the DESCRIBE/SHOW COLUMNS filter LIKE
honors the effective case-insensitive collation (the #32197
replan-refilter assertions are unchanged).
`pkg/tests/sqlintegration/like_prefix_index_test.go` pins its #31940
prefix-plan fixtures to `utf8mb4_bin`, the byte-ordered domain the
prefix rewrite requires, and the new
`TestLikePrefixCaseInsensitiveKeepsFoldedPredicate` proves that under
`utf8mb4_general_ci` the analyzed planner keeps the folding LIKE
predicate (no `prefix_in_range`/`prefix_eq`) while scan, forced-index
and computed-subject paths all return the folded rows
(`'abc'`/`'ABC'`/`'Abc'` for `LIKE 'abc%'`).
- BVT: new
`test/distributed/cases/charset_collation/issue_31175_pattern_collation.sql`
— 416 statements covering literals, columns, explicit COLLATE in both
operand orders, `_binary`/HEX/BIT/CAST domains, prepared `CAST(?)`
parameters, user variables, VARBINARY columns, index-vs-scan plans,
NULL/empty/escape boundaries and error texts; every expected value
probed against a MySQL 8.0.44 oracle. Its resource-boundary rows pin the
r5 contract: the 328-byte four-alternative comment-bearing shape raises
the bounded resource-limit error naming the regexp2 4,096-track
backtracking-state bound under `i` while the `c` control returns 1,
below-bound shapes fold fully on the regexp2 route (six `ß` match twelve
`s`), and the RE2 route folds fully at the original scale (forty `ß`
match eighty `s`). New
`test/distributed/cases/charset_collation/issue_31175_pattern_resource_limits.sql`
(15 statements) pins the bounded error contract at every bound —
per-pattern emission budget exhaustion, RE2 nesting admission, the
4,096-track bound, and below-bound positive/negative fold controls
(`CONCAT(REPEAT('ß',20),'a')` matches the forty-`s`-then-`a` branch = 1;
the unsuffixed subject = 0). Existing expectations updated only where
folding intentionally changes results (`operator/like_operator`,
`optimizer/like` plans, `function/func_regular_like` CRLF-multiline
rows), plus the same intentional case-folding flips surfaced by CI in
`charset_collation/charset_collation_advanced` (`code LIKE 'abc%'`),
`charset_collation/charset_collation_basic` (`name LIKE 'app%'/'APP%'`
on the `general_ci` table; the `utf8mb4_bin` controls are unchanged),
`operator/operator.test` (`username LIKE '%Frau'`),
`operator/regexp_operator` and `operator/not_regexp_operator` (`'Acorn'
[NOT] REGEXP 'Corn'`), and `fulltext2/fulltext2_covered` (`tag LIKE
'Act%'`). `operator/mysql_compat_string_binary_comparison` keeps its
committed expectations: its CI failure was root cause 6, fixed in code.

Local validation: `mo-cgo-test -count=1 ./pkg/sql/plan
./pkg/sql/plan/rule ./pkg/sql/plan/function ./pkg/common/collation` (all
packages pass), `go vet` clean, gofmt clean, `go test -count=1 -run
'TestLikePrefixIndex$|TestLikePrefixCaseInsensitiveKeepsFoldedPredicate$'
./pkg/tests/sqlintegration` (both pass, memory+persisted phases; the
unadapted fixture failed the line-105 plan assertion in CI coverage UT
on this head), and mo-tester `run` of the new BVT passes 410/410 on the
fixed binary while the pre-fix binary fails exactly the new
discriminator statements. At the pre-rebase r5 head `5c628ab92f` (same
diff, now rebased): focused UT batches pass (`pkg/sql/plan/function`
dedup/fold/routing suites incl.
`TestRegexp2CaseFoldIdenticalAlternativesDedup` and
`TestRE2CaseFoldIdenticalAlternativesDedup`; full `pkg/common/collation`
batch incl. the LIKE budget UTs), and mo-tester `genrs` + independent
row review + two normal-comparison `run` passes of
`include=issue_31175_pattern` on one clean instance each pass 431/431
(416 collation + 15 resource-limits). After the root-cause-6 fix,
mo-tester `run` additionally passes
`operator/mysql_compat_string_binary_comparison` (57/57), the six
refreshed files above, `function/func_regular_like`, `optimizer/like`
and `optimizer/like_prefix_range` on the rebuilt binary
(`operator/like_operator` passes 190/190 in CI; one `rpad`+cast INSERT
at row 230 fails only under the local prepared-statement runner, before
and after this change); live probes confirm `vc LIKE BINARY 'a%'` / `vc
LIKE CAST('a%' AS BINARY)` / `BINARY vc LIKE 'a%'` / `vc LIKE BINARY vb`
compare byte-wise while `_binary 'a%'` and plain literals keep folding
case-insensitively.



**Rebase note (2026-11-09).** Rebased onto main `c99234dcf4` to clear
the merge conflict: #32341's `BuildPlan`/`CompilerContext.Resolve`
signature migration overlapped this PR's `n_NAME`→`n_PAME` expectation
update in `pkg/sql/plan/build_show_desc_oracle_test.go` (kept the PR's
case-beyond-letter-case fixture with the new 4-argument call and
`TableResolution` output), and one PR-added `BuildPlan` call in
`pkg/sql/plan/collation_expression_test.go` was migrated to the new
signature. The post-rebase PR diff is byte-identical to the pre-rebase
diff outside those two resolutions. Post-rebase validation on
`bd80b57137`: all five touched Go packages (`pkg/sql/plan`,
`pkg/sql/plan/function`, `pkg/common/collation`, `pkg/sql/plan/rule`,
`pkg/tests/sqlintegration`) compile clean via `mo-cgo-test`; the 26
DESC-oracle/LIKE-prefix/binary-tie tests and the 20 collation-expression
tests (incl. the migrated `TestPatternBinaryColumnCastTieRestored`)
pass; the full `pkg/sql/plan/rule` suite passes.

**Review-resolution note (2026-11-09, head `c8a615913c`).** Resolved the
mo-bot implementation review's P1 on `bd80b57137` (the deduplication
prepass performed quadratic work before the rewrite budgets):
identical-sibling dedup now makes one pass per alternation (65,536
alternatives: 2.19 s -> 4.8 ms in an exact-source probe) and
capture/reference/setter marks fold upward at group close instead of
walking the ancestor stack per construct (32,768 nested captures: 0.94 s
-> 4.7 ms), with eligibility verdicts preserved exactly; a charged 4 MiB
prepass bound abandons dedup byte-identically on exhaustion (the
depth-2000 nested-alternation shape that would hash ~410 MB is capped).
Validation on `c8a615913c`: focused dedup/work-bound/eligibility suites
pass (incl. exact-budget straddle pins and nested flag-propagation
rows), the broad `CaseFold|Dedup|Regexp|RE2` selection passes 135/135
top-level tests (917 runs incl. subtests, 0 failures), gofmt and `go
vet` clean. No BVT result changes: abandonment is unreachable below the
bound (every BVT pattern is orders of magnitude smaller), and dedup
outputs are unchanged for all in-budget patterns.

**Base refresh (2026-11-09, head `07943b3040`).** Rebased onto main
`da867c90df` (6 commits: #32401, #32399, #31419, #32353, #32380, #32251)
under the scheduled ci_base_refresh after run 42566409967's four
failures were verified as the unrelated #27066 tool-download transport
class. Zero file overlap with this PR's diff; no conflict resolutions
needed and the post-rebase PR diff is byte-identical to the pre-rebase
diff. Post-rebase validation on `07943b3040`: `go test -count=1` passes
for all three affected packages — `pkg/common/collation` (17.2s),
`pkg/sql/plan/function` (38.9s), `pkg/sql/plan` (131.1s). No code
change; design r5/r6 record and all review dispositions carry over
unchanged.

**Residual limits** (pinned by tests and documented in the issue): LIKE
stays a per-character weight comparison (no multi-character expansion
spanning; `ß LIKE 'ss'` = 0); three ICU-only regexp corners diverge
(character-class string closure, caseless backreference matching,
quantified-atom image spanning); equality/IN over pure literals under
explicit `utf8mb4_general_ci` keep a pre-existing parity gap that a
follow-up issue owns; `REGEXP_INSTR`/`REGEXP_SUBSTR`/`REGEXP_REPLACE`
keep their default case behavior unless `match_type` requests `i`; PAD
SPACE, sort weights and key uniqueness under ci collations are out of
scope per the issue's acceptance checklist.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
@VioletQwQ-0
VioletQwQ-0 deleted the codex/perf-decimal64-dense-sum-r5 branch December 1, 2026 03:47

This branch was previously deployed

1 inactive deployment
ci — f32fba32 Deployed Nov 11, 2026 by XuPeng-SH
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.

4 participants