Skip to content

fix(plan): preserve DISTINCT statistics and reuse aggregate partitions - #31250

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/clickbench-distinct-ownership-20261026
Oct 26, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/clickbench-distinct-ownership-20261026

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 26, 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:

Related to #27665. This does not close the ClickBench tracker or its Q14 performance gap.

What this PR does / why we need it:

DISTINCT rewriting copies group cardinalities into new column bindings without registering their statistics provenance. Recalculation consequently estimates one output group even when the source estimate is large. Preserve estimates through the existing trusted-binding mechanism for scalar and tuple rewrites.

When consecutive aggregates retain the same complete partition key, reuse the existing owner before applying the cost thresholds for a new exchange. When their keys differ, retain local reduction and MergeGroup: redistributing unreduced rows based only on marginal NDV regressed a dominant composite-group control. Replanning clears stale shuffle decisions and proves lineage in the current column-reference mode. The compiler preserves the complete child aggregation when the parent reuses its partition; local-only preaggregation is allowed only when a normal parent establishes its own exchange. This prevents nested DISTINCT from returning duplicate keys across workers. Existing join distribution, aggregate execution, spill and wire formats are unchanged.

Validation on macOS arm64:

  • Full planner tests; full compiler tests (1,579 top-level / 3,964 cases); focused planner and compiler race (compiler: 24 top-level / 73 cases); incremental plan/compiler vet, molint and golangci-lint (zero issues).
  • Nested DISTINCT regression: 32,768 persisted rows with NULL, 0, 1 returned 12 rows before the compiler correction and exactly 3 afterward. The verified local four-worker SQL regression passes all 19 statements, including empty results and repeated prepared execution. Actual compiler-entry tests retain the child exchange and complete Groups in one-/two-CN bucket layouts without another exchange or MergeGroup.
  • Public SQL at one and four workers: COUNT/SUM/AVG DISTINCT, NULL/empty input, multiple keys, CHAR padding, prepared reuse, INSERT...SELECT and forced spill. A separate 3M-row Unicode-collation fixture verifies hash-owner reuse and exact results.
  • Matched four-worker resident measurements: a 10M-row query grouping k_clustered=id DIV 10 with COUNT(DISTINCT id%8) improves from 0.412s to 0.329s (~20%). Uniform, dominant and correlated composite controls show no repeatable regression; one-worker controls remain neutral. The retained patch leaves 30M ClickBench Q14 at 1.066s. More aggressive final-key repartitioning was rejected after measured regressions and is absent here.
  • Rebased onto 83c1e23526fc; service build and full planner tests pass. The measured production delta is byte-identical across the rebase (the added main changes concern views/Python DML). The original head passed required CI including UT, SCA, coverage and both multi-CN BVT jobs. CI for the compiler correction is pending; local SQL validation used one CN.

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

Copy link
Copy Markdown
Contributor Author

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

Commit: 16c8b830c641e5b1a97c5a7d33b3af57df16872f

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

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

Commit: 16c8b830c641e5b1a97c5a7d33b3af57df16872f

Assessment: request_changes

Reviewed the complete seven-file delta and affected planner/compiler paths. Reusing existing statistics provenance is appropriate and adds bounded planning work, but aggregate partition reuse introduces a confirmed wrong-result regression.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P1 pkg/sql/plan/shuffle.go:1465: Plan SELECT DISTINCT k FROM (SELECT DISTINCT k FROM t) q when the inner aggregate selects shuffle and duplicate keys occur on separate source workers.
    Impact: The outer DISTINCT can return duplicate rows. Preserve the child's complete aggregation when reusing its partition, or retain a completing exchange, and add a compiler-level regression covering duplicates across workers.
    Evidence: The new branch marks the parent ShuffleMethod_Reuse, but compile.go:2015 also selects isLocalPreAggregationGroup. That shortcut bypasses the child's complete shuffle aggregation and installs only local deduplication. compileShuffleGroup at compile.go:9224 then adds final Groups without an exchange or MergeGroup. A real BuildPlan plus actual compiler helpers and Group execution returned four copies of key 7 instead of one. compiler-repro.log and checks/1792999442610183132-4.json record the failure. The base-production control does not enter this unsafe combination.

