Skip to content

perf(shuffle): balance complete string-key ownership - #27744

Merged
XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-27728-group-shuffle
Aug 27, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-27728-group-shuffle

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

What changed

This PR fixes the string-shuffle ownership half of #27728.

  • Replace the legacy sampled CHAR/VARCHAR/TEXT owner hash with a portable, allocation-free complete-key mapping at MORPC v33; senders at v32 or earlier retain the exact legacy mapping.
  • Select the mapping once when an execution is admitted, freeze it on Process, copy it to every child/reused scope, and carry it to remote CNs in ProcessInfo.
  • Add a string-hash-specific pipeline capability marker. A pre-v33 CN rejects the unknown marker before executing the pipeline; a new CN validates that the marker and ProcessInfo select the same mapping. Mixed rollout/rollback can therefore fail loudly, but cannot silently split equal keys across owners.
  • Keep data-only retries on the original execution mapping. A prepared statement's next Reset starts a new execution generation and selects again from the rollout gate.
  • Route constant, null/non-null, expression, and ordinary row paths through one string-owner helper.
  • Scope the rollout marker to CHAR/VARCHAR/TEXT Hash Shuffle only. Numeric Hash Shuffle and Range Shuffle do not acquire an unnecessary old-CN rejection boundary.
  • Stabilize the embedded-cluster UT fixture under -race: test-mode heartbeat RPCs use a 15s budget inside the existing 60s store-liveness window. Product defaults are unchanged, explicit test overrides are preserved, and retry opportunities remain bounded.

The implementation is generic: there are no query-text, schema-name, URL-shape, data-size, benchmark, or issue-number branches.

Correctness and rollout contract

Sender / receiver Behavior
legacy / legacy sampled mapping
legacy / new absent metadata defaults to sampled mapping
v33 / new complete mapping frozen for the execution
v33 / pre-v33 receiver rejects the new string-hash opcode before execution
mismatched new metadata/opcode receiver returns InvalidState before operator execution

Equal logical keys therefore have one owner for both GROUP and shuffle-join paths. Empty, short, UTF-8, binary-content text, const vectors, and nulls are covered. Unknown algorithm values fail during Process decoding rather than falling back.

Numeric ownership, Range Shuffle, non-shuffle plans, and IVF-FLAT ownership are unchanged. The IVF path continues to use its existing full ObjectID xxhash mapping.

Validation

Validated after merging current main:

  • full tests: pkg/container/hashtable, pkg/pb/pipeline, pkg/sql/plan, pkg/sql/colexec/shuffle, pkg/vm/process, pkg/vm, pkg/sql/compile, and pkg/embed;
  • focused -race -count=10: complete/legacy hashing, mixed service-runtime admission, ProcessInfo codec, child/reuse generations, retry/prepared reset, string/numeric/range wire markers, marker/metadata mismatch rejection, and operator duplication;
  • full pkg/tests/issues -race with GOMAXPROCS=8, covering the catalog/restore/authenticated shared-cluster combination that failed the previous UT job;
  • protobuf regeneration is deterministic (identical SHA-256 on consecutive generations);
  • no sleeps, timing assertions, large generated UT fixtures, or production timeout changes.

Exact statement coverage is non-decreasing for every affected package, including generated wire-code branches:

package base candidate
hashtable 60.8205% (593/975) 63.2278% (619/979)
pb/pipeline 4.6725% (1013/21680) 5.1173% (1112/21730)
colexec/shuffle 77.6213% (992/1278) 78.5266% (1002/1276)
sql/plan 78.6420% (40989/52121) 78.6471% (40994/52124)
vm/process 77.4727% (2060/2659) 77.5663% (2078/2679)
vm 85.0000% (85/100) 85.0000% (85/100)
sql/compile 60.7669% (12456/20498) 60.8778% (12511/20551)
embed 84.4237% (813/963) 84.4560% (815/965)

Performance boundary

The complete-key implementation allocates zero bytes per operation. It is linear in total key bytes by design; an adaptive sampled fallback would recreate data-dependent skew cliffs. Local microbenchmarks measure about 35-36 GB/s for 64 KiB and 1 MiB keys. Ordinary 8-32 byte keys are at least as fast as the legacy helper; 64-byte keys are about 10% slower in the isolated hash loop.

On host 10.222.1.55, using the existing 10,000,000-row / 10,000,000-NDV URL data on NVMe with 16-way execution, twelve interleaved legacy/complete pairs measured:

ownership median wall time owner rows min/max max owner memory max group shard
legacy sampled key 0.514s 363,803 / 1,013,198 137.53 MiB 454ms
complete key 0.544s 623,575 / 626,598 109.58 MiB 388ms
  • owner max/min improves from 2.785x to 1.005x;
  • maximum per-owner memory falls about 20.3%;
  • the slowest group shard falls about 14.5%;
  • aggregate operator timeConsumed falls from 8,973ms to 7,350ms;
  • neither refreshed-plan control spills and result rows are identical;
  • end-to-end wall time is about 5.8% higher in this already non-spilling case because complete hashing reads every key byte.

Hash reuse across operators is tracked separately in #27753. Stale post-ANALYZE plan visibility is also independent of this PR.

Part of #27728
Related: #27685, #27753

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

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Aug 27, 2026
@XuPeng-SH
XuPeng-SH marked this pull request as draft August 27, 2026 07:39
@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-27728-group-shuffle branch from 47fcdfe to ab35c60 Compare August 27, 2026 08:38
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Aug 27, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

@gouhongshen The requested changes are addressed in head c692ab66ae.

