Skip to content

[Optimizer] Push down correlated scalar aggregate keys - #26152

Merged
XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
aunjgr:agent/fix-26130
Aug 11, 2026
Merged

XuPeng-SH merged 8 commits into
matrixorigin:mainfrom
aunjgr:agent/fix-26130

Conversation

@aunjgr

@aunjgr aunjgr commented Jul 24, 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 #26130

What this PR does / why we need it:

TPC-H Q17 decorrelates its scalar AVG subquery by grouping on the correlation key, but previously aggregated every inner lineitem row even when the outer part predicates selected only a small key set.

This change restricts the aggregate input with a SEMI join against a cloned outer base-table scan carrying deterministic, single-binding WHERE predicates. The cloned scan receives a fresh binding tag and preserves its scan snapshot. Predicate order does not affect discovery. Unfiltered, volatile, multi-table, and derived-table domains retain the existing plan.

The regression coverage verifies:

  • both Q17 predicate orders produce a filtered part key-domain scan below the correlated AVG;
  • the original and cloned scans use distinct binding tags;
  • unfiltered and volatile domains skip the rewrite;
  • the optimized query returns the expected result on a counterexample containing an excluded part;
  • both high- and low-NDV EXPLAIN snapshots include the SEMI join.

Validation:

  • env GOCACHE=/tmp/mo26152-gocache .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s ./pkg/sql/plan
  • env GOCACHE=/tmp/mo26152-gocache .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s ./pkg/sql/plan/explain
  • official mo-tester on optimizer/associative.sql: 20/20 passed
  • package coverage: 76.2% (pushdownScalarAggregateKeys: 82.4%)
  • go build, go vet, make err-check, and git diff --check

@aunjgr
aunjgr requested a review from XuPeng-SH as a code owner July 24, 2026 11:25
@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 →

@aunjgr

aunjgr commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Updated the branch to current main and replaced the ineffective original rewrite.

Root cause: the previous SEMI join copied the outer scan before WHERE predicate pushdown, so its part scan had no p_brand/p_container filters and still admitted every part key. It also reused the original binding tag.

The revised rewrite builds a fresh, filtered key-domain scan from the complete bound WHERE list, assigns a new binding tag, preserves scan snapshots, and skips unsafe/unhelpful unfiltered or volatile domains. The regression now checks both predicate orders, filter retention, tag ownership, fallback cases, final EXPLAIN shape, and an executed counterexample result.

Local validation passed: planner and explain packages, build, vet, SCA/forbidden-package check, 76.2% package coverage, and official mo-tester for optimizer/associative.sql (20/20).

@aunjgr

aunjgr commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the coverage gate on current head c3145f31f1 after merging newest main. The failed artifact showed 45/60 changed lines (exactly 75%, while the gate requires >75%). The added guard tests exercise nine previously uncovered changed blocks in scalar-aggregate pushdown/projection traversal, taking the artifact-based changed coverage to at least 54/60 (90%). Focused tests, full planner tests with coverage, SCA, and diff checks pass.

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

Reviewed the complete optimizer rewrite against current main. Checked the SEMI-domain equivalence for duplicate and NULL keys, direct multi-key equality, outer joins and superset filters, predicate order, volatile/subquery/derived guards, scan snapshot preservation, fresh tag rebinding, and aggregate empty-input behavior. Focused planner counterexample tests pass locally and CI, coverage, SCA, and BVT are green. No P0-P3 findings.

@XuPeng-SH
XuPeng-SH merged commit 75d61d0 into matrixorigin:main Aug 11, 2026
26 checks passed
XuPeng-SH added a commit that referenced this pull request Sep 7, 2026
## Summary

Fixes #28158.

This is the `main`-branch companion to #28353. The two branches have
diverged: `main` already contains the broad duplicate-safe SEMI rewrite
from
#26152, so the 4.2 commit cannot be cherry-picked cleanly. This PR
applies the
same correctness fix to the current `main` planner while retaining that
existing behavior.

## Root cause

After decorrelation, a correlated scalar aggregate groups by the
pulled-up
correlation key, but its aggregate input is otherwise independent of the
outer relation's key domain. If the outer query selects a narrow
tenant/task
or primary-key domain, the aggregate can scan and aggregate unrelated
rows
that share only part of the correlation key. An ordinary INNER JOIN is
not a
safe fix because duplicate outer keys would multiply rows and change
COUNT,
SUM, or MAX semantics.

## Changes

- Keep `main`'s existing duplicate-safe SEMI key-domain rewrite for safe
  deterministic correlations, including non-point domains.
- For a complete primary-key point domain, copy only the proven equality
predicates to the aggregate's base-table scan. This gives the physical
scan
  and index selection the same bounded domain instead of relying on join
  reordering.
- Require direct inner group-by columns for this rewrite. Computed inner
keys
  are left on the original plan so an expression is not evaluated twice.
- Require one base-table outer binding and deterministic, same-table
local
  predicates. Missing, derived, multi-table, volatile, computed, OR, and
  incomplete composite-key cases conservatively fall back.
- Deep-copy predicates/snapshots and rebind the copied scan with a fresh
tag
  so the new domain scan cannot alias or mutate the outer scan.

## Correctness and performance considerations

- The SEMI join preserves outer multiplicity; it does not introduce the
row
  multiplication of an INNER JOIN.
- Composite primary-key pushdown requires every key part to be
constrained by
a direct runtime-constant equality. A partial key remains on the
existing
  SEMI path and is not copied to the aggregate scan.
- Empty-input behavior is covered for COUNT (zero) and SUM/MAX (NULL).
- The point-filter copy is a bounded-domain optimization only. Broad
filters
  do not cause an additional wide aggregate scan or a large set of point
  probes.
- In a local 100,000-row reproduction with 100 rows in the target
domain, the
aggregate-side scan read the bounded 100-row domain (50 rows reached the
aggregate after filtering), instead of reading all 100,000 rows. This is
a
  plan/profile sanity check, not a representative benchmark.

## Validation

- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158' -timeout=300s ./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158|TestCorrelatedScalarAggregatePushdown' -timeout=300s
./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s
./pkg/sql/plan`
- `go vet ./pkg/sql/plan`
- `make build`
- `make err-check`
- MatrixOne distributed optimizer regression: 11/11 passed
- `gofmt -d` and `git diff --check` clean

CI was not awaited locally; GitHub CI should provide the final
cross-platform
validation.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…26152)

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

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

TPC-H Q17 decorrelates its scalar `AVG` subquery by grouping on the
correlation key, but previously aggregated every inner `lineitem` row
even when the outer `part` predicates selected only a small key set.

This change restricts the aggregate input with a SEMI join against a
cloned outer base-table scan carrying deterministic, single-binding
WHERE predicates. The cloned scan receives a fresh binding tag and
preserves its scan snapshot. Predicate order does not affect discovery.
Unfiltered, volatile, multi-table, and derived-table domains retain the
existing plan.

The regression coverage verifies:

- both Q17 predicate orders produce a filtered `part` key-domain scan
below the correlated `AVG`;
- the original and cloned scans use distinct binding tags;
- unfiltered and volatile domains skip the rewrite;
- the optimized query returns the expected result on a counterexample
containing an excluded part;
- both high- and low-NDV EXPLAIN snapshots include the SEMI join.

Validation:

- `env GOCACHE=/tmp/mo26152-gocache
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s
./pkg/sql/plan`
- `env GOCACHE=/tmp/mo26152-gocache
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s
./pkg/sql/plan/explain`
- official `mo-tester` on `optimizer/associative.sql`: 20/20 passed
- package coverage: 76.2% (`pushdownScalarAggregateKeys`: 82.4%)
- `go build`, `go vet`, `make err-check`, and `git diff --check`

---------

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…origin#28355)

## Summary

Fixes matrixorigin#28158.

This is the `main`-branch companion to matrixorigin#28353. The two branches have
diverged: `main` already contains the broad duplicate-safe SEMI rewrite
from
matrixorigin#26152, so the 4.2 commit cannot be cherry-picked cleanly. This PR
applies the
same correctness fix to the current `main` planner while retaining that
existing behavior.

## Root cause

After decorrelation, a correlated scalar aggregate groups by the
pulled-up
correlation key, but its aggregate input is otherwise independent of the
outer relation's key domain. If the outer query selects a narrow
tenant/task
or primary-key domain, the aggregate can scan and aggregate unrelated
rows
that share only part of the correlation key. An ordinary INNER JOIN is
not a
safe fix because duplicate outer keys would multiply rows and change
COUNT,
SUM, or MAX semantics.

## Changes

- Keep `main`'s existing duplicate-safe SEMI key-domain rewrite for safe
  deterministic correlations, including non-point domains.
- For a complete primary-key point domain, copy only the proven equality
predicates to the aggregate's base-table scan. This gives the physical
scan
  and index selection the same bounded domain instead of relying on join
  reordering.
- Require direct inner group-by columns for this rewrite. Computed inner
keys
  are left on the original plan so an expression is not evaluated twice.
- Require one base-table outer binding and deterministic, same-table
local
  predicates. Missing, derived, multi-table, volatile, computed, OR, and
  incomplete composite-key cases conservatively fall back.
- Deep-copy predicates/snapshots and rebind the copied scan with a fresh
tag
  so the new domain scan cannot alias or mutate the outer scan.

## Correctness and performance considerations

- The SEMI join preserves outer multiplicity; it does not introduce the
row
  multiplication of an INNER JOIN.
- Composite primary-key pushdown requires every key part to be
constrained by
a direct runtime-constant equality. A partial key remains on the
existing
  SEMI path and is not copied to the aggregate scan.
- Empty-input behavior is covered for COUNT (zero) and SUM/MAX (NULL).
- The point-filter copy is a bounded-domain optimization only. Broad
filters
  do not cause an additional wide aggregate scan or a large set of point
  probes.
- In a local 100,000-row reproduction with 100 rows in the target
domain, the
aggregate-side scan read the bounded 100-row domain (50 rows reached the
aggregate after filtering), instead of reading all 100,000 rows. This is
a
  plan/profile sanity check, not a representative benchmark.

## Validation

- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158' -timeout=300s ./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158|TestCorrelatedScalarAggregatePushdown' -timeout=300s
./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s
./pkg/sql/plan`
- `go vet ./pkg/sql/plan`
- `make build`
- `make err-check`
- MatrixOne distributed optimizer regression: 11/11 passed
- `gofmt -d` and `git diff --check` clean

CI was not awaited locally; GitHub CI should provide the final
cross-platform
validation.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…26152)

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

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

TPC-H Q17 decorrelates its scalar `AVG` subquery by grouping on the
correlation key, but previously aggregated every inner `lineitem` row
even when the outer `part` predicates selected only a small key set.

This change restricts the aggregate input with a SEMI join against a
cloned outer base-table scan carrying deterministic, single-binding
WHERE predicates. The cloned scan receives a fresh binding tag and
preserves its scan snapshot. Predicate order does not affect discovery.
Unfiltered, volatile, multi-table, and derived-table domains retain the
existing plan.

The regression coverage verifies:

- both Q17 predicate orders produce a filtered `part` key-domain scan
below the correlated `AVG`;
- the original and cloned scans use distinct binding tags;
- unfiltered and volatile domains skip the rewrite;
- the optimized query returns the expected result on a counterexample
containing an excluded part;
- both high- and low-NDV EXPLAIN snapshots include the SEMI join.

Validation:

- `env GOCACHE=/tmp/mo26152-gocache
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s
./pkg/sql/plan`
- `env GOCACHE=/tmp/mo26152-gocache
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s
./pkg/sql/plan/explain`
- official `mo-tester` on `optimizer/associative.sql`: 20/20 passed
- package coverage: 76.2% (`pushdownScalarAggregateKeys`: 82.4%)
- `go build`, `go vet`, `make err-check`, and `git diff --check`

---------

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…origin#28355)

## Summary

Fixes matrixorigin#28158.

This is the `main`-branch companion to matrixorigin#28353. The two branches have
diverged: `main` already contains the broad duplicate-safe SEMI rewrite
from
matrixorigin#26152, so the 4.2 commit cannot be cherry-picked cleanly. This PR
applies the
same correctness fix to the current `main` planner while retaining that
existing behavior.

## Root cause

After decorrelation, a correlated scalar aggregate groups by the
pulled-up
correlation key, but its aggregate input is otherwise independent of the
outer relation's key domain. If the outer query selects a narrow
tenant/task
or primary-key domain, the aggregate can scan and aggregate unrelated
rows
that share only part of the correlation key. An ordinary INNER JOIN is
not a
safe fix because duplicate outer keys would multiply rows and change
COUNT,
SUM, or MAX semantics.

## Changes

- Keep `main`'s existing duplicate-safe SEMI key-domain rewrite for safe
  deterministic correlations, including non-point domains.
- For a complete primary-key point domain, copy only the proven equality
predicates to the aggregate's base-table scan. This gives the physical
scan
  and index selection the same bounded domain instead of relying on join
  reordering.
- Require direct inner group-by columns for this rewrite. Computed inner
keys
  are left on the original plan so an expression is not evaluated twice.
- Require one base-table outer binding and deterministic, same-table
local
  predicates. Missing, derived, multi-table, volatile, computed, OR, and
  incomplete composite-key cases conservatively fall back.
- Deep-copy predicates/snapshots and rebind the copied scan with a fresh
tag
  so the new domain scan cannot alias or mutate the outer scan.

## Correctness and performance considerations

- The SEMI join preserves outer multiplicity; it does not introduce the
row
  multiplication of an INNER JOIN.
- Composite primary-key pushdown requires every key part to be
constrained by
a direct runtime-constant equality. A partial key remains on the
existing
  SEMI path and is not copied to the aggregate scan.
- Empty-input behavior is covered for COUNT (zero) and SUM/MAX (NULL).
- The point-filter copy is a bounded-domain optimization only. Broad
filters
  do not cause an additional wide aggregate scan or a large set of point
  probes.
- In a local 100,000-row reproduction with 100 rows in the target
domain, the
aggregate-side scan read the bounded 100-row domain (50 rows reached the
aggregate after filtering), instead of reading all 100,000 rows. This is
a
  plan/profile sanity check, not a representative benchmark.

## Validation

- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158' -timeout=300s ./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158|TestCorrelatedScalarAggregatePushdown' -timeout=300s
./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s
./pkg/sql/plan`
- `go vet ./pkg/sql/plan`
- `make build`
- `make err-check`
- MatrixOne distributed optimizer regression: 11/11 passed
- `gofmt -d` and `git diff --check` clean

CI was not awaited locally; GitHub CI should provide the final
cross-platform
validation.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…26152)

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

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

TPC-H Q17 decorrelates its scalar `AVG` subquery by grouping on the
correlation key, but previously aggregated every inner `lineitem` row
even when the outer `part` predicates selected only a small key set.

This change restricts the aggregate input with a SEMI join against a
cloned outer base-table scan carrying deterministic, single-binding
WHERE predicates. The cloned scan receives a fresh binding tag and
preserves its scan snapshot. Predicate order does not affect discovery.
Unfiltered, volatile, multi-table, and derived-table domains retain the
existing plan.

The regression coverage verifies:

- both Q17 predicate orders produce a filtered `part` key-domain scan
below the correlated `AVG`;
- the original and cloned scans use distinct binding tags;
- unfiltered and volatile domains skip the rewrite;
- the optimized query returns the expected result on a counterexample
containing an excluded part;
- both high- and low-NDV EXPLAIN snapshots include the SEMI join.

Validation:

- `env GOCACHE=/tmp/mo26152-gocache
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s
./pkg/sql/plan`
- `env GOCACHE=/tmp/mo26152-gocache
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=180s
./pkg/sql/plan/explain`
- official `mo-tester` on `optimizer/associative.sql`: 20/20 passed
- package coverage: 76.2% (`pushdownScalarAggregateKeys`: 82.4%)
- `go build`, `go vet`, `make err-check`, and `git diff --check`

---------

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…origin#28355)

## Summary

Fixes matrixorigin#28158.

This is the `main`-branch companion to matrixorigin#28353. The two branches have
diverged: `main` already contains the broad duplicate-safe SEMI rewrite
from
matrixorigin#26152, so the 4.2 commit cannot be cherry-picked cleanly. This PR
applies the
same correctness fix to the current `main` planner while retaining that
existing behavior.

## Root cause

After decorrelation, a correlated scalar aggregate groups by the
pulled-up
correlation key, but its aggregate input is otherwise independent of the
outer relation's key domain. If the outer query selects a narrow
tenant/task
or primary-key domain, the aggregate can scan and aggregate unrelated
rows
that share only part of the correlation key. An ordinary INNER JOIN is
not a
safe fix because duplicate outer keys would multiply rows and change
COUNT,
SUM, or MAX semantics.

## Changes

- Keep `main`'s existing duplicate-safe SEMI key-domain rewrite for safe
  deterministic correlations, including non-point domains.
- For a complete primary-key point domain, copy only the proven equality
predicates to the aggregate's base-table scan. This gives the physical
scan
  and index selection the same bounded domain instead of relying on join
  reordering.
- Require direct inner group-by columns for this rewrite. Computed inner
keys
  are left on the original plan so an expression is not evaluated twice.
- Require one base-table outer binding and deterministic, same-table
local
  predicates. Missing, derived, multi-table, volatile, computed, OR, and
  incomplete composite-key cases conservatively fall back.
- Deep-copy predicates/snapshots and rebind the copied scan with a fresh
tag
  so the new domain scan cannot alias or mutate the outer scan.

## Correctness and performance considerations

- The SEMI join preserves outer multiplicity; it does not introduce the
row
  multiplication of an INNER JOIN.
- Composite primary-key pushdown requires every key part to be
constrained by
a direct runtime-constant equality. A partial key remains on the
existing
  SEMI path and is not copied to the aggregate scan.
- Empty-input behavior is covered for COUNT (zero) and SUM/MAX (NULL).
- The point-filter copy is a bounded-domain optimization only. Broad
filters
  do not cause an additional wide aggregate scan or a large set of point
  probes.
- In a local 100,000-row reproduction with 100 rows in the target
domain, the
aggregate-side scan read the bounded 100-row domain (50 rows reached the
aggregate after filtering), instead of reading all 100,000 rows. This is
a
  plan/profile sanity check, not a representative benchmark.

## Validation

- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158' -timeout=300s ./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run
'TestIssue28158|TestCorrelatedScalarAggregatePushdown' -timeout=300s
./pkg/sql/plan`
- `./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s
./pkg/sql/plan`
- `go vet ./pkg/sql/plan`
- `make build`
- `make err-check`
- MatrixOne distributed optimizer regression: 11/11 passed
- `gofmt -d` and `git diff --check` clean

CI was not awaited locally; GitHub CI should provide the final
cross-platform
validation.

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants