Skip to content

fix(plan): make analyzed stats safe for join planning - #28348

Merged
XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
aptend:fix/manual-analyze-plan-stats
Sep 8, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:mainfrom
aptend:fix/manual-analyze-plan-stats

Conversation

@aptend

@aptend aptend commented Sep 7, 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:

issue #26768

What this PR does / why we need it:

Manual ANALYZE TABLE replaced metadata-derived min/max and shuffle ranges with sampled value statistics. That made NDV more accurate but removed physical-distribution inputs used by scan, shuffle, and join planning. The optimizer also multiplied redundant ranges on one column and compared dimension filters against the dimension's full historical key domain instead of the keys active in the fact table.

This change:

  • atomically composes sampled value statistics with a fresh bounded ObjectMeta collection, with sampled fields taking precedence and NDV/NULL counts capped by the exact analyzed row population;
  • intersects constant ranges on the same column and estimates the resulting interval once;
  • orders high-NDV single-table dimensions by their selectivity on the active fact-key domain, consistently across initial join ordering, associative rewrites, and SEMI/ANTI pushdown; unsupported or incomplete statistics retain the previous fallback.

The rules depend on column statistics and relational shape, not benchmark/query identities.

Validation:

  • TPC-DS 1 TB, same data/config, merge disabled, 128 MiB join/aggregate spill limits, two runs per candidate: Q32/Q53/Q63/Q92 aggregate average improved from 158.7s to 120.4s (-24.1%); Q53 improved 63.9s to 46.8s (-26.7%) and Q63 improved 66.1s to 45.2s (-31.7%). All result files were byte-identical.
  • All 99 TPC-DS 1 TB ordinary and verbose EXPLAIN plans generated after ANALYZE.
  • TPC-H 100 GB: 21/22 plans unchanged; Q15 changed to the range-aligned plan and warmed runtime improved by about 28%, with identical output.
  • go test ./pkg/sql/plan -count=1
  • go test ./pkg/vm/engine/disttae -count=1
  • go test -race ./pkg/vm/engine/disttae -run TestComposeAnalyzedStatsGenerationKeepsFreshPhysicalDistribution -count=1
  • make build

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

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

Codex automated review

Prior behavior. On origin/main, publishAnalyzedStats installed newAnalyzedStatsGeneration(collected) — a bare clone of what AnalyzeTable produced. So after ANALYZE TABLE the cache held sampled NDV/NULL/size (and min/max only under full coverage) but no AccurateObjectNumber/ApproxObjectNumber, no ShuffleRangeMap, and nothing at all for unselected columns. Join ordering sorted dimensions by compareStats(node.Stats), i.e. by the dimension's own filter selectivity against its full catalog key domain, and nested same-column constant ranges were multiplied (andSelectivity) or merged only for the 2-arg canMergeToBetweenAnd case.

What the PR does. (1) composeAnalyzedStatsGeneration clones a freshly collected ObjectMeta generation and overlays the analyzed fields, capping NDV/NULL by the exact analyzed row population; (2) estimateAndSelectivity flattens the AND tree, groups same-column constant ranges by (relPos, colPos, colFnName) and estimates the intersected interval once; (3) selectivityOnParent / getJoinActiveDomainSelectivityOnSide order dimensions, drive applyAssociativeLawRule3 and gate SEMI/ANTI pushdown by selectivity on the active fact-key domain min(parentNDV, dimensionNDV, parent.Outcnt).

Verification performed. Read every hunk. Confirmed: ANALYZE only overwrites MinValMap/MaxValMap under fullCoverage (pkg/vm/engine/disttae/analyze.go:548), so sampled bounds cannot contradict the metadata-derived ShuffleRangeMap; the publish fence publishStatsForGenerationAtTableVersion → WithTableVersion(expectedVersion) still rejects a schema drift even though the new metadata pass uses the latest TableDef; compareJoinVertexStats remains a strict weak ordering (lexicographic on (floor(sel/0.01), outcnt)), preserving the #25702 slices.SortFunc contract; setParent/unsetParent reset selectivityOnParent to the -1 sentinel and setSelectivityOnParent re-checks vertices[child].parent == parent, so no stale parent-relative value survives a graph rewrite; every new guard falls back to the previous estimate instead of returning a partial one; estimateAndSelectivity also removes a latent Args[0] out-of-range panic for a zero-arg and. Ran go test ./pkg/sql/plan/ -count=1 (ok, 10.9s) and go test ./pkg/vm/engine/disttae/ -run 'TestComposeAnalyzedStatsGenerationKeepsFreshPhysicalDistribution|TestAnalyze' -count=1 (ok) at head 7408895.

Review state. The PR has no human reviews and no inline review comments (only a paused-Qodo bot notice), so no prior finding is being duplicated or deferred to.

Intentional behavior changes worth recording, not blocking. ANALYZE TABLE now fails outright if the metadata collection fails, where before it published sampled stats alone; that is a deliberate no-silent-fallback choice and is consistent with the repo's stated preference. AccurateObjectNumber moves from always-0 to the real object count, which also fixes the baseObjectCount baseline reset in markExplicitUpdateComplete and makes the table_stats table function report object counts after ANALYZE.

Conclusion. No blocking defect found: the changes affect cardinality/cost estimation and join-shape heuristics only, all new paths degrade to the pre-existing fallback, and no crash, leak, race, result-correctness, or compatibility path was identified. The four findings below are non-blocking consolidation and consistency items.

P1 - pushdownSemiAntiJoins can compare an active-domain reduction factor against a raw filter selectivity (pkg/sql/plan/join_order.go:94)

semiAntiSelectivity (join_order.go:62-66) and siblingSelectivity (join_order.go:94-98 and 105-109) are each substituted independently, so the two operands of semiAntiSelectivity*ratio > siblingSelectivity can be in different units.

getJoinActiveDomainSelectivityOnSide returns a join-reduction measure: dimension.Stats.Outcnt / min(parentNDV, dimensionNDV, parent.Stats.Outcnt), and for ANTI its complement 1 - matchSelectivity (join_order.go:812-818). The value it replaces, Stats.Selectivity on a JOIN node, is selectivity_out = andSelectivity(leftSelectivity, rightSelectivity) (pkg/sql/plan/stats.go:1418, 1487, 1499) — the AND of the children's filter selectivities, not a reduction factor.

Concrete path: a SEMI join S whose inner side is a single high-NDV table with complete stats gets semiAntiSelectivity = 0.2 (active domain). Walking the left spine, the sibling inner join J has a multi-table right child, so hasSingleTableBinding fails at join_order.go:757 and siblingSelectivity stays D1.Stats.Selectivity = 0.005. The test becomes 0.2*2.0 > 0.005 → break → no pushdown, whereas the pre-PR comparison of two filter selectivities (S.Selectivity ≈ 0.001 vs 0.005) pushed down. Only one side needs to fall back for the decision to flip.

applyAssociativeLawRule3 in the same PR explicitly refuses to mix: it uses the active-domain pair only when currentActiveOK && candidateActiveOK, otherwise both operands fall back together (pkg/sql/plan/associative_law.go:394-408). Applying the same all-or-nothing rule here would keep the comparison homogeneous. Non-blocking because SEMI/ANTI pushdown legality is decided by joinSide, not by this threshold, so only plan quality is affected.

P2 - publishAnalyzedStats re-implements refreshStatsWithMode's metadata collection block, and the copies have already diverged (pkg/vm/engine/disttae/stats.go:1683)

Lines 1683-1710 duplicate, almost verbatim, the collection setup that refreshStatsWithMode already performs at stats.go:1557-1595: latest-catalog GetTableById, ps.ApproxDataObjectsNum() overridden by GetBaseObjectCnt(key), timestamp.Timestamp{PhysicalTime: time.Now().UnixNano()}, the updateStatsRequest literal, and the CollectAndCalculateStats(refreshCtx, req, gs.concurrentExecutor) call. executeStatsUpdate (stats.go:2009-2040) is a third copy of the same block, and it at least uses the existing newUpdateStatsRequest constructor (stats.go:166) that the new code bypasses.

The copies already disagree on two points:

  1. Error contract. refreshStatsWithMode passes a bare context.Canceled/context.DeadlineExceeded through unchanged (stats.go:1598-1600); the new copy wraps everything that is not a statsRefreshCancellationCause hit into moerr.NewInternalErrorNoCtxf("failed to collect physical statistics for analyzed table: %v", err) (stats.go:1707-1710), so the same failure is classified differently depending on entry point.
  2. Ordering contract. stats.go:1562-1564 states the generation must be captured "only after subscription and catalog resolution succeed". publishAnalyzedStats captures it at line 1677 and resolves the catalog at line 1683, so the table not found return at line 1686 leaves an idle updateRecord created for a table generation this publication never validated. It is reclaimed by RemoveTid, so this is not a leak — but it is exactly what the sibling comment says to avoid.

Extracting one collectFreshMetadataGeneration(ctx, refreshCtx, key, ps) (*pb.StatsInfo, float64, error) helper and calling it from both refreshStatsWithMode and publishAnalyzedStats would remove the divergence risk instead of leaving three copies to keep in sync.

P2 - Row-count capping of NDV/NULL is now implemented twice, alongside the existing StatsRefreshOptions extension point (pkg/vm/engine/disttae/stats.go:1792)

composeAnalyzedStatsGeneration caps every NDV and NULL count at the exact analyzed row population (stats.go:1770-1772, 1782-1784, and the two re-cap loops at 1792-1797). applyStatsRefreshOptions already implements the identical rule — including the identical rationale comment, "no distinct or NULL count may exceed the now-exact table cardinality" — at stats.go:1859-1872.

The duplication is structural, not incidental. engine.StatsRefreshOptions (pkg/vm/engine/types.go:1364-1384) is the documented extension point for "statistics that the statement computed from a table-wide scan", carrying TableDefVersion, TableRowCount and ColumnNDVs, and refreshStatsWithMode applies it on top of a freshly collected metadata generation at stats.go:1609. That is precisely the shape this PR has converged on for ANALYZE, yet the two paths remain separate: StatsRefreshOptions is only ever passed empty in production code (engine.go:1312, stats.go:1516), so the cap logic there is exercised only by tests while the live ANALYZE path uses the new copy.

Worth consolidating — e.g. extend the options struct to carry the full analyzed StatsInfo and route ANALYZE through refreshStatsWithMode, or at minimum have both call sites share one capStatsAtRowCount(stats *pb.StatsInfo, rowCount float64) helper — so the bound cannot drift between the two publications. Non-blocking: both copies are correct today and the published generation is internally consistent.

P2 - Range-group path silently discards a pre-assigned Expr.Selectivity memo (pkg/sql/plan/stats.go:1091)

estimateExprSelectivity treats a non-zero expr.Selectivity as authoritative and returns it immediately (stats.go:968-970, "already calculated"). The new group path bypasses that: rangeSelectivityGroupKey (stats.go:1113-1131) does not check the memo, and estimateConjunctiveRangeSelectivity recomputes from MinValMap/MaxValMap for the whole group (stats.go:1092-1100).

between is one of the groupable operator names, and several producers assign Selectivity to a between expr with information that is not derivable from column min/max:

  • pkg/sql/plan/expr_opt.go:2301 — merged.Selectivity = filters[lowerIdx].Selectivity * filters[upperIdx].Selectivity from mergeFiltersOnCompositeKey;
  • pkg/sql/plan/apply_indices.go:2596, 4486, 4510 — compositeFilterSel accumulated from per-index-part filters.

Reachable case: a query with three same-column bounds (x >= 1 and x >= 2 and x <= 3) leaves one merged between plus a residual >= in FilterList; at stats.go:2148 RewriteFilterExprList ANDs them, estimateAndSelectivity flattens and groups both, and the index/composite-derived memo on the between is thrown away in favour of a plain min/max interval. Conversely, conjuncts inside a group never get their own Selectivity written back, so sortFilterListByStats (stats.go:1369-1372) and calcBlockSelectivityUsingShuffleRange (stats.go:3377) keep reading per-predicate values for the same expressions.

For the common case the recomputation is harmless and arguably better — the discarded value is itself a product of two per-predicate estimates, which is the double counting this PR sets out to remove. But the memo is an explicit cross-module contract, so either honour it in rangeSelectivityGroupKey (skip a conjunct whose Selectivity != 0) or state in the comment at stats.go:1046-1051 that an assigned selectivity is intentionally overridden for grouped same-column ranges.

@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 of 7408895 against 39225f5. One confirmed P2 interval-boundary defect requires correction; see the inline comment. Reviewed all eight changed files and traced conjunction estimates, join-order consumers, ANALYZE composition, cancellation and versioned publication. No other new blocking finding established.

Validation: extracted the exact current estimateIntervalSelectivity, clampSelectivity and finiteOr functions into an isolated Go test. Three singleton-domain full-coverage cases incorrectly returned 1e-8; strict-at-value and inclusive-at-value controls passed. This is production-helper evidence, not a full SQL execution reproduction. Existing exact-head package/benchmark evidence was reused. UT/SCA are green; Proxy BVT and aggregate Coverage are failed and were not attributed by this review.

The previously noted mixed active-domain/raw-selectivity comparison in SEMI/ANTI remains a useful non-blocking follow-up: switch both operands together when both estimates are available, otherwise retain the paired fallback.

Comment thread pkg/sql/plan/stats.go Resolved

@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 b636dc9 against merge-base 040356c. The prior P2 singleton-domain defect is fixed: clipping a strict out-of-domain bound now preserves membership at the observed boundary, while strict bounds at the singleton still estimate empty. The six direct boundary controls and bound-expression regressions cover both directions.

Read all eight changed files and traced the range grouping/fallback, join ordering and associative/SEMI/ANTI consumers, and analyzed-statistics composition through refresh admission, cancellation, schema-version and generation-checked publication. Stats maps and shuffle ranges are independently cloned; admissions and owner callbacks have deferred cleanup. This is a bug-fix change, so no new feature design gate applies. No additional concrete blocker was found. The previously recorded mixed-selectivity heuristic and arithmetic-estimate tradeoffs remain nonblocking; this approval does not claim uniformly better plans for every distribution.

Evidence reused: current-head Ubuntu UT, static checks, shared build and both substantive multi-CN BVT jobs are successful in run 34180637835. Inspected the UT log confirming all 2717 planner tests are selected across eight race-detector processes. Existing semantic evidence for the unchanged composition/benchmark closures is retained. No local service or test rerun was performed.

@mergify mergify Bot added the queued label Sep 8, 2026
@mergify

mergify Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-08 06:48 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-08 07:36 UTC · at 85bab2824182b54eb140977ad40c73a4d9b7edad

This pull request spent 48 minutes 31 seconds in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]

Reason

Pull request #28348 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.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You 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.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, 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

@XuPeng-SH
XuPeng-SH merged commit 565ce74 into matrixorigin:main Sep 8, 2026
16 of 18 checks passed
@mergify mergify Bot added dequeued and removed queued labels Sep 8, 2026
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…8348)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26768

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

Manual `ANALYZE TABLE` replaced metadata-derived min/max and shuffle
ranges with sampled value statistics. That made NDV more accurate but
removed physical-distribution inputs used by scan, shuffle, and join
planning. The optimizer also multiplied redundant ranges on one column
and compared dimension filters against the dimension's full historical
key domain instead of the keys active in the fact table.

This change:

- atomically composes sampled value statistics with a fresh bounded
ObjectMeta collection, with sampled fields taking precedence and
NDV/NULL counts capped by the exact analyzed row population;
- intersects constant ranges on the same column and estimates the
resulting interval once;
- orders high-NDV single-table dimensions by their selectivity on the
active fact-key domain, consistently across initial join ordering,
associative rewrites, and SEMI/ANTI pushdown; unsupported or incomplete
statistics retain the previous fallback.

The rules depend on column statistics and relational shape, not
benchmark/query identities.

Validation:

- TPC-DS 1 TB, same data/config, merge disabled, 128 MiB join/aggregate
spill limits, two runs per candidate: Q32/Q53/Q63/Q92 aggregate average
improved from 158.7s to 120.4s (-24.1%); Q53 improved 63.9s to 46.8s
(-26.7%) and Q63 improved 66.1s to 45.2s (-31.7%). All result files were
byte-identical.
- All 99 TPC-DS 1 TB ordinary and verbose `EXPLAIN` plans generated
after `ANALYZE`.
- TPC-H 100 GB: 21/22 plans unchanged; Q15 changed to the range-aligned
plan and warmed runtime improved by about 28%, with identical output.
- `go test ./pkg/sql/plan -count=1`
- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
TestComposeAnalyzedStatsGenerationKeepsFreshPhysicalDistribution
-count=1`
- `make build`

---------

Co-authored-by: XuPeng-SH <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…8348)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26768

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

Manual `ANALYZE TABLE` replaced metadata-derived min/max and shuffle
ranges with sampled value statistics. That made NDV more accurate but
removed physical-distribution inputs used by scan, shuffle, and join
planning. The optimizer also multiplied redundant ranges on one column
and compared dimension filters against the dimension's full historical
key domain instead of the keys active in the fact table.

This change:

- atomically composes sampled value statistics with a fresh bounded
ObjectMeta collection, with sampled fields taking precedence and
NDV/NULL counts capped by the exact analyzed row population;
- intersects constant ranges on the same column and estimates the
resulting interval once;
- orders high-NDV single-table dimensions by their selectivity on the
active fact-key domain, consistently across initial join ordering,
associative rewrites, and SEMI/ANTI pushdown; unsupported or incomplete
statistics retain the previous fallback.

The rules depend on column statistics and relational shape, not
benchmark/query identities.

Validation:

- TPC-DS 1 TB, same data/config, merge disabled, 128 MiB join/aggregate
spill limits, two runs per candidate: Q32/Q53/Q63/Q92 aggregate average
improved from 158.7s to 120.4s (-24.1%); Q53 improved 63.9s to 46.8s
(-26.7%) and Q63 improved 66.1s to 45.2s (-31.7%). All result files were
byte-identical.
- All 99 TPC-DS 1 TB ordinary and verbose `EXPLAIN` plans generated
after `ANALYZE`.
- TPC-H 100 GB: 21/22 plans unchanged; Q15 changed to the range-aligned
plan and warmed runtime improved by about 28%, with identical output.
- `go test ./pkg/sql/plan -count=1`
- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
TestComposeAnalyzedStatsGenerationKeepsFreshPhysicalDistribution
-count=1`
- `make build`

---------

Co-authored-by: XuPeng-SH <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…8348)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26768

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

Manual `ANALYZE TABLE` replaced metadata-derived min/max and shuffle
ranges with sampled value statistics. That made NDV more accurate but
removed physical-distribution inputs used by scan, shuffle, and join
planning. The optimizer also multiplied redundant ranges on one column
and compared dimension filters against the dimension's full historical
key domain instead of the keys active in the fact table.

This change:

- atomically composes sampled value statistics with a fresh bounded
ObjectMeta collection, with sampled fields taking precedence and
NDV/NULL counts capped by the exact analyzed row population;
- intersects constant ranges on the same column and estimates the
resulting interval once;
- orders high-NDV single-table dimensions by their selectivity on the
active fact-key domain, consistently across initial join ordering,
associative rewrites, and SEMI/ANTI pushdown; unsupported or incomplete
statistics retain the previous fallback.

The rules depend on column statistics and relational shape, not
benchmark/query identities.

Validation:

- TPC-DS 1 TB, same data/config, merge disabled, 128 MiB join/aggregate
spill limits, two runs per candidate: Q32/Q53/Q63/Q92 aggregate average
improved from 158.7s to 120.4s (-24.1%); Q53 improved 63.9s to 46.8s
(-26.7%) and Q63 improved 66.1s to 45.2s (-31.7%). All result files were
byte-identical.
- All 99 TPC-DS 1 TB ordinary and verbose `EXPLAIN` plans generated
after `ANALYZE`.
- TPC-H 100 GB: 21/22 plans unchanged; Q15 changed to the range-aligned
plan and warmed runtime improved by about 28%, with identical output.
- `go test ./pkg/sql/plan -count=1`
- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
TestComposeAnalyzedStatsGenerationKeepsFreshPhysicalDistribution
-count=1`
- `make build`

---------

Co-authored-by: XuPeng-SH <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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