Skip to content

fix(optimizer): bound correlated scalar aggregate point scans - #28353

Merged
XuPeng-SH merged 2 commits into
4.2-devfrom
codex/fix-issue-28158-42-v2
Sep 7, 2026
Merged

XuPeng-SH merged 2 commits into
4.2-devfrom
codex/fix-issue-28158-42-v2

Conversation

@XuPeng-SH

Copy link
Copy Markdown
Contributor

Summary

Fixes #28158.

The 4.2 optimizer decorrelates a scalar aggregate such as:

SELECT MAX(e.seq)
FROM agent_runtime_events AS e
WHERE e.workspace_id = task.workspace_id
  AND e.task_id = task.id;

by adding the correlated columns to the aggregate GROUP BY. The aggregate input can nevertheless remain independent of the filtered outer task. For a point lookup this makes the event relation scan unrelated workspaces/tasks before the grouped result is joined back to the task.

Design

This change adds a deliberately narrow admission rule for the concrete incident shape:

  1. Recognize only direct equality correlations that become aggregate group keys.
  2. Require the outer relation to be one base-table scan with a complete primary-key point domain (pk1 = constant AND ... AND pkn = constant). Range, IN, OR, partial-key, non-key, derived, multi-table, and unfiltered domains keep the existing plan.
  3. Add a duplicate-safe SEMI join from the aggregate input to a deep-copied outer key domain. SEMI is intentional: an ordinary inner join could multiply aggregate input when the outer relation contains duplicate keys.
  4. Copy only deterministic outer predicates to the cloned domain. Deep-copy expressions and snapshots, allocate a fresh binding tag, and do not mutate the original scan or its read view.
  5. When the aggregate input is a direct base-table scan and each correlation key is the corresponding direct scan column, copy the proven primary-key point predicates to that scan. This lets the normal index-selection path bound the physical read; the logical SEMI remains the correctness-preserving domain restriction.
  6. Reject computed inner group keys for this rewrite. Reusing a computed/volatile key in both the aggregate and the new SEMI condition could evaluate it twice and change semantics. Unsafe shapes fall back to the pre-existing decorrelation behavior.

The complete WHERE list is made available while its conjuncts are flattened, so the admission decision does not depend on SQL predicate order. The temporary state is replaced by the flattened list after the walk.

Correctness and risk decisions

  • SEMI preserves inner-row multiplicity; it does not multiply COUNT, SUM, or MAX inputs.
  • Empty-input behavior remains intact: COUNT(*) = 0, while SUM/MAX remain NULL; the surrounding outer row is retained.
  • Composite keys require every key component to have a runtime-constant equality. Missing components and disjunctive/range predicates do not admit the optimization.
  • Volatile/unknown functions and subqueries are not copied. A safe key equality may still be copied while unrelated unsafe conjuncts remain only on the original outer path.
  • A failed predicate bind or unsupported shape returns before attaching the new node or aggregate filters, avoiding partial plan mutation.
  • No new runtime synchronization, goroutine, retry, or resource-lifecycle path is introduced.
  • The optimization intentionally does not attempt a cost model for broad domains. The point-only scope avoids adding a second wide domain scan or many unbounded probes.

Validation

Local validation was run on the final commit:

  • ./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=300s ./pkg/sql/plan
  • ./.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run 'TestIssue28158' -timeout=300s ./pkg/sql/plan
  • go vet ./pkg/sql/plan
  • make err-check
  • make build
  • mo-tester optimizer regression: 11/11, 100%
  • git diff --check

The regression covers complete and partial composite-key correlations, duplicate keys, empty aggregate input, COUNT/SUM/MAX, volatile predicates, computed inner keys, disjunctions, incomplete key domains, and predicate-order independence.

For a local 100,000-event reproduction with only 100 rows belonging to the target task, the final EXPLAIN ANALYZE showed 100 rows read by the aggregate-side event scan, 100 rows from the task_event_key index domain, and 50 rows entering the aggregate after the completion predicate. Without the copied scan-level point filters, the aggregate-side event scan read 100,000 rows. This is plan evidence for the issue's point-lookup shape, not a claim about every workload.

CI was not awaited locally; GitHub CI remains the final platform/build matrix.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner September 7, 2026 15:00
@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 →

@LeftHandCold LeftHandCold left a comment

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.

Reviewed 8e9c21d against 4.2-dev and issue #28158. No blocking correctness or regression finding.

Checked complete outer primary-key point admission, direct correlation/group columns, deterministic predicate selection, duplicate-safe SEMI construction, snapshot/tag independence, and preservation of COUNT=0 and SUM/MAX=NULL empty-input behavior. Publishing the complete bound WHERE list before flattening makes admission independent of conjunct order. Unlike the main companion, this backport does not introduce the broad non-point SEMI optimization.

Local validation passed: TestIssue28158 plus five reviewer planner cases (complete composite key, reversed equality, missing correlated key part, OR domain, range domain), with GOMAXPROCS=2 and -p=1. Reviewer fixtures normalize the existing mock composite-key Names padding to actual catalog metadata. git diff --check passed. The distributed SQL/result fixtures were inspected, not independently executed locally; no independent production performance claim is made.

Non-blocking code-review note / outstanding CI gate: Coverage job 101799628436 reports changed-code coverage 68.90%, below the required >75%. Please add the missing branch tests and satisfy that gate before merging; this approval does not waive it. Complete composite-key/reversed-equality and unsupported-input fallback tests are useful additions. The change targets the point-lookup shape in #28158, not arbitrary correlated aggregate queries.

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

size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants