Repository navigation
fix(optimizer): bound correlated scalar aggregate point scans - #28355
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
LeftHandCold
left a comment
There was a problem hiding this comment.
Reviewed b28e7c7 against main and issue #28158. No blocking correctness or regression finding.
Checked the direct-column correlation proof, complete primary-key admission, atomic application of copied scan predicates, duplicate-safe SEMI join, snapshot/tag copying, and existing empty-aggregate reconstruction. Main retains its existing non-point SEMI optimization; the new scan-level point copy does not broaden admission to partial keys, OR/ranges, or computed/volatile expressions.
Validation: focused TestIssue28158 and TestCorrelatedScalarAggregatePushdown passed locally (Darwin arm64, GOMAXPROCS=2, -p=1). Five additional reviewer planner cases passed: complete composite key, reversed equality, missing correlated key part, OR domain, and range domain. The standard mock composite-key Names padding was normalized in the reviewer-only fixture to match real catalog metadata. git diff --check passed.
Scope: these are planner checks plus code/SQL-result-fixture review, not an independent distributed execution or production performance measurement. The reported bounded-scan evidence addresses the specific point-lookup shape in #28158; this is not a general optimization guarantee for arbitrary correlated aggregates.
### Root cause Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent. The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order. ### Changes - Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts. - Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution. - Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction. - Preserve existing explicit user-transaction validation and ownership semantics. - Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests. - Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions. ### Issue-to-test proof `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers: - database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs; - DIFF while an unrelated database DROP runs; - PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate; - completion, result correctness, and unrelated-drop visibility after every interleaving. The exact external regression set from #26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs. ### Validation - rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged - focused frontend admission and retry tests, including rollback/begin/gate error propagation - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3` - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1` - full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed - full `./pkg/frontend` - full `./pkg/tests/issues` - exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL` - `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment - `make build` - exact ten-case MOTR command from #26404 with `--repeat 20 -j 9` - `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored - `git diff --check` After upstream #28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream #28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed. The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers. Workflow run 34125753066 exposed one stale assertion in the existing #27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated #28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved #28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers. After rebasing onto upstream #28343's remote-bind convergence change and #28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN #26404 regression and the adjacent #27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with #28356's executor-owned temporary ALTER COPY transaction fix, which resolved #28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing. Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only #28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed. ### Residual risk The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload. Approved by: @XuPeng-SH
…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.
…28325) ### Root cause Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent. The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order. ### Changes - Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts. - Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution. - Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction. - Preserve existing explicit user-transaction validation and ownership semantics. - Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests. - Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions. ### Issue-to-test proof `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers: - database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs; - DIFF while an unrelated database DROP runs; - PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate; - completion, result correctness, and unrelated-drop visibility after every interleaving. The exact external regression set from matrixorigin#26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs. ### Validation - rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged - focused frontend admission and retry tests, including rollback/begin/gate error propagation - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3` - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1` - full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed - full `./pkg/frontend` - full `./pkg/tests/issues` - exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL` - `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment - `make build` - exact ten-case MOTR command from matrixorigin#26404 with `--repeat 20 -j 9` - `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored - `git diff --check` After upstream matrixorigin#28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream matrixorigin#28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed. The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers. Workflow run 34125753066 exposed one stale assertion in the existing matrixorigin#27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated matrixorigin#28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved matrixorigin#28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers. After rebasing onto upstream matrixorigin#28343's remote-bind convergence change and matrixorigin#28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN matrixorigin#26404 regression and the adjacent matrixorigin#27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with matrixorigin#28356's executor-owned temporary ALTER COPY transaction fix, which resolved matrixorigin#28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing. Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only matrixorigin#28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed. ### Residual risk The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload. Approved by: @XuPeng-SH
…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.
…28325) ### Root cause Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent. The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order. ### Changes - Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts. - Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution. - Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction. - Preserve existing explicit user-transaction validation and ownership semantics. - Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests. - Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions. ### Issue-to-test proof `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers: - database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs; - DIFF while an unrelated database DROP runs; - PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate; - completion, result correctness, and unrelated-drop visibility after every interleaving. The exact external regression set from matrixorigin#26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs. ### Validation - rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged - focused frontend admission and retry tests, including rollback/begin/gate error propagation - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3` - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1` - full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed - full `./pkg/frontend` - full `./pkg/tests/issues` - exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL` - `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment - `make build` - exact ten-case MOTR command from matrixorigin#26404 with `--repeat 20 -j 9` - `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored - `git diff --check` After upstream matrixorigin#28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream matrixorigin#28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed. The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers. Workflow run 34125753066 exposed one stale assertion in the existing matrixorigin#27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated matrixorigin#28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved matrixorigin#28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers. After rebasing onto upstream matrixorigin#28343's remote-bind convergence change and matrixorigin#28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN matrixorigin#26404 regression and the adjacent matrixorigin#27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with matrixorigin#28356's executor-owned temporary ALTER COPY transaction fix, which resolved matrixorigin#28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing. Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only matrixorigin#28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed. ### Residual risk The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload. Approved by: @XuPeng-SH
…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.
…28325) ### Root cause Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent. The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order. ### Changes - Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts. - Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution. - Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction. - Preserve existing explicit user-transaction validation and ownership semantics. - Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests. - Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions. ### Issue-to-test proof `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers: - database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs; - DIFF while an unrelated database DROP runs; - PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate; - completion, result correctness, and unrelated-drop visibility after every interleaving. The exact external regression set from matrixorigin#26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs. ### Validation - rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged - focused frontend admission and retry tests, including rollback/begin/gate error propagation - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3` - `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3` - `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1` - full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed - full `./pkg/frontend` - full `./pkg/tests/issues` - exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL` - `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment - `make build` - exact ten-case MOTR command from matrixorigin#26404 with `--repeat 20 -j 9` - `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored - `git diff --check` After upstream matrixorigin#28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream matrixorigin#28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed. The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers. Workflow run 34125753066 exposed one stale assertion in the existing matrixorigin#27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated matrixorigin#28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved matrixorigin#28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers. After rebasing onto upstream matrixorigin#28343's remote-bind convergence change and matrixorigin#28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN matrixorigin#26404 regression and the adjacent matrixorigin#27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with matrixorigin#28356's executor-owned temporary ALTER COPY transaction fix, which resolved matrixorigin#28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing. Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only matrixorigin#28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed. ### Residual risk The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload. Approved by: @XuPeng-SH
Summary
Fixes #28158.
This is the
main-branch companion to #28353. The two branches havediverged:
mainalready 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
mainplanner while retaining thatexisting 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
main's existing duplicate-safe SEMI key-domain rewrite for safedeterministic correlations, including non-point domains.
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.
are left on the original plan so an expression is not evaluated twice.
predicates. Missing, derived, multi-table, volatile, computed, OR, and
incomplete composite-key cases conservatively fall back.
so the new domain scan cannot alias or mutate the outer scan.
Correctness and performance considerations
multiplication of an INNER JOIN.
a direct runtime-constant equality. A partial key remains on the existing
SEMI path and is not copied to the aggregate scan.
do not cause an additional wide aggregate scan or a large set of point
probes.
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/plango vet ./pkg/sql/planmake buildmake err-checkgofmt -dandgit diff --checkcleanCI was not awaited locally; GitHub CI should provide the final cross-platform
validation.