P0 closure:

  • The coordinator now selects the string-owner algorithm once before physical compilation. The immutable value lives on Process, is copied to every child/reused scope, is inherited by data/definition retries, and is serialized in ProcessInfo for remote CNs. Shuffle.Prepare no longer reads service-local MOProtocolVersion.
  • Prepared Reset deliberately starts the next execution generation and selects again; already-created processes retain the prior generation.
  • String-key Hash Shuffle carries an appended ShuffleStable wire opcode plus Shuffle.string_hash_key. On a pre-v33 receiver, that opcode has the old OpTypeEnd value and reaches the existing unexpected operator default before operator execution. A new receiver validates the opcode against the ProcessInfo algorithm and returns InvalidState on either mismatch. This is an in-band check, so there is no capability-preflight TOCTOU window.
  • The marker is type-scoped: CHAR/VARCHAR/TEXT Hash Shuffle uses it; numeric Hash and Range Shuffle keep their existing wire opcode and behavior.
  • Mixed local runtime values after admission no longer affect a running execution. If the participant is a genuinely old binary, the query fails loudly rather than returning split GROUP rows or dropped join matches.

P2 closure:

  • Const, null/non-null, expression, and ordinary row routes now share stringHashToRange; there is one owner-contract definition.

Regression matrix added for legacy/new round trips, mixed service runtimes, old-field defaults, unknown algorithm values, child/reuse generations, prepared reset, retry inheritance, string/numeric/range markers, both mismatch directions, illegal stable-range metadata, operator duplication, GROUP/join construction type classification, and deterministic equal-key counterexamples.

The prior UT failure was separate: under -race, the catalog/restore/authenticated shared cluster could exceed the implicit heartbeat RPC budget and close the HAKeeper transport. Test mode now uses a bounded 15s heartbeat deadline inside the unchanged 60s store-liveness window; product defaults are untouched and explicit overrides remain effective. After merging current main, full pkg/tests/issues -race with GOMAXPROCS=8 passes in 124.448s.

Coverage is non-decreasing for every affected package. The new protobuf wire branches were explicitly checked too: pkg/pb/pipeline rises from 4.6725% (1013/21680) to 5.1173% (1112/21730). Full validation details and the complete matrix are in the updated PR body.

Please re-review the new head.

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

Re-reviewed exact head c692ab6. I read the complete review/comment history and author closure response, audited the full base diff and the increment from the previously reviewed 26c0c91 head. The prior split-brain blocker is closed: the coordinator freezes one mapping generation, child/reused/retry/remote processes inherit it, pre-v33 receivers reject the appended string-hash opcode, and new receivers validate opcode/ProcessInfo agreement before execution. The duplicated row/constant implementation is also unified. I checked complete-key hashing, string type classification, constant/null/expression/vector paths, prepared reset and retry lifecycles, mixed rollout/rollback behavior, numeric/range/IVF boundaries, generated wire fields, and the test-only heartbeat adjustment; no blocking issue remains. Full owning-package tests passed on this exact worktree, as did focused race repetitions across hashtable, pipeline codec, process propagation, shuffle, plan, and compile; diff check is clean.

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

Codex automated review

All prior blockers remain fixed at the new head, and the incremental delta is a verified safe narrowing of the rollout guard. No blocking or non-blocking findings.

Prior blocker dispositions (revalidated at c692ab6):

  1. My P0 (per-CN protocol gate allowed one distributed query to hash the same string key to different owners across CNs, silent wrong results) stays FIXED by the freeze mechanism: the owner algorithm is decided once per execution at admission, frozen on Process, propagated to every child/reused/retry process and to remote CNs via ProcessInfo field 16 (strict decode validation), and the ShuffleStable wire opcode makes pre-v33 receivers fail before execution while new receivers cross-check marker vs carried algorithm. All of this is intact at the new head.
  2. My P2 (two spellings of the owner mapping) stays FIXED: all string-hash call sites route through the single stringHashToRange/appendStringHashSels helpers.
    XuPeng-SH's review raised the same P0-class issue and remains addressed by the same mechanism; not re-raised.

New delta review (9895280..c692ab6):

  • Merge 135ef97 is a clean merge of upstream #27493 with zero conflict-resolution delta (verified via remerge-diff); those frontend/plan changes are not authored by this PR.
  • ed25d52 scopes the ShuffleStable marker to string-key hash shuffles only, via a new Shuffle.StringHashKey flag set from the actual key type in both constructors, copied in dupOperatorWithContext, and carried on the wire as Shuffle.string_hash_key field 11. I verified completeness: all four shuffle construction sites handle the flag; the runtime string-hash path is reachable only for char/varchar/text, exactly matching isStringShuffleKeyType; the planner enables hash shuffle only for plain columns (group) and column/serial_full/serial keys (join), and serial/serial_full are typed varchar so expression-based string shuffles are marked too. Numeric hash shuffles and range shuffles correctly carry no marker, and their routing is algorithm-independent on both sides. Net effect: integer-key shuffles keep working on pre-v33 CNs during a mixed window while string-key shuffles still fail loudly — a strict narrowing of the failure surface with no new correctness gap.
  • c692ab6 adds pb-level wire round-trip contract tests for both new fields.

Validation at the new head: pkg/pb/pipeline, pkg/sql/colexec/shuffle, pkg/vm/process pass; pkg/sql/compile passes except the three parquet extern-scan fanout tests already proven pre-existing by identical failures at the clean merge base; the new tests (construction type matrix incl. binary->false, wire contract incl. numeric-hash no-marker case, dup propagation, mixed-runtime admission) pass explicitly; go vet clean on all touched packages.

@mergify

mergify Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

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

  • Queue this pull request

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

size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants