Skip to content

perf(plan): expose safe subquery predicates before join costing - #27915

Merged
XuPeng-SH merged 12 commits into
matrixorigin:mainfrom
aptend:perf/tpcds-plan-robustness
Sep 2, 2026
Merged

XuPeng-SH merged 12 commits into
matrixorigin:mainfrom
aptend:perf/tpcds-plan-robustness

Conversation

@aptend

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

Related to #26768

What this PR does / why we need it:

Implements the subquery/predicate closure of the three-PR analytic rewrite series. The exact design is RFC v6 in #27934, now aligned with the implementations at in-progress.

  • Totalizes eligible existential MARK predicates, bounded filtering OR-of-EXISTS, and common cross-relation DNF keys.
  • Adds an exact scalar-predicate runtime filter without moving SINGLE + FILTER, so scalar cardinality errors remain at their original logical scope.
  • Rejects scalar probe-column lineages that cross a shuffle boundary.
  • Validates current-CN scalar producer/consumer placement after physical scopes are built. If colocation cannot be proved, both physical message endpoints are removed before execution and the unchanged FILTER + SINGLE plan runs without the optional filter.
  • Requires total, side-effect-free keys for MARK, OR-of-EXISTS, and DNF rewrites; fallible/evaluation-domain counterexamples retain legacy behavior.
  • Adds compatibility fallback and the cohort rollback subqueryPredicatePlanning=1.

Public SQL evidence covers positive results and error scope for nullable EXISTS/MARK, OR-of-EXISTS, DNF, scalar empty/NULL/no-match, and eliminated/surviving SINGLE probe rows.

Exact-head validation:

  • ./pkg/sql/plan, ./pkg/sql/compile, and ./pkg/sql/colexec/hashbuild: PASS.
  • Multi-CN topology regression proves an unreachable scalar filter falls back without leaving either blocking consumer or producer endpoint; the colocated case retains the optimization.
  • Public SQL TestNullableExistsMarkKeepsHashEqualityAndBooleanResults and TestSingleJoinPushdownPreservesCardinalityErrorScope: PASS.
  • Scoped golangci-lint: 0 issues; git diff --check: clean.
  • Same-host planner p50 versus origin/main@c46d897e96: control +0.4%; admitted wall-time maximum +4.6%; allocation-byte maximum +8.4%, within RFC v6's bounded admitted-path budget.
  • Existing TPC-DS 1 TiB Q14b run: PASS in 1757.689s, 25,923,890,232 rows read.

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

@aptend

aptend commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the proxy BVT plan regression in 81d74ee without changing the fixture. The new outer-join rules were unconditionally rerunning build/probe ordering even when no outer rewrite matched, which perturbed the existing all-inner associative plan. The rules now report whether any subtree changed, and physical reordering runs only after an actual rewrite. Added positive/negative change-signal coverage; pkg/sql/plan tests and go vet pass locally.

@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 exact head 81d74ee against PR base 073d465.\n\nRequesting changes for two objective blockers.\n\n[Blocking] The mandatory design-first gate is not closed.\n\nThis is not an ordinary focused fix. It changes more than 1,200 production lines on the planner hot path and combines several independently semantic rewrite/costing contracts: preserved-side and nullable-side outer-join association, LEFT-to-ANTI conversion, OR-of-EXISTS folding, scalar SINGLE-filter placement, DNF join-key extraction, ANTI cardinality, and shuffle-layout reuse. Their legality and ordering interact, and incorrect admission can silently change SQL results.\n\nIssue #26768 is a roadmap/tracking issue, not an approved implementation design for this combined change. It explicitly says the work must be split into independently reviewable subissues rather than one monolithic PR, and its M0 measurement/regression foundation remains open. The PR does not link an exact reviewed design revision or approval decision, define the ordering and interaction invariants for these rules, compare credible alternatives, or map each rule to public semantic and performance acceptance evidence.\n\nPlease either split this into independently designed/reviewable closures as #26768 requires, or provide one versioned design for the complete rewrite series and obtain design approval first. The design must state rule ordering/fixpoint behavior, NULL/correlation/volatility/lineage/uniqueness contracts, fail-closed behavior, compile-time and plan-quality budgets, rollback, and a per-rule black-box/typed validation matrix. Implementation review can then verify the code against that approved contract without serially rediscovering architectural assumptions.\n\n[Blocking] Rebase/resolve the current main conflict before implementation approval.\n\nThe PR head is based at 073d465 while current main is b23beee, and a real content conflict exists in pkg/sql/plan/query_builder.go. Resolving that conflict changes the optimizer pass composition point, which is semantically relevant to the rewrite ordering above. The current exact-head CI cannot validate the eventual merged code. Rebase on latest main, resolve the conflict according to the approved ordering contract, and rerun the relevant planner UT, SCA, and SQL/BVT evidence.\n\nI inspected the production change map sufficiently to confirm the design trigger and interacting surfaces. Per the repository design-first contract, full implementation approval is intentionally blocked until these upstream gates are closed.

@aptend

aptend commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Added the versioned RFC at docs/rfcs/00000000_safe_subquery_predicate_rewrites.md in revision 1a80c490433eaa6da0b6039368210198d763435c. This PR is now in a distinct design-only phase; implementation approval remains blocked. The RFC records the complete rule set, legality and error-scope invariants, fixed ordering, compatibility/resource model, alternatives, rollout, and validation gates. Please review the RFC design first.

@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 exact head 1a80c490433eaa6da0b6039368210198d763435c against exact base fb2868cd974d11695dc6b8c72a7d46d10ec36232.

The RFC is substantially better: existential totalization, the scalar actual-cardinality state machine, fixed rule order, resource bounds, and optional-wire fallback are directionally sound. I am still requesting changes for one design-level correctness hole and the acknowledged implementation/evidence gaps below.

[Blocking design] Scalar runtime filtering can suppress errors or volatile evaluation in the sibling of an INNER join.

The RFC admits lineage through either side of INNER (docs/rfcs/00000000_safe_subquery_predicate_rewrites.md:239) and checks only the selected lineage, crossed join predicates, and target scan. The implementation does the same (scalar_predicate_runtime_filter.go:131-180), and the new test explicitly accepts inner right (runtime_filter_test.go:254-255). If that selected scan is the physical hash-build side, a scalar with zero rows/NULL publishes DROP (hashbuild/build.go:1056-1060,1089-1092), and a one-value filter can also make the build empty. HashJoin then terminates at hashjoin/join.go:225-230 without reading its probe-side sibling. A fallible or volatile filter in that sibling was observable before the final scalar predicate, but is now skipped. This violates the RFC observational-equivalence and safe-evaluation invariants even though every predicate on the selected path is total.

Please make eligibility aware of the finalized physical build/probe orientation: conservatively allow only a side whose filtering cannot trigger empty-build short-circuit of an unchecked sibling, or prove the complete skipped sibling subtree total and side-effect-free. Cover both ordinary and swapped build orientation with a typed plan oracle and a public error/volatile counterexample where the scalar is empty/NULL and where a one-value filter removes every build row.

[Blocking implementation alignment] The current prototype does not implement the RFC totality/fallibility gates:

  • flatten_subquery.go:912-927 exposes every existential predicate raw without proving hash-key operands/comparison total;
  • pushdown.go:836-887,1018-1066 rejects volatility but can project fallible OR-of-EXISTS keys into a union build; and
  • utils.go:493-554 factors structurally common DNF predicates without the RFC totality guard.

These can newly evaluate a key on a non-empty build when the common outer input is empty, or move a fallible common predicate into hash-key evaluation. Fail closed unless totality is proved, and add negative plan plus SQL error-scope controls for all three closures.

[Blocking readiness evidence] The RFC and PR body themselves identify evidence that is still absent: public/differential OR-of-EXISTS and DNF equivalence controls, an explicit correlated-scalar rejection proof, old/new mixed-version execution, and controlled base/head TPC-H/TPC-DS planning-time/allocation/node-count measurements under the stated 5% budget. Exact-head UT/SCA/BVT are green, but they do not cover these gates. Attach the required evidence after the implementation is aligned.

I also traced scalar delivery through compile, loop-build HashBuild, current-CN message wait, zero/one/multi-row terminal messages, cancellation, and remote serialization. I found no separate producer/wait deadlock or unbounded-state defect in the intended exact-version topology; the blocker is the newly skipped sibling evaluation domain above.

@aptend
aptend requested a review from XuPeng-SH September 1, 2026 10:40

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

Request changes on exact head 1a80c490433eaa6da0b6039368210198d763435c against merge-base fb2868cd974d11695dc6b8c72a7d46d10ec36232.

The mandatory design artifact is still Status: draft and explicitly says the prototype lacks totality gates, correlated-scalar rejection proof, public/differential OR-of-EXISTS and DNF controls, mixed-version execution, and controlled planner/performance evidence. Those are not editorial follow-ups for this optimizer/wire/executor change; its own Ready gate keeps implementation approval blocked.

There is also an unresolved semantic hole in the exact code. scalarRuntimeFilterScanColumn accepts either child of an INNER join. If the selected scan is the finalized physical hash-build side, scalar zero/NULL or a one-value filter can empty that build; HashJoin can then terminate without evaluating the sibling subtree. A fallible or volatile expression in that sibling was observable before the final scalar predicate and can now be suppressed. Restrict admission to finalized physical probe-side lineage, or prove the entire skipped sibling total and side-effect-free, and cover ordinary/swapped orientation with public error/volatile counterexamples.

The implementation still lacks the RFC totality proof elsewhere: insertMarkJoin leaves every existential predicate raw without proving the comparison and operands total, and extractExistenceJoinKeys rejects volatility but not fallible key evaluation before projecting OR-of-EXISTS branches. These rewrites can expand an expression evaluation domain when the original outer side is empty. Add the fail-closed totality gates and matching positive/negative typed plus public result/error evidence, then advance an exact design revision and request re-review.

@aptend

aptend commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the current review findings on exact head cdfd38ac7f: scalar filtering follows only finalized physical probe lineage; build/right and correlated cases fail closed; MARK, OR-of-EXISTS, and DNF now require totality; public result/error controls cover the expanded evaluation-domain cases; subqueryPredicatePlanning=1 restores legacy behavior; and v42 predecessor fallback is tested. Owning packages, public SQL, scoped lint, and diff checks pass. Planner measurements are in the updated template body.

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

Request changes on exact head cdfd38ac7f0011bc00d7061aa7f0ddf5e4f4920d.

  1. [P1][Q2 hang] The new current-CN scalar runtime filter can cross a shuffle boundary, while the physical topology guard does not validate this kind of tag. scalarRuntimeFilterScanColumn recursively crosses INNER, SEMI, and ANTI joins without rejecting Stats.HashmapStats.Shuffle. The runtime-filter address is AddrBroadCastOnCurrentCN, but rightSingleLocalRuntimeFilterTags only collects SINGLE && IsRightJoin; a left-SINGLE ScalarPredicate tag therefore bypasses validateRightSingleRuntimeFilterTopology. If the shuffled scan consumer and scalar producer land on different CNs, the scan blocks in ReceiveMessage(true, ...) waiting for a message that cannot arrive. Its 300-second timer only logs and loops, so the statement remains stuck until its context is cancelled.

I verified both omissions with temporary, uncommitted counterexample tests on this exact head:

  • a shuffled INNER path was accepted by scalarRuntimeFilterScanColumn;
  • a left-SINGLE scalar tag with producer on CN1 and consumer on CN2 returned no topology error.

Please preserve the no-runtime-filter fallback when colocation cannot be proved: reject shuffle-crossing probe lineages and include scalar-predicate tags in final physical topology validation, or implement actual cross-CN delivery. Add a multi-CN topology regression test so this cannot become a query hang.

  1. The design and wire-version integration gate is still open. The PR body still pins RFC v5 at e987af7..., whose status is draft, and declares merge order #27756 -> #27914 -> #27915. Both #27914 and this branch independently claim MORPC v43. Rebase onto the accepted predecessors, resolve the final protocol number and generated wire state, and rerun compatibility fallback coverage on that integrated head. Green CI on the isolated branch does not validate the final wire contract.

The previous scalar error-scope and totality concerns appear addressed on this head. I found no separate Q1 cleanup or Q3 unbounded-growth blocker: the scalar payload is bounded to one value and terminal build paths send a release message. The unresolved Q2 topology gap above is sufficient to block approval.

@aptend

aptend commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the Q2 hang finding on exact head b969c2763fa6f0484e322cc285035521247ae993.

  • Planning now rejects scalar probe-column lineages at any explicit shuffle boundary; missing join/hash-map metadata also fails closed.
  • Physical topology tracking now includes scalar-predicate tags as well as right-SINGLE local tags.
  • After scopes are built and before any pipeline starts, the compiler requires one producer and every blocking scan consumer to share an execution CN.
  • A scalar topology mismatch is an optimization fallback, not a query error: the compiler removes the physical scan receiver and HashBuild sender for that tag, then executes the unchanged FILTER + SINGLE plan. It does not mutate the reusable logical plan or remove unrelated runtime filters.
  • The colocated topology retains both endpoints and the optimization.

Regressions cover a shuffled INNER probe lineage, producer CN1 / consumer CN2 fallback, preservation of an unrelated probe spec and logical plan, and the colocated positive case.

Validation:

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=5m -run '^(TestScalarRuntimeFilterScanColumnStopsAtSemanticBarriers|TestScalarPredicateRuntimeFilterPreservesSinglePosition)$' ./pkg/sql/plan
PASS

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=5m -run '^TestValidateLocalRuntimeFilterTopology$' ./pkg/sql/compile
PASS

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=20m ./pkg/sql/plan ./pkg/sql/compile
PASS

golangci-lint run ./pkg/sql/plan ./pkg/sql/compile
0 issues

The PR body now points to RFC v6 exact revision 8ac5fe82192320c5b0200ff36f1a6d27890c1ba6, which records the shuffle guard, final physical validation, and no-filter topology fallback.

@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 re-review of exact head b969c27 against merge-base c46d897. The prior Q2 blocker is closed: scalar lineage rejects shuffle boundaries, final physical validation covers scalar tags before pipeline start, and an unproved current-CN topology removes both effective scan receivers and matching HashBuild senders while preserving unrelated filters and the reusable logical plan. I rechecked nullable EXISTS and NOT EXISTS MARK semantics, OR-of-EXISTS UNION plus SEMI equivalence under NULLs and duplicates, totality gates, common-DNF factoring, scalar zero/NULL/one/multi-row states, exact encoding, cardinality-error scope, build/probe orientation, remote/deep-copy compatibility, rollback, resource bounds, and current-main drift. Focused exact-head planner, compiler, and hashbuild tests pass locally. Exact-head Linux UT, arm64 SCA, and multi-CN BVT are green. No remaining correctness, performance, hang, leak, or design blocker found.

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 kind/documentation Improvements or additions to documentation kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants