Skip to content

perf(plan): parallelize non-null tuple count distinct - #30998

Merged
XuPeng-SH merged 5 commits into
mainfrom
codex/perf-30995-tuple-distinct
Oct 24, 2026
Merged

XuPeng-SH merged 5 commits into
mainfrom
codex/perf-30995-tuple-distinct

Conversation

@XuPeng-SH

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

Fixes #30995.

What this PR does / why we need it:

Multiargument COUNT DISTINCT retains exact argument sets and merges them serially, making a one-million-row tuple query much slower than its unary equivalent. Extend the existing planner-owned pair-Group path to supported tuples whose arguments are all proven non-NULL at aggregate input. Local reduction and a canonical high-NDV component exchange feed complete-tuple deduplication, followed by ordinary COUNT. Every tuple component remains part of equality, including those not selected for exchange.

Reuse existing Group, shuffle, spill and count execution. Normalize CHAR/PAD SPACE before exchange and preserve physical grouping keys. Nullable/unproven inputs, outer-join NULL extension, low/unknown NDV, unsupported types/expressions, grouping sets and mixed aggregates retain their existing path. Unary optimization and shared costing are unchanged. See design.

A separate test-only commit fixes TestReadBarrierResponseFollowsEarlierLogtailUpdate: response receipt can precede deferred admission release. Bounded reacquisition of the sole slot synchronizes with actual release while retaining leak detection and response-order assertions.

Rebased onto main 94faf02. The compile test conflict retains main's real physical-selection assertions and adds grouped/global tuple cases. Production tuple/logtail content is unchanged.

Retained validation evidence requested by review 5633797167: index and acceptance matrix, source/build identity, public execution receipt, raw timing samples, timing receipt. The bundle includes exact commands, archived diagnostics/configs, binary hashes, terminal logs, physical/analyze plans and SHA256SUMS.

Fresh local validation on the rebased source, darwin/arm64, Go 1.27.1 with matching native inputs:

  • Planner/logtail service owning-package UT, related real-SQL compile tests and affected plan/compile/logtail race tests passed.
  • Derived 345-package incremental vet, molint and golangci-lint all exited 0; golangci reported 0 issues. Retained molint diagnostics are not claimed raw-zero.
  • Exact SQL at DOP 1/8: complete tuple axes, CHAR/Unicode, NULL/empty/outer joins, two CNs, four prepared executions, actual nonzero SpillRows, concurrent cancellation 1317, surviving 5M-row query, connection reuse and zero newly remaining spill files passed.
  • Controlled clean-main/candidate ABBA, 20 warm samples/version/control: tuple 458.803 → 36.698 ms (12.50x), reversed tuple 12.15x, duplicates 17.13x, CHAR 8.61x. Unary +5.06%, mixed +0.55%, low-NDV −0.54%, all-invalid −11.59%. Exact results checked on every invocation; all eight cases retained.
  • Public correctness and final timing have separate documented fixture IDs. An initial timing startup failed before any sample after the older temporary store no longer contained the database; its failure is retained and no samples are mixed. Final timings use one freshly bootstrapped task-owned persisted fixture for every phase.
  • gpt-6.1-sol/xhigh design and final overall review: PASS, zero unresolved material findings or proof gaps.

Nullable tuple acceleration and general mixed/multiple aggregate acceleration remain outside this bounded optimization. GitHub CI for the new head is pending.

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

Copy link
Copy Markdown
Contributor Author

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

Commit: 007b27c1cd53a6e90adf41ce4d34ab08aea45621

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: 007b27c1cd53a6e90adf41ce4d34ab08aea45621

Assessment: request_changes

Reviewed the complete six-file delta. The design coherently reuses existing nullability, canonicalization, Group/shuffle and cleanup owners while preserving full tuple identity. Local checks passed; no implementation defect was confirmed. Required end-to-end and performance evidence remains unverified.

Model: gpt-6-astra / xhigh

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

  • P2 pkg/sql/plan/distinct_agg.go:64: Validation requirement: qualifying non-NULL COUNT(DISTINCT a,b) now enters the local Group → exchange → final Group → ordinary COUNT topology.
    Impact: The available tests establish admission and plan shape, but do not establish cross-worker SQL exactness, spill/cancellation cleanup, prepared reuse or the claimed performance benefit. These are explicit acceptance requirements for this execution path.
    Evidence: evidence.json.local_validation is empty. The PR reports SQL and ABBA results without retained logs or command/source/build/exit receipts. TestLocalPreAggregationCompileShapeIsReachableFromSQL only optimizes SQL and checks plan shape. Provide the existing exact-candidate artifacts, or run the uncovered checks: duplicate tuples differing in the nonselected component; CHAR/Unicode and NULL/outer-join/empty controls; DOP1/8 and two-CN execution; forced spill, cancellation and prepared reuse with cleanup assertions; and controlled base/candidate timings with unary/mixed/low-NDV/all-invalid controls. Reconcile these with the design document’s acceptance matrix.

Validation:

  • Preflight passed. Go 1.27.1/linux-amd64 used assigned caches and test-exec. Current native inputs matched a retained build accepted by the repository provenance verifier.

  • Passed focused planner, compiler and logtail tests; full pkg/sql/plan and pkg/vm/engine/tae/logtail/service packages.

  • The changed logtail synchronization test passed under -race with count=20 and count=100. git diff --check passed.

  • Ten receipts were reconciled with retained logs in /home/xupeng/.local/state/mo-bot/jobs/f7da52954ac55e70cc341c8f/attempt-1/validation-audit.json. Review coverage is recorded in review-map.json. Source remained unchanged.

Limitations:

  • Distributed SQL, spill/cancellation, prepared execution and benchmark acceptance remain open; no performance measurements were independently verified.

  • Initial native-owner setup rejection executed no tests; compatible artifacts were subsequently verified and reported product checks completed.

  • Two preexisting planner subtests were skipped. The frozen CI snapshot supplies no relevant completed end-to-end evidence; the linked issue body was not supplied.

@XuPeng-SH
XuPeng-SH force-pushed the codex/perf-30995-tuple-distinct branch from 007b27c to a1f27da Compare October 24, 2026 01:03
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the retained-validation-evidence request in review 5633797167, and rebased onto main 94faf02. Current head: a1f27dad63c4ef1e5e06c4a50fe3f4b906776107.

The evidence index and acceptance matrix now retains exact source/build/command/exit receipts, binary hashes, diagnostic sources/configs, SQL outputs, physical/analyze plans, raw timing samples and SHA256SUMS. The tested candidate 3d1b86f and this documentation-only follow-up have identical pkg/cmd trees and changed Go file hashes. The rebase conflict preserves main’s actual compiler physical-selection assertions plus the new tuple cases; production tuple/logtail content is unchanged.

Fresh normal/race and incremental SCA passed. Public execution proves DOP 1/8, nonselected-component tuple differences, CHAR/Unicode, NULL/outer-join/empty controls, two CNs, four prepared executions, nonzero spill, cancellation 1317 with a surviving 5M-row query, connection reuse and zero newly remaining spill files.

The current clean-main/candidate ABBA samples and receipt cover all eight cases, 20 warm samples/version: tuple 458.803 → 36.698 ms (12.50x); unary +5.06%, mixed +0.55%, low-NDV −0.54%, all-invalid −11.59%. All results were checked exactly. Public correctness and final performance datasets are explicitly distinguished. A pre-sample startup failure is retained and excluded; final timing uses a newly bootstrapped task-owned persisted fixture throughout.

The gpt-6.1-sol/xhigh final overall review passed with no unresolved material findings/proof gaps. Please re-review the now-retained proof. GitHub CI for the new head remains pending.

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Oct 24, 2026
@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: a1f27dad63c4ef1e5e06c4a50fe3f4b906776107

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: a1f27dad63c4ef1e5e06c4a50fe3f4b906776107

Assessment: approve

Reviewed the complete delta and affected callers. The design preserves complete canonical tuple identity, requires effective non-NULL proof, and reuses existing Group, shuffle, COUNT and cleanup owners. Conservative fallbacks remain intact. The logtail test correctly synchronizes admission release. Verified retained evidence closes the previous validation finding; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Independent evidence audit passed: checks/1792804573500201577-3.json records exit 0 and the clean assigned head. Retained evidence-audit.log, evidence-audit.json and review-map.json document reconciliation.

  • All 127 archived checksums match. Tested commit 3d1b86f differs from this head only in evidence files. Executable/test inputs, native input provenance, build identities, script snapshots and output hashes match.

  • Reused verified passing full planner/logtail tests, focused compiler tests and 23 focused race tests. Static-analysis receipts cover 345 packages; lint reports zero issues. Molint's retained diagnostics were not represented as warning-free.

  • Verified public SQL results and physical plans covering tuple order, nonselected components, CHAR/Unicode, NULL/outer-join/empty fallbacks, two CNs, prepared reuse and actual spill. Cancellation completed in 24.8 ms; the concurrent survivor succeeded, the canceled connection remained usable, and all 358 observed new spill files were cleaned up.

  • Recomputed 320 ABBA samples: eligible tuple cases improved 8.6–17.1×. Unary timing increased 5.06% and mixed aggregates 0.55%; low-NDV and all-invalid controls improved. Production/test/design whitespace checks passed.

Limitations:

  • Native execution evidence was reused from matching darwin/arm64 builds; native tests were not rerun locally. Relevant CI jobs remained pending in the frozen snapshot.

  • Measurements establish warm local performance and colocated two-CN correctness, not production-network performance or reduced peak memory. Additional pair-Group state retains existing memory and spill controls.

  • The linked issue body was not supplied; its behavioral contract was assessed from the frozen PR, design and review evidence.

@XuPeng-SH
XuPeng-SH merged commit 70e48cb into main Oct 24, 2026
32 of 33 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/perf-30995-tuple-distinct branch October 24, 2026 04:29
XuPeng-SH added a commit that referenced this pull request Nov 16, 2026
)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #32665
Fixes #32690 on 4.2-dev

## What this PR does / why we need it:

Preserve a useful forced regular-index access when ORDER BY still needs
a separate sort. A bounded index-side Top is admitted only when the
access is private, all required predicates and sort keys can be
evaluated safely, the order includes the primary key, and known
statistics justify it. The base SQL predicates and final Top remain
authoritative; an unproven residual prevents a static reader limit.

Keep nullable TopValue pruning fail-open when nullability, physical
type, scale or block metadata cannot prove exclusion. Reuse existing
scan-reader and shuffle ownership, exact IN membership, vector and Top
execution paths while avoiding redundant reader, decoding and sorting
work.

Publish complete index predicates before deriving scan statistics. A
synthesized prefix range and its decoded SQL residual must not count the
same condition twice. Scan statistics derive an estimation-only view
from the actual encoded access and decoded rechecks, recognizing every
proven static integer prefix component or exact IN set. The executable
expressions keep their own selectivities for filter ordering and block
estimates. Unproven cases remain conservative.

The pre-existing 4.2 DECIMAL comparison and pruning defect exposed by
this PR's CI was fixed independently by #32767, now merged into 4.2-dev
as 6dd9f9d. This branch is rebased on that merge. The original
reported DECIMAL query has also been verified on main.

The logtail CI failure is addressed by backporting the test-only
read-barrier synchronization already merged on main in #30998. Receiving
the response can precede the publisher's deferred release; the test now
waits to reacquire the sole admission slot and still detects a leak.

The CI follow-up updates the expected block-filter plan and fixes the
test comparator's tie key for two IVF JOIN queries. Their original SQL
is unchanged; actual plans confirm that the default query still uses IVF
and the forced exact query retains its exact path.

## Validation

- Current fix on 57: full `pkg/sql/plan` normal tests, the focused
selectivity suite under `-race`, and `static-check-selected` for
`pkg/sql/plan` exited successfully. Golangci-lint reported zero issues;
molint also printed five `checkrecover` diagnostics in code unchanged
from the previous PR head. On the previous PR head, the new multi-prefix
regression failed with 18,939.39 estimated rows; after the fix the index
scan and inner Top input cost both estimate 75,757.58. The test also
covers open ranges, a residual, low selectivity, repeated refresh, and
mismatching/NULL/sourced bounds.
- Executed FORCE-versus-IGNORE SQL on one- and two-CN embedded
instances, before and after flushing both the table and its index.
Range, offset, descending order, residual, NULL, empty, IN and
composite-primary-key cases matched; after flush `EXPLAIN` confirmed the
index-side Top and both rechecks. The two-CN instance selected
`ForceOneCN`, so this does not claim multi-CN parallel execution.

- Logtail test-only follow-up before the current selectivity fix: the
exact failing logtail test passed 100 race-detector repetitions; its
full owning package passed normal and race tests, go list/build/vet, and
static-check-selected.
- On the clean 4.2-dev baseline, controlled publisher scheduling
demonstrated that the response can arrive before the deferred slot
release. A temporary leak-injection overlay made the corrected test fail
as expected; no production mutation was retained.
- Against 4.2-dev at 296402f and #32767: actual SQL on one and two
CNs, before and after flush, including FORCE/AUTO/IGNORE, composite
DECIMAL bounds, NULL, outer joins and overflow. The original FORCE query
was verified to use its index.
- A DECIMAL composite-index query with a non-exact range was verified to
apply its decoded residual below the internal Top; both FORCE and IGNORE
returned the same expected rows. After rebasing, actual CHAR index and
JOIN runtime-filter probes and the one/two-CN DECIMAL and Top/vector
plan probes all passed.
- Before the current selectivity fix, relevant two-CN BVT: 1,451/1,451
statements passed, with no failures or skips. This includes all three
previously failing #32767 files as well as force_index_order,
explain_index and vector_ivf_equi_join.
- Before the current selectivity fix, the complete pkg/sql/plan and
pkg/sql/plan/function suites passed both normally and with race
detection. Earlier focused tests for the affected packages and
selectivity proof boundaries also passed.
- Before the current selectivity fix, vet and the project
static-check-selected target (molint and golangci-lint) passed for all
12 Go packages then changed relative to 4.2-dev.
- BuildPlan tests with explicit 1M-row statistical fixtures verify the
range and IN estimates are counted once and remain correct after a leaf
statistics refresh. Tests also cover NULL, parameter sources,
malformed/different vectors, changed bindings and truncated keys.

## Performance

For this selectivity fix, an ABBA planner microbenchmark on 57 compared
the previous PR head and the fix using the same four FORCE query/fixture
shapes. The two-run mean changed from -3.2% to +2.8% across cases; the
multi-prefix Top case changed from 289.4 to 290.5 microseconds per
planning iteration. This includes fixture construction and parsing and
is not a SQL execution latency benchmark.

On host 57, a direct ABBA comparison used the prior #32675 head
baefd9b and the then-candidate d4671cf (before the later
prerequisite CI follow-up), one million flushed/analyzed rows in
concentrated and scattered layouts, eight SQL cases, 100 warmups and 300
measured executions per case per process. All 16 comparisons used
identical plans and result digests; mean process medians changed between
-4.6% and +5.1%.

A separate comparison made before the prerequisite CI follow-up against
the then-#32767 baseline showed that some FORCE queries are 14%–47%
slower because the old code ignored FORCE and used a table scan, while
the candidate performs the requested index scan and backfill. Other
workloads improved; for example the concentrated IN/Top case improved
about 75%. The identical-plan AUTO case was faster in the concentrated
layout and essentially unchanged in the scattered layout. These numbers
describe the tested workloads, not every possible query.

A separate pre-existing 4.2 issue remains for reused untyped prepared
parameters whose DECIMAL scale changes; it also reproduces without an
index and is outside this PR.

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

[Bug]: Multi-column COUNT(DISTINCT) retains serial exact-state merge and is ~20x slower than unary control

2 participants