Validation:

  • Artifacts are retained under /home/xupeng/.local/state/mo-bot/jobs/4db0edc5b36f00dd06d9dec8/attempt-1. review-audit.json reconciles commands, source fingerprints, exits, logs and diagnostic overlays; audit receipt 1792999969825398127-3.json passed.

  • Confirmed frozen HEAD, matching patch and unchanged source. Private /tmp and loopback preflight passed. Built native prerequisites through the repository build owner and verified 194 input files and 46 artifact hashes.

  • Full unmodified planner package passed: 4,226 top-level tests, with two existing skipped subtests. See planner-package.log and receipt 1792999569855699775-3.json.

  • All 27 selected compiler controls passed. See compiler-controls.log and receipt 1792999807892040143-3.json.

  • Candidate reproduction failed with expected 1 row versus actual 4. Base-production control passed using the two base planner files with an unused signature adapter; it verifies absence of the unsafe plan combination, not full baseline SQL execution.

Limitations:

  • The reproduction uses real planner/compiler/operator code with mock scan inputs; a full SQL server and live distributed cluster were not run.

  • Frozen product CI checks were still in progress. local_validation was empty; author-reported SQL, race, lint and performance results lacked retained execution artifacts.

  • The reported 0.412s-to-0.329s improvement was not independently measured. The change adds no new runtime state or wire format, and claims no Q14 speedup. Linked issue #27665's body was not supplied.

@XuPeng-SH

XuPeng-SH commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 5f62167e389cbf43a14a9dcfee78d5740d75c8cc

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

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

Commit: 5f62167e389cbf43a14a9dcfee78d5740d75c8cc

Assessment: approve

Reviewed all 11 changed files and surrounding planner/compiler owners. The prior nested-DISTINCT wrong-result finding is resolved. The design preserves trusted cardinality provenance and permits partition reuse only through compatible keys, while the shared compiler predicate preserves complete child aggregation. Incompatible keys retain local reduction and MergeGroup. Added planning work is bounded per key; existing execution and cleanup mechanisms remain authoritative. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Preflight passed. Recovered repository-built native libraries after verifying 194 matching inputs and 46 artifact hashes; retained provenance and build logs.

  • Full planner and compiler suites passed with -count=1: 4,230 planner tests plus 15,910 subtests; 1,582 compiler tests plus 2,388 subtests. Two unrelated existing planner subtests skipped. Receipt: checks/1793007555055461798-4.json; output: owning-packages.jsonl.

  • Executed all 19 new BVT SQL statements twice through the real frontend on one CN, using 32,768 persisted rows. Verified four scan workers, nested DISTINCT results NULL/0/1, empty input, repeated prepared execution, restored session settings and database cleanup. Receipt: checks/1793007825559235183-6.json; output: public-sql.jsonl.

  • Repeated the SQL validation on two CNs with remote placement explicitly asserted. COUNT/SUM/AVG DISTINCT, tuple DISTINCT and grouped controls also passed with max_dop=1 and 4. Receipt: checks/1793007967071046116-5.json; output: public-multicn.jsonl.

  • Reconciled commands, exit statuses, frozen-head fingerprints, selected tests and retained artifact hashes. Source remained unchanged. Audit: /home/xupeng/.local/state/mo-bot/jobs/871db71d3eb790a340877944/attempt-1/review-evidence-audit.json; final receipt: checks/1793008149235558677-3.json.

Limitations:

  • SQL validation used diagnostic test-only overlays and independent result assertions, not mo-tester's result-rendering comparison.

  • Author benchmark claims lack retained raw evidence and are not certified. Expected benefits are accurate estimates and reuse of existing partition ownership; no Q14 speedup or general regression-free performance claim is made.

  • Frozen CI was still in progress. No additional race or forced-spill campaign was run; this change introduces no new concurrent state or spill implementation.

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/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants