Skip to content

perf(plan): remove constant sort after singleton grouping - #27889

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/27858-constant-order-having
Aug 31, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/27858-constant-order-having

Conversation

@XuPeng-SH

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

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:

Refs #27858

Depends on #27850. The non-primary unique-key and ordered-access extensions
remain separate work in #27856 and #27857, so this PR does not auto-close the
umbrella issue.

What this PR does / why we need it:

The complete-primary-key grouping rewrite proves one input row per group, so
COUNT(*) is the constant 1. Queries such as
GROUP BY pk ORDER BY COUNT(*) LIMIT K nevertheless retained a blocking Sort,
which prevented the existing bounded-demand pushdown from reaching TableScan.

This change removes that Sort only when:

  • every ORDER BY key resolves and safely folds to a scalar literal;
  • at least one key traces through unary Projects to an Aggregate converted by
    the current singleton-group rewrite pass;
  • LIMIT/OFFSET pagination composes safely; and
  • rank/tie behavior and SQL_CALC_FOUND_ROWS are absent.

The provenance requirement keeps this from becoming a global constant-order
rewrite. Dynamic parameters, volatile/erroring expressions, row-dependent tie
breakers, nullable COUNT, rank options, FOUND_ROWS, malformed shapes, and unsafe
pagination all retain Sort.

Counterexample review also found that a standalone INTERVAL could panic both
constant-folding paths and later crash sort/group/window execution. The fix
separates the two required contracts:

  • both constant-folding entry points are total and retain an unmaterializable
    standalone interval instead of panicking;
  • public SELECT, GROUP BY, top-level/grouping-set ORDER BY, and window
    PARTITION/ORDER boundaries reject a bare interval with error 20105; and
  • temporal consumers such as date_add(..., INTERVAL ...) and interval window
    frames remain valid.

Validation:

  • rebased cleanly onto matrixorigin/main at 89740fae15;
  • focused activation, fail-closed, prepared-pagination, typed interval, and
    public scalar-boundary tests;
  • complete pkg/sql/plan and pkg/sql/plan/rule tests through the repository
    CGo harness after the final rebase;
  • post-rebase go vet ./pkg/sql/plan ./pkg/sql/plan/rule and make build;
  • post-rebase 28-statement distributed SQL case passes with metadata comparison;
  • live interval probes cover all five public escape boundaries, the original
    PR counterexample, valid temporal consumption, and a temporal RANGE frame;
  • 55-host NVMe validation on 10M rows changes full TableScan + Sort to a bounded
    TableScan and improves 100 fresh-client executions from 3.00s to 0.90s;
  • exact feature A/B before the unrelated main rebase: 10M-row medians are
    23.359ms base versus 8.668ms current (2.70x); 50M-row medians are 166.745ms
    versus 8.853ms (18.83x). Base reads all rows, while current reads one
    8,192-row block; and
  • retained-Sort controls show no regression: mixed row-key 27.895ms base versus
    27.433ms current, nullable COUNT 52.181ms versus 52.523ms.

The proof, alternatives, semantic barriers, rollback boundary, and complete
validation evidence are documented in
docs/design/singleton_group_constant_order_elimination.md.

@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 Aug 31, 2026
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Aug 31, 2026
@XuPeng-SH
XuPeng-SH force-pushed the codex/27858-constant-order-having branch from 71e9137 to ed26383 Compare August 31, 2026 06:52

@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 review completed at exact head ed26383e96c754ecf8591deed6b29003da365362. I reviewed the design, full diff, and current review history, and validated the exact head in an isolated worktree. The constant-order sort-removal proof, provenance guard, and pagination barriers look sound, but the interval panic-closure path is not complete, so I am requesting changes. Validation: make thirdparties, make cgo, go test ./pkg/sql/plan ./pkg/sql/plan/rule -count=1, go vet ./pkg/sql/plan ./pkg/sql/plan/rule, plus review-only counterexample tests (removed afterward).

Comment thread pkg/sql/plan/query_builder.go Outdated
}

func rejectStandaloneIntervalExpr(ctx context.Context, expr *plan.Expr, clause string) error {
if expr != nil && expr.Typ.Id == int32(types.T_interval) {

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.

[P1] This guard checks only the outer expression type, so nested generic scalar/aggregate consumers still let the internal INTERVAL Expr_List escape. At this exact head, both SELECT INTERVAL 1 DAY IS NULL; and SELECT COUNT(INTERVAL 1 DAY) FROM select_test.bind_select; build successfully, and their plans retain a raw T_interval list under isnull / count. A review-only executor test evaluating that same list produced a BIGINT vector of length 2 with values [1 2036425731] (the bytes of day were interpreted as an integer), rather than one scalar value. That means a public executable plan can silently corrupt row/aggregate semantics instead of returning the intended not-supported error. Please reject unconsumed interval pseudo-expressions recursively at every generic scalar/aggregate boundary, while continuing to allow only explicit temporal/window consumers, and add public tests for both IS NULL and COUNT cases.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Confirmed. The new guards validate only the outer expression type, so wrapping the retained T_interval pseudo-expression in a generic scalar or aggregate hides it from every added boundary check. Since this PR intentionally changes constant folding from panic to retention, letting that internal list reach execution is a real wrong-result path, not merely a diagnostic gap. Please make the validation recursive and consumer-aware (only the explicit temporal/window consumers may consume an interval), and keep the IS NULL and COUNT counterexamples as public regressions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed at 87cf1d4d42091c4bc1010d0f203048618dc96364. Unconsumed T_interval is now rejected recursively at generic scalar/aggregate boundaries; the explicit temporal/window consumer set must rewrite it before function publication. The same invariant now covers predicate roots and IN/NOT IN/ANY subquery paths before their internal Expr_List can be mistaken for row arity. Added public IS NULL and COUNT(INTERVAL ...) BVT regressions, nested tuple/direct-plan/predicate/subquery unit counterexamples, and valid-consumer controls. Rebased on current main; full plan/rule tests, CGo-configured vet, build, isolated 31/31 BVT twice, and live 20105 probes pass.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Fixed the PROXY BVT compatibility regression at head 13ea58e.

Root cause: the interval no-escape guard ran before builtin overload resolution, replacing established ErrInvalidArg diagnostics for known functions with a generic standalone-INTERVAL error. The fix now:

  • lets known builtins resolve first and preserves their resolver error;
  • rejects a successfully bound expression if raw INTERVAL remains;
  • rejects unknown-function INTERVAL arguments before UDF fallback.

Regression coverage includes all four failed CI statements (uuid_v4 and the three greatest variants), plus ISNULL, COUNT, nested interval, valid temporal consumers, unsupported arithmetic, and unknown/UDF fallback.

Post-rebase validation on upstream/main 3f05ced:

  • pkg/sql/plan, pkg/sql/plan/rule, pkg/sql/plan/explain: pass
  • focused interval matrix, count=10: pass
  • CGo-configured go vet for the same packages: pass
  • make build: pass

The branch was rebased and pushed with force-with-lease. I did not wait for CI.

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

kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/enhancement kind/test-ci 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