Skip to content

feat: enable cost-based window hash partitioning - #28608

Merged
XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
iamlinjunhong:m1-27943
Oct 14, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
iamlinjunhong:m1-27943

Conversation

@iamlinjunhong

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

What this PR does / why we need it:

feat: enable cost-based window hash partitioning

@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/M Denotes a PR that changes [100,499] lines label Sep 10, 2026

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

Deep review completed at exact head 5da20f6. REQUEST_CHANGES: two confirmed blockers remain.

Confirmed blockers

P1 — Short VARCHAR partition keys can merge distinct SQL partitions.

Locations: pkg/sql/plan/window_partition.go:171, pkg/sql/colexec/partition/hash.go:91, pkg/common/hashmap/inthashmap.go:452.

Counterexample:

CREATE TABLE whp_keys(k1 VARCHAR(2) NOT NULL, k2 VARCHAR(2) NOT NULL, v INT NOT NULL);
INSERT INTO whp_keys SELECT 'a', 'bc', 1 FROM generate_series(1,5000) g;
INSERT INTO whp_keys SELECT 'ab', 'c', 10 FROM generate_series(1,5000) g;
ANALYZE TABLE whp_keys(k1,k2);
SELECT MIN(s), MAX(s) FROM (
  SELECT SUM(v) OVER (PARTITION BY k1,k2) AS s FROM whp_keys
) q;

COST can admit the 4-byte composite key and select IntHashMap. Its variable-length encoding concatenates components without lengths or boundaries, so ('a','bc') and ('ab','c') both encode as abc. They receive one group ID; the expected results are (5000,50000), while the traced HASH path produces (55000,55000).

Fix: use the framed string hashmap whenever any partition component is variable-length, or implement a proven injective bounded encoding. Add composite-boundary tests covering trailing NULs, multibyte strings, and nullable combinations.

P2 — Payload-blind admission can turn executable windows into runtime OOM errors.

Locations: pkg/sql/plan/window_partition.go:233, pkg/sql/colexec/partition/hash.go:217 and :164.

Counterexample state: 65,536 rows, 64 distinct INT partition keys, and a selected 128-byte payload per row, with agg_spill_mem=2097152 and window_partition_algorithm='COST'. The planner estimates about 1.05 MB of hash auxiliary memory and selects HASH, while payload alone requires about 8 MB. Runtime includes retained payload in its threshold, enters fallback during multibatch ingestion, then explicitly returns OOM instead of completing.

Fix: align admission with the complete retained working set and provide a completion-capable fallback. At minimum reject automatic HASH admission when estimated payload exceeds the runtime budget. Add a multibatch wide-payload COST-versus-SORT regression.

Both counterexamples are source-confirmed but were not executed against a live service.

Test evidence / unverified risks

Exact-head CI run 34444199080 passed Ubuntu UT, SCA, coverage, and active BVT; the window_hash_partition.sql artifact recorded 22/22 passed. Compatibility and Darwin jobs were skipped.

Remaining gaps: prepared execution across COST/SORT/HASH changes, binary-protocol reuse, allocation-failure recovery, selected-HASH NULL/duplicate/frame-boundary cases, runtime fallback through Window, same-instance teardown/repetition, mixed-version/upgrade/downgrade/restore, and benchmarks.

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

Mandatory design-gate review of exact head 5da20f6bedf7e9020a63a0f9c3b08046d9b9f7af (base e3959405658a2607b590aef63e648c5c068fa5e4) completed. This change turns a previously hard-disabled blocking window algorithm on by default through a new cost model/session contract, so the approved design and performance-acceptance decision must precede implementation approval.

P1 — docs/design/window_hash_partition.md:3-8,297-341,354-371: the default-enable decision is unapproved and contradicts its own merge gate.

PR #27972 was approved only as a gated implementation. Its final independent approvals explicitly said automatic selection remained hard-disabled and that approval did not cover enabling it without the documented real-Window acceptance matrix. This PR changes that decision while retaining the same window-hash-partition-2026-09-02-r4 revision identifier, and this exact PR currently has no independent design review/approval.

The exact document still says merge requires repeated coverage across 1K/64K/1M rows, NDV/key-width variants, windows with and without ORDER BY, material wins for activating cases, and no material regression for SORT controls. But its supplied numbers are Partition-prerequisite microbenchmarks; lines 322-324 and 334-341 explicitly say they are not end-to-end Window latency evidence and leave real-Window/multi-scope comparisons as follow-up. The issue timeline supplies the same operator-only benchmark. The SQL BVT proves correctness/selection, not the latency, allocation, coordinator peak-memory, or crossover assumptions used to route production queries by default.

Trigger/impact: with COST now the session default, every eligible analyzed window query can enter HASH based on these unvalidated constants. Ordered windows, wide retained payloads, or merged multi-scope input can therefore regress latency or coordinator memory even though the isolated partition step wins; users must discover and manually switch to SORT after impact. This is exactly the rollout risk the prior gated approval deferred.

Please either keep automatic COST selection disabled (leaving HASH as an explicit controlled mode), or provide the design-required repeated exact-head HASH-vs-SORT evidence through a real Window consumer for activating/rejected, ordered/unordered, fallback, and multi-scope cases with peak memory, then record a new exact design revision and obtain traceable independent approval of the default-enable decision. Per the design-first gate, implementation polishing is intentionally not treated as approval evidence on this head.

Exact-head CI is green, but it cannot replace the missing architecture/performance decision and its stated acceptance evidence.

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

Re-reviewed exact head 4f2a5eb against main 315502e, including the earlier REQUEST_CHANGES reviews and subsequent fixes. APPROVE for the current gated scope; this is not approval to enable COST by default or to declare #27943's production performance acceptance complete.

Prior findings:

  • Composite short varlen partition keys now always select StrHashMap. Its length-framed encoding distinguishes ('a','bc') from ('ab','c'); the new regression also checks trailing NULs, multibyte boundaries and nullable combinations.
  • Admission now includes N * Rowsize plus hash/index estimates. Missing/non-finite row size rejects HASH, and the earlier 65,536-row / 128-byte payload / 2 MiB counterexample stays SORT in both COST and explicit HASH controls.
  • The default-enable blocker is resolved by taking the requested rollback option: SORT is the actual session default and resolver fallback. Design revision window-hash-partition-2026-09-10-r6 explicitly gates default enablement and accurately labels the two-batch MockOperator benchmark as component evidence, not production multi-scope/Merge acceptance.

Current-path checks: mode resolution is once per planner traversal; HASH bypasses relative cost only, retaining structural/type/statistics/memory admission. SORT clears stale algorithm/spill selection. Session mode changes clear ordinary cached plans and mark prepared generations for rebuild without deleting handles; the existing execution rebuild path rebuilds the plan and retires cached compilation. The unchanged compiler preserves one coordinator partition owner after Merge, and its v47 capability check restores both local Orders and SORT on older deployments. The change adds no new wire fields or aggregate/frame implementation.

Limits remain explicit: estimates are not a hard completion guarantee. Underestimated retained input can still hit the existing bounded fallback/OOM path in the opt-in mode; no guaranteed spill-to-completion claim is made. Ordering inside complete partitions remains Window's responsibility; incidental inter-partition output order is not a SQL guarantee.

Non-blocking test observations: the public BVT switches back to SORT before its result queries, so its HASH assertions prove plan selection rather than selected-HASH frame semantics. The new CURRENT ROW checksum consumer is likewise weak at detecting incorrect partition membership. Existing operator partition-identity tests and the new framing regression carry that proof here; before default enablement, retain the documented real multi-scope/fallback acceptance gate and add genuinely partition-sensitive public HASH-versus-SORT results.

Validation: full 14-file change and r6 design read, prior findings/deltas and issue discussion inspected, exact-head planner, hash framing/fallback, prepared-rebuild and compile-version consumers traced. The final delta from approved 97d8cb3 is an unused-assignment fix and SQL test-comment corrections. Head/base rechecked before submission. No new native tests, BVT, distributed benchmark or CI wait performed; recorded author measurements were reviewed, not independently reproduced.

@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 14 changed files and design revision window-hash-partition-2026-09-10-r6 at exact head 4f2a5eb, base 315502e. No confirmed blocker for the current opt-in scope.

SORT remains both session default and resolver fallback. COST/HASH retain structural, type, statistics and retained-payload memory admission; HASH bypasses only relative cost. Variable-length keys select framed StrHashMap encoding, preserving composite partition identity. Session mode changes clear cached plans and mark prepared generations for rebuilding without deleting handles. The existing compiler still merges upstream scopes before one partition owner and restores local sorts plus SORT below v47.

Reused green exact-head CI and the existing independent r6 review/recorded component benchmark evidence; no new local native tests or benchmark run. The unchanged bounded fallback/OOM contract is not a spill-to-completion guarantee.

Nonblocking follow-up before default enablement: the public BVT restores SORT before checking window results, and CURRENT ROW checksums are weak partition-membership oracles. Add partition-sensitive public HASH-versus-SORT results and the documented real multi-scope/Merge acceptance evidence before enabling COST by default. This approval does not claim those deferred production-performance gates are complete.

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

Deep re-review of exact head af729ee0652576f7ae66ad64e42b69e065418700 against base/merge-base dce60631f8c857ae730a4d2f328df5962e4f2a8d. APPROVE for the current gated, session opt-in scope. My earlier default-enable finding is closed by keeping SORT as the default; this approval does not authorize enabling COST by default or claim completion of #27943's production performance acceptance.

I read all six historical reviews, the PR/issue discussions and the one unresolved, now-outdated inline thread; there are no author replies in that thread. I reviewed the r6 design first, then the full 13-file diff and the rebased increment. Range-diff separates the five corresponding earlier commits from the two new test commits. The design's gated decision is consistent with the independent r6 approvals; updated component benchmark numbers do not change its rollout contract.

Prior findings and current closures

  • Default enablement / misleading multi-scope proof: SORT is both the session default and resolver fallback. COST/HASH are explicit session controls. The two-batch MockOperator benchmark is now accurately documented as component evidence, not production multi-scope/Merge acceptance. Real topology/fallback performance acceptance remains required before default enablement.
  • Composite varlen partition identity: actual hash preparation uses HasVariableLengthKey to select framed string hashing. The short-VARCHAR boundary regression passes for ('a','bc') versus ('ab','c'), trailing NULs, multibyte boundaries and nullable components.
  • Payload-blind admission: retained N * Rowsize is included with hash/index estimates; unknown/non-finite row size fails closed. The old 65,536-row / 128-byte payload / 2 MiB scenario remains SORT in both COST and explicit HASH.
  • Prepared/cache generations: a changed converted mode clears ordinary cached plans and marks prepared plans stale while retaining handles. The existing EXECUTE consumer rebuilds plans and retires stale cached compilation. A temporary direct-consumer probe passed through both SQL/Binary EXECUTE setup, switching COST → HASH → SORT and checking actual generation replacement and handle survival; same-mode SORT does not invalidate. This is frontend fixture execution, not a live wire-protocol test.
  • Public HASH results: the BVT now executes, rather than only explains, COST/HASH-selected windows. HASH runs partition-sensitive aggregate, rank, first_value, ROWS and RANGE oracles before restoring SORT controls. I independently checked the expected sums: 10001000000, 1005000, 255000 and 99511225.
  • Topology/compatibility: compile still merges before one coordinator partition owner. Typed topology, duplication and v47/v46 gate tests pass; the older-protocol fallback restores local Orders plus SORT. No new wire/disk format or index-plugin dispatch is introduced.

Scoped ownership, termination and bounds

Q Closure traced Outcome
Q1 retained inputs/key executors/hash/index/output views → Partition Reset/Free; invalid prepared generation → EXECUTE rebuild and old compile Free/Release Cleanup/reuse/cancel tests pass; no new demonstrated leak or double cleanup.
Q2 per-session cache invalidation under its existing mutex; synchronous marking; hash receive/finalization cancellation; existing compiler merge owner No new asynchronous wait/protocol is added. Focused cancellation and topology tests pass.
Q3 finite row/NDV/width/retained-memory admission → bounded pre-output fallback; cache generation replacement rather than additional retained histories No new unbounded-growth finding. Stale estimates can still reach the documented fallback/OOM behavior; opt-in HASH is not a spill-to-completion guarantee.

Applicable risk is configuration/planner/result/generation/resource and hot-path selection. Persistence/security/GPU/new background-protocol work is not introduced by this range. The expensive multi-scope performance dimension remains explicitly gated rather than falsely certified by this approval.

Evidence and limits

  • Fresh head and clean-baseline native builds completed with make -j2 cgo; repository CGo wrapper used. Linux/amd64, repository-selected Go 1.27.0, CPU release/SIMSIMD=0; Sonic reports its encoding/json fallback.
  • Focused normal tests passed in frontend, planner, partition, window and compile, covering every changed test root and the relevant consumer/gate paths. Full partition package passed.
  • TestSessionWindowPartitionAlgorithmChangeInvalidatesPreparedPlanGeneration: race measurement reported elapsed below resolution; adaptive -race -count=100 passed. The temporary real prepared-rebuild consumer probe also passed under race.
  • Supplementary full Window package is not green locally: four existing tests fail with execution resource admission rejected: requested=8 used=0 cap=1. I reran the exact four-test command at this head and in a separate worktree at the verified clean base, with independently built matching native inputs. Both exit 1 with identical failures in TestWindowOrderSpillsAndKeepsArgumentsAligned, TestWindowOrderSpillReleasesConsumedMaterializedInput, TestWindowOrderSpillPreservesAggregateArguments and TestWindowPartitionTopNSeparatesGroupingNullFromEmptyString. Their sources and execution owner are unchanged by this PR. This is confirmed baseline failure evidence, not a new PR finding; it is not hidden as a package pass.
  • Exact-head CI run 37732492921 passes required CI, UT, SCA and enabled BVT. I checked actual planner shard completion (8/8, status 0), not only the check name.
  • Downloaded BVT execution logs verify the exact window case in the pessimistic multi-CN job: 30/30 success, 0 ignored/failed/abnormal, normal comparison, 0.528s. A multi-CN test environment is not proof that this TP query used remote source scopes; real multi-scope performance acceptance remains deferred.
  • Changed-Go gofmt and range diff-check pass. No new local full SQL deployment, distributed benchmark, same-instance BVT repeat, upgrade or GPU execution is claimed.

The temporary probe and detached head/baseline worktrees will be cleaned after verified submission. No production changes were made.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 04:10 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 05:32 UTC · at c29092933fa536fdf365b693376f58015de193bb

This pull request spent 1 hour 21 minutes 57 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated

This pull request seems to come 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, or update the branch manually.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, 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 was successfully deployed

No deployments
ci — c2909293 Deployed Oct 14, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants