Repository navigation
feat(sql): support MEDIAN WITHIN GROUP syntax - #27476
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
# Conflicts: # pkg/sql/parsers/dialect/mysql/mysql_sql.go
|
Addressed the latest default-database P1 in
Validation on exact head
Independent code review: APPROVE. Independent architecture review: CLEAR. @iamlinjunhong @XuPeng-SH please re-review the updated head when convenient. |
|
Resolved the actionable failing check in Root cause of the PROXY BVT failure:
Fix:
Validation:
The prior |
# Conflicts: # test/distributed/cases/pessimistic_transaction/vector/vector_hnsw_async.sql
XuPeng-SH
left a comment
There was a problem hiding this comment.
Reviewed exact head 385d039 against merge base 6ef0c78.
[P1 design gate] Please provide and obtain approval for a stable, versioned design document before continuing implementation review.
This PR is a user-visible SQL feature rather than an ordinary bug fix: it adds a new MEDIAN ... WITHIN GROUP grammar/semantic contract and crosses parser, binder, planner, and public SQL/BVT boundaries. Excluding generated mysql_sql.go and tests, the production change is still about 1,200 lines (including 1,113 new lines in group_binder.go), exceeding the repository review workflow's 500-line feature-design trigger. It also changes a public SQL compatibility contract.
Neither the PR nor #25110 links an approved design revision. The issue states the feature request but leaves the implementation/design section empty; an issue description and implementation comments are not a traceable design approval.
The design needs to define at least:
- the supported SQL-standard surface and explicit scope/non-goals (MEDIAN only vs reusable ordered-set semantics);
- semantic equivalence rules for value/order expressions across query blocks, aliases, CTEs, subqueries, database/name case modes, variables, parameters, and literals;
- planner-state ownership/isolation for validation-only binding and why it cannot mutate CTE/view/node/type state;
- compatibility and error behavior for existing MEDIAN/window syntax;
- planning cost/allocation bounds for nested expressions and the validation matrix at UT and public BVT layers;
- alternatives considered, especially a narrower typed/AST contract versus a 1,100-line specialized canonicalization subsystem.
Per the design-first gate, implementation approval is blocked until the exact design revision and approval are linked. This review intentionally stops before another full implementation-polishing cycle; git diff --check is clean, but that does not close the missing mandatory artifact.
iamlinjunhong
left a comment
There was a problem hiding this comment.
Reviewed exact HEAD 385d039 against current origin/main a53f5a3 and merge-base 6ef0c78. I inspected the complete PR diff, the parser -> canonical validation binder -> MEDIAN aggregate path, the added planner/distributed tests, the delta since my previous review, and all prior reviews, threads, replies, and conversation. The previous default-database P1 has an explicit author reply and is closed, but one current blocker remains.
[P1 correctness] pkg/sql/plan/group_binder.go:634-663 — remove binder-no-op parentheses before formatting the canonical key across every expression node.
The initial qualifyColumnNames pass does not descend into IsTrueExpr, IsFalseExpr, or IsUnknownExpr, while canonicalizeMedianAstValue recursively visits a ParenExpr without replacing it. The real binder does remove ParenExpr before binding the child. Consequently these two sides bind to the same supported signed numeric expression but receive different formatted keys solely because one inner column is parenthesized:
select median(cast((a) is true as signed))
within group (order by cast(a is true as signed))
from select_test.bind_select;
The value key retains cast((resolved-column) is true as signed), the order key contains cast(resolved-column is true as signed), and having_binder.go:387-391 rejects the statement with the MEDIAN match error. Both corresponding ordinary MEDIAN controls follow the same binder expression after the no-op parentheses are stripped. Please normalize no-op parentheses independently of qualifyColumnNames node coverage and add this positive regression, including the two ordinary controls.
Validation: the exact head is unchanged; all 26 GitHub checks are completed (12 SUCCESS, 12 SKIPPED, 2 NEUTRAL), git diff --check is clean, and the current-main merge is textually conflict-free. Local pkg/sql/plan execution cannot start in this sandbox because MatrixOne native CGo prerequisites are absent; the failure above is deterministic from the parser, formatter, qualifier, and binder paths. No P0, P2, or P3 findings.
|
Addressed the latest P1 at
Validation on the updated head:
All local commands passed. Please re-review the updated head and the design revision. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep-reviewed exact HEAD 208002103539bab738c0cd633918eae40e15844e.
The latest parenthesized-predicate blocker is closed, but the mandatory feature-design gate is not.
[P1 design/performance] Finish and approve the design contract before implementation approval.
Trigger: this changes the public SQL compatibility contract and adds about 1.3k non-generated planner LOC. docs/design/median_within_group.md is still marked Proposed, and it does not yet close two decisions that materially determine whether this approach is safe:
-
Normative contract and scope. The document calls
MEDIAN(value) WITHIN GROUP (ORDER BY value)SQL-standard but names no standard/version or interoperable precedent, does not connect this MEDIAN-only spelling to the acceptance criteria of #25110, and does not compare the chosen duplicate-value syntax against credible grammar/binder alternatives. Define the exact user-visible invariant and evidence, then record the reviewed decision. -
Cost and abuse bound. Lines 104-112 claim linear work in the expression AST, but
canonicalizeMedianSubquery,newMedianValidationBuilder, andcloneMedianBindScopebind each cloned scalar subquery separately for both sides and copy the full reachable parent planner/context graph, including existing nodes, bindings, CTE ASTs, expressions, table metadata, and binders. Nested scalar subqueries repeat this operation. Cost therefore depends on the existing parent plan/query-block graph and can become superlinear with nesting; it is not the stated O(n) model. Provide an honest asymptotic/allocation model, an explicit query-complexity or resource bound, and deterministic benchmark/scale evidence. Also evaluate a simpler design that does not duplicate large portions of binder semantics through reflection and deep cloning.
Until those decisions are approved, the 1.2k-line canonicalizer is difficult to judge stable: every new binder precedence or AST-node rule can create another false accept/reject, which is exactly what the preceding review loop has exposed.
[P2 hygiene] git diff --check is not clean on this exact head: the design document has trailing whitespace on lines 3-4 and a blank line at EOF. Please fix this and update the validation claim.
|
Addressed the latest design/performance review at exact head The implementation was redesigned instead of extending the specialized canonicalizer:
Validation on the exact head:
Independent code review: APPROVE. Independent architecture review: CLEAR. @XuPeng-SH @iamlinjunhong please review/approve design revision v2 and re-review the simplified implementation. |
iamlinjunhong
left a comment
There was a problem hiding this comment.
Reviewed exact HEAD a9ee07f001a436b0597c338c9966c7f3233e0cbf against current origin/main 3a3a80185bdbb196c536d9f3af84fdf973069fb8 and merge-base a560c6e3a830c7b06b57265b8977156f2c4c5bef. I inspected the complete 9-file PR diff, parser → tree.FuncExpr → HavingBinder → existing MEDIAN executor closure, affected planner/parser/BVT tests, and all prior reviews, threads, author replies, and conversation. The author explicitly replied to my previous parenthesis-canonicalization P1; current design v2 removes that duplicate-expression canonicalizer and its validation binds entirely, so the prior path is closed.
No P0, P1, P2, or P3 findings remain.
Validation: all 3 current GitHub checks are completed with no failing or pending check; regenerated mysql_sql.go matches mysql_sql.y byte-for-byte after the generated command header; git diff --check and gofmt are clean; and the current-main merge tree is conflict-free. Local targeted Go tests could not start under the required CGo mode because this isolated worktree has no cgo/libmo.dylib; I did not treat that environment failure as test evidence.
|
@XuPeng-SH reviewer comment 已按最终收敛方案处理,请重新 review 当前精确 head 本轮更新:
合并后验证:
两条独立复审分别给出 |
|
已定位并修复本轮 failing checks,更新到 head 根因:
修复:
提交: |
|
已处理最新 failing checks,更新到 head
验证:
提交: |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-reviewed exact head f9bece7c941861d69e42ea06600f5db40108c98a, including design revision v2, the full current diff, the history since my prior request, parser → AST → HavingBinder → existing MEDIAN executor, and the public BVT.
Design revision v2 is approved. The public contract is now explicit and narrow: MEDIAN() WITHIN GROUP (ORDER BY expr) is documented as a MatrixOne extension; the order expression is the sole aggregate input and is bound once. Standards/precedent, compatibility of the never-released v1 spelling, alternatives, cost/resource bounds, validation, and rollback of the rejected canonicalizer design are adequately closed.
The implementation matches that design. The old duplicate-expression canonicalizer, reflection/deep-clone logic, validation-only planner, and all prior column/subquery/CTE state-contamination paths are gone. Ordinary MEDIAN(expr) and its window path stay on the existing branch; ordered-set MEDIAN validates exactly one key, propagates bind errors, applies the existing ENUM/SET numeric contract, and lowers to the existing one-argument executor. Parser, prepared/scalar-subquery, invalid-shape/window, structural no-duplicate-plan, and public result/error oracles cover the changed boundary.
Performance is bounded to one normal expression bind (O(P(n))) with no copied parent planner graph or extra subquery generation. Generated parser evidence is semantically valid for the current grammar; git diff --check passes, and exact-head required CI, UT, SCA, coverage, Proxy BVT, and pessimistic BVT are green. No remaining blocker.
LeftHandCold
left a comment
There was a problem hiding this comment.
Reviewed exact HEAD f9bece7c941861d69e42ea06600f5db40108c98a against current origin/main (424fe3d821e45fe883ab93af5b404d77686d05a0), including the complete 9-file diff, design revision v2, parser → AST → HavingBinder → existing one-argument MEDIAN executor path, tests, CI, prior review history, and all active review threads.
No P0, P1, P2, or P3 findings remain. The current implementation has removed the rejected duplicate-expression canonicalization/validation-planner design. The ordered-set form has one aggregate input, binds it once, preserves ordinary MEDIAN(expr) behavior, rejects unsupported shapes, and adds parser/planner/public BVT coverage.
Validation on this exact HEAD:
- parser regeneration matches the committed
mysql_sql.gooutput; - affected package selection is non-empty;
- CGo-configured build and vet pass for
pkg/sql/parsers/dialect/mysqlandpkg/sql/plan; - full tests pass for both affected packages;
- focused ordered-set/MEDIAN tests pass under
-race -count=3; git diff --checkpasses and the current-main merge tree is conflict-free;- all 26 current GitHub checks are completed with no failures or pending checks.
|
Queued — the merge queue status continues in this comment ↓. |
|
Merge Queue Status
This pull request spent 23 seconds in the queue, with no time running CI. Required conditions to merge
ReasonThe pull request #27476 has been manually updated Requeued — the merge queue status continues in this comment ↓. |
Merge Queue Status
This pull request spent 39 minutes 4 seconds in the queue, with no time running CI. Waiting for
All conditions
ReasonPull request #27476 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.
Failing checks:
HintYou 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. Tick the box to put this pull request back in the merge queue (same as
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #25110
What this PR does / why we need it:
MEDIAN() WITHIN GROUP (ORDER BY value).ORDER BYexpression as the aggregate input and bind it exactly once before lowering to the existing one-argument MEDIAN executor.MEDIAN(value)and its existing window behavior unchanged; reject multiple ordered-set keys and theWITHIN GROUP ... OVERcombination.Design
The exact contract, standards/interoperability evidence, migration decision, cost bound, alternatives, benchmark evidence, and validation matrix are in docs/design/median_within_group.md (revision v2, approval requested).
The v1
MEDIAN(value) WITHIN GROUP (ORDER BY value)spelling existed only on this open PR and was never merged or released. Revision v2 uses the ordered-set model in which the aggregated input is introduced byORDER BY; no semantic comparison of duplicated expressions is needed.Tests
go test ./pkg/sql/parsers/... ./pkg/sql/plan ./pkg/sql/plan/function -count=1-race -count=3go vet ./pkg/sql/parsers/... ./pkg/sql/plan ./pkg/sql/plan/functionBenchmarkBuildMedianForms -benchmem -benchtime=200x -count=3git diff --checkRelated to #25110.