Skip to content

fix: preserve distributed Product execution and shared producer lifetime - #29643

Merged
XuPeng-SH merged 5 commits into
mainfrom
codex/issue-29642-shared-build-lifetime
Oct 6, 2026
Merged

XuPeng-SH merged 5 commits into
mainfrom
codex/issue-29642-shared-build-lifetime

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Test and CI

Which issue(s) this PR fixes:

Related to #29642. This corrects multi-scope Product ownership; it does not claim complete closure of the other HashJoin/required-filter topologies.

What this PR does / why we need it:

An empty Product consumer, or an outer empty-build HashJoin that bypasses Product.Call, can cancel a shared broadcast producer still needed by a peer. The compiler now defers producer ownership until downstream placement is complete. Original probe scopes remain available to local Group, Limit, Sort and subsequent Join compilation. An ordinary auxiliary Merge owns build terminal connectors and the source/dispatch; its completion edges never enter result receivers.

Jobs attach after canonical step/Output/RETURNING assembly. Lazy UNION ALL and ADAPTIVE_TOP candidates retain producers inside their independently activated branches. Independent DML writer roots retain placement and affected-row accounting; the existing root scheduler cancels auxiliary jobs after the last primary finishes, before joining cleanup. Bounded compiler metadata preserves original producer errors across nested Merge owners without changing query cancellation or retry priority. No additional lifecycle scheduler, wire protocol or per-row path is added. The rejected early-gather implementation and obsolete Product EOF wait are removed; the single-scope and other join paths remain scoped to their existing contracts.

Validation

Go 1.26.4, Linux amd64, repository CGo prerequisites:

  • Complete Compile suite passes normal and race; unchanged Product normal/race and six base-template fixture race results are reused.
  • Real scheduler tests assert complete nine-row peer output, both outer-HashJoin consumer orders, empty inputs/builds, all-empty interruption, build failure, partial-output panic through two enclosing Merges, cancellation/deadline and cleanup. The final ownership matrix passes 29 bounded race iterations; two-ancestor panic and independent-root runOnce fixtures each pass 100. Independent roots prove first/last completion, cancellation before cleanup acknowledgement, failure and exact accounting.
  • Typed compiler checks cover Group, local Limit, Order, ordered Top, packed-worker reference adjustment, unique ownership and unchanged result receiver sets. Codec/notify/terminal composition and map-release tests retain their distinct coverage.
  • Real two-CN SQL passes normal and race: 256x256 exact count/sum, two aggregate states entering the global Merge, lazy skipped Product, INSERT with 65,536 affected rows and verified contents, and prepared nonempty/empty/nonempty reuse.
  • Incremental formatting, vet, golangci-lint and molint cover Compile, Product, function and multicn. No introduced finding; molint retains seven baseline recover diagnostics in five byte-identical files.

Performance and review scope

The unconditional early gather is removed: the 256x256 aggregate again sends 2 states to the global Merge instead of 65,536 raw rows. Local downstream reduction and parallel placement follow the original compiler rules.

A private placement-only Go overlay pins the same 18-byte object ownership in the real two-CN fixture. For 1024x1024 input, both the original distributed PR implementation and this correction compute all 1,048,576 Product rows remotely and gather 2 aggregate states. With 5 warmups and 25 timed queries, medians are 52.6 ms original / 52.3 ms corrected: no observed regression for that controlled query. The rejected mandatory-gather implementation is faster on this single-host loopback fixture (44.0 ms); the restored plan is 18.8% slower against that control, while avoiding its gather of all 1,048,576 raw rows. This adverse comparison is disclosed; cardinality improvement is not a claim of universally lower latency or measured wire-byte savings. Placement overlays and benchmarks are outside tracked source.

The ancestor bypass fixture is composed white-box evidence, not proof of that exact SQL planner topology. The remote-retirement fixture uses mocked transport, not full blocked-network MORPC evidence. The historical one-off ancestor_stop failure remains unexplained and is not rewritten as an all-green historical run. Current corrected-code validation is separate from that history.

Implementation +191/-11, tests +991/-32, documentation +0/-0 against the target merge base; movements are not counted as reductions. Final gpt-6.1-sol/xhigh review and the additional controlled-performance assessment are recorded. CI for a new pushed revision is separate from these local results.

@XuPeng-SH XuPeng-SH self-assigned this Oct 6, 2026
@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 →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of commit 278604c: no blocking findings for the scoped Product EOF correction.

The design fits the existing responsibilities: an empty local probe receives the shared build terminal before ending, using the existing dependency receive, JoinMap reference ownership, and Reset/Free cleanup. Recursive markers still pass before build publication. The change adds no state machine, goroutine, cleanup owner, or per-row allocation/work.

Independent validation:

  • Exact-base product.go with the same tests fails: empty probe drops a substantive build error, and the compiler/scheduler counterexample retires the empty owner with a nil result before the build completes.
  • Current Product terminal/reuse/recursive-marker tests pass under the race detector.
  • All six current compiler/scheduler cases pass under the race detector: nonempty peer with the complete nine-row result, all probes empty, empty build, build failure, query cancellation, and ancestor normal stop. Quiescent allocation-account cleanup assertions pass.
  • An additional private Go-overlay probe moves the gated source failure from Call to Prepare; all 20 repetitions pass under the race detector, preserving the originating error and completing scheduler/resource cleanup.
  • Native build and diff whitespace checks pass. Initial compiler attempts exhausted the local /tmp filesystem; the completed compiler checks above were rerun sequentially with an NVMe temporary directory.

Implementation, tests, and documentation increments were reviewed separately. Production is +9/-7; tests are +392/-4, with distinct operator and real scheduler contracts using existing fixtures and deterministic barriers; documentation changes are zero. The missing testutil import correctly repairs existing test-package references.

Accepted tradeoff: all-empty probes now wait for finite build completion and may perform additional build work. This review establishes the confirmed Product path, not a general resolution of every shared-producer topology or attribution of the earlier #29638 CI failure.

Comment audit: no existing human reviews, inline comments, or review threads; the only PR comment is the Qodo pause notice.

At publication, shared build and CodeQL checks have passed; SCA, Ubuntu UT, UT coverage, and the two active multi-CN BVT jobs are still running. Pending checks are not counted as passes; merge readiness remains subject to CI completion.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent white-box QA of head 278604cd39d525ba6763130c9bef87efa630571d.

[P2] An ancestor's early termination bypasses the Product barrier and can still retire a shared broadcast build.

The Product EOF change is valid when Product.Call runs, but it does not resolve the shared producer's lifetime ownership:

  • pkg/sql/compile/compile.go:7118 attaches the shared build to the first consumer's PreScopes.
  • pkg/sql/compile/compile2.go:1312–1316 makes those producers inherit that consumer's pipeline context.
  • An outer INNER HashJoin with an empty build can return before calling its Product child (pkg/sql/colexec/hashjoin/join.go:251–255). The new receive barrier therefore never executes.
  • Normal cleanup of that first consumer cancels the shared producer while another Product consumer still needs it.

I reproduced this using real compiler broadcast wiring and the full MergeRun scheduler, with a manually composed outer HashJoin. Under -race -count=100, the current ownership produced zero rows in every run: 29 returned success despite missing the expected nine rows, and 71 returned context canceled. A diagnostic control giving both the shared source and build a common owner returned success with all nine rows in 100/100 runs. A separate correctness-oracle test fails on the missing rows.

This is an existing issue left unresolved, not a demonstrated regression introduced by this PR. The ancestor topology is white-box composed; I have not demonstrated that an end-to-end SQL plan generates it, so production SQL reachability and frequency remain unproven.

Please resolve shared source/dispatch/build lifetime at the existing common owner, preserving query cancellation, error propagation, waiting, and all-consumer termination. The control's context reparenting is diagnostic evidence, not a complete production fix. Alternatively, scope this PR explicitly to Product's own EOF and avoid claiming full closure of #29642.

Additional validation: full Product and Compile suites passed both normally and under race; partial source output followed by panic passed 100 race runs; a blocked build with a real query deadline passed 30 race runs. The PR's own scheduler matrix failed once in 100 runs in ancestor_stop with context canceled; a targeted follow-up and a diagnostic 1,000-run matrix passed. That original failure remains unexplained and should not be described as an entirely green stress run.

Performance: there is no new per-row probe work, but an all-empty probe now waits for build completion and may incur full build scanning/allocation instead of early termination. No benchmark was performed, so this review does not establish absence of performance impact.

@XuPeng-SH XuPeng-SH changed the title fix: prevent empty Product partition from retiring shared broadcast build fix: preserve shared Product producer lifetime Oct 6, 2026
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Oct 6, 2026

@XuPeng-SH XuPeng-SH left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review and fixes at 52201425a28a0deb5f10572c88be337c1b570be8.

All actionable comments have been reconciled:

  • The original ancestor-termination P2 remains fixed. Shared producers belong to completed execution regions, with exact peer results and cancellation before scheduler joins.
  • The mandatory early-gather P2 is fixed in this PR: original probe scopes reach downstream compilation, preserving local Group/Limit/Sort/Join placement. Global aggregate input is again two states, not the Cartesian output. The earlier suggestion to leave this as a follow-up optimization is superseded.
  • Additional gpt-6.1-sol/xhigh review findings were corrected: substantive source errors survive arbitrary finalized Merge ancestry, and real runOnce coverage proves independent-primary retirement, failure and affected-row accounting. Complete review and the explicit performance assessment both ACCEPT.

Final local evidence: complete Compile normal/race; public two-CN normal/race with exact aggregation, lazy skipped branch, INSERT affected rows/content and prepared reuse; ownership matrix 29 race iterations; two-ancestor panic and independent-root fixtures 100 race iterations each. Incremental formatting/vet/golangci/molint covers the four affected package closures, with zero introduced findings; the seven molint diagnostics are unchanged baseline files. Unchanged Product and original base-template checks are reused.

Performance is deliberately reported without a universal speedup claim. Same 18-byte object ownership is pinned through a private placement-only overlay in the real two-CN 1024x1024 fixture (five warmups, 25 queries). Corrected median 52.316 ms versus original distributed-plan 52.624 ms: no observed regression for that comparison. Rejected mandatory gathering is faster on this single-host loopback fixture at 44.041 ms, making the restored plan 18.8% slower against that control; it gathers 1,048,576 raw rows instead of two states. This adverse comparison is disclosed in the PR. Sequential runs without CPU pinning do not establish general throughput parity; logical vectors are not measured wire bytes.

The old one-off ancestor_stop failure remains unexplained, exact SQL reachability of the composed bypass remains unproven, and the composed remote test uses mocked transport. These limits are retained. CI for the new revision is pending and is separate from the completed local checks. No merge or default-branch push was performed.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent deep review of 52201425a28a0deb5f10572c88be337c1b570be8, performed directly without subagents.

Code-review recommendation: approvable; no new blocking production-code finding. This is a COMMENT review because the authenticated reviewer is also the PR author. Merge readiness remains conditional on required CI completing successfully.

The prior shared-producer ownership and premature-gather P2 findings are addressed. Deferred attachment retains the original probe scopes for downstream Group, Limit, Order/Top and Join compilation. Source/build ownership transfers into existing scope trees after canonical step/output assembly; auxiliary terminal connectors stay outside result receivers. Existing MergeRun/runOnce and Pipeline.Cleanup own cancellation-before-join and error collection. Compiler records are query-bounded and introduce no new lifecycle state machine, wire format, storage projection or per-row execution path. The obsolete Product EOF barrier and mandatory early gather are removed.

[P3, non-blocking] First-primary retirement test still depends on a timing window. At pkg/sql/compile/broadcast_product_lifetime_test.go:636-651, scope-context cancellation precedes root-result publication/consumption. Waiting another 25 ms does not prove the completion collector observed that first result. If collection is delayed until the second writer finishes, an incorrect first-completion retirement policy can escape this particular oracle. Prefer a deterministic acknowledgement that the first completion has been consumed before releasing the second writer. This is a test determinism gap, not a demonstrated production scheduler defect.

Performance evidence correction: the previously reported 52.6 ms control is early PR commit 278604cd39d525ba6763130c9bef87efa630571d, including its Product EOF barrier; it is not target base 614ab46453638324a7997ac3ecc6813e5c810309. The recorded 52.3 ms corrected / 52.6 ms early-PR comparison remains valid only for that controlled query. The rejected mandatory-gather control at 44.0 ms remains faster on the single-host loopback fixture; the adverse 18.8% comparison is retained.

In this review, an exact-target-base production overlay used the same 18-byte object-placement control and SQL fixture. It returned 0 / NULL where the 256x256 aggregate requires 65536 / 16842752. Current production returned the correct result with the same fixture. The incorrect base result cannot support a comparable latency baseline. Accordingly, any statement that measured latency parity against the true target base has been established is withdrawn; there is no all-workload performance-parity claim.

Additional independent validation:

  • 28 SQL permutations (seven shapes across DOP 1/2/4/8) pass under race: three-table Products, Products on both sides, activated lazy first/second branches, ordered LIMIT/OFFSET, DISTINCT reduction and CTE reuse. Package elapsed 15.685 s.
  • Actual buildScanParallelRun/newParallelScope with an injected storage reader that emits data then panics passes 100/100 race iterations, preserving the original error through two enclosing Merges and completing allocation cleanup. Package elapsed 1.549 s.
  • The identical current benchmark fixture passes exact result checks, including the 1,048,576-row Cartesian aggregate; 25 timed queries have a 51.8 ms median in this additional run. This is current-only evidence, not target-base latency parity.
  • Exact-head Compile normal/race, public two-CN race, ownership stress, independent-root execution and incremental SCA evidence was inspected and reused; no relevant source changed. The checkout remains clean.

Implementation +191/-11, tests +991/-32, documentation +0/-0 were reviewed separately. Most test additions prove distinct operator, compiler, scheduler, codec and public SQL contracts and reuse existing fixtures; the timing-window issue above is not excused by test volume.

Comment audit: the original EOF-barrier acceptance describes a superseded implementation; the ancestor-ownership P2 and both gather/performance comments are addressed; the Qodo pause notice requires no source change. The historical ancestor_stop flake, unproven exact SQL reachability of the manually composed outer-HashJoin topology, mocked-transport limitation and Product-only issue scope remain explicit. Full blocked-network MORPC failure injection was not performed.

At publication, no current-head CI failure is reported. Ubuntu UT, Linux/arm64 SCA, coverage, proxy multi-CN BVT and pessimistic multi-CN BVT are still in progress. Pending or skipped checks are not counted as passes.

@XuPeng-SH
XuPeng-SH merged commit ffe8362 into main Oct 6, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/issue-29642-shared-build-lifetime branch October 6, 2026 10:29
XuPeng-SH added a commit that referenced this pull request Oct 8, 2026
…ement (#29666)

## Summary

This is a small follow-up to the shared broadcast producer ownership
work.
When several independent broadcast probe scopes share one CN, a
HashBuild/map
and its build source must be owned by their common result region, not by
the
first consumer. That consumer may end normally without calling its child
while
a peer still needs the shared build.

Reuse the existing producer-region protocol for repeated-CN
HashJoin/LoopJoin
probe groups. Keep single/packed scopes, unique-CN non-Product scopes,
IndexJoin, ProductL2, DedupJoin and RightDedupJoin unchanged. Do not
change JOIN
semantics, probe placement, result receiver order, scan count,
cancellation
normalization, or add global
serialization. Existing Product ownership remains unchanged; the already
computed groups are reused rather than calculated twice.

The extension is deliberately limited to HashJoin/LoopJoin. Other
HashBuild
operators also have related structure, but their repeated-CN lifecycle
has
not been reproduced and is not changed by this PR. HashJoin's JOIN-type
variants use the same ownership protocol; their algorithms are
unchanged.
The new runtime RED/GREEN is specifically
equi INNER HashJoin and non-equi INNER LoopJoin, **not a claim that
every
operator/type was reproduced in this topology**. Existing owning-package
tests validate the unchanged operator/compiler contracts separately.

The existing producer-region helper runs Dispatch at the coordinator. An
eligible remote build source may therefore acquire one additional
coordinator
Merge relay. Scan count and probe placement are preserved, but this PR
does
**not** claim that every source/network placement is identical or that
public
SQL performance in this remote-source domain has been A/B validated.

## Deterministic contract evidence

The regression fixture uses real compiler probe/build assembly,
finalized
producer ownership, pipeline context initialization and MergeRun. Two
independent colocated HashJoin/LoopJoin probes consume the same build. A
real
outer broadcast INNER join with an empty map normally skips one
consumer,
while the peer still requires three build rows. The first consumer's
cause is
asserted to be ErrPipelineStopped, and the query parent remains live.

On the untouched base, normal consumer cleanup cancels the
still-required
shared source. With the fix, the peer returns the exact expected result.
Additional cases cover first/last skipped consumers, empty peer, all
consumers
skipped, empty build, original build error, partial output then panic,
query
cancel/deadline, ancestor normal stop, and normal/cancelled execution
followed
by Scope.Reset with a fresh allocation-account/pipeline generation.
The reuse test retains internal operator templates; it does not assert
that AP
prepared SQL is supported.

Every scenario joins workers and drains board/spool ownership before
asserting
allocation-account usage is zero. A structural regression explicitly
excludes
IndexJoin and checks final worker reference counts, including downstream
DOP
changes and existing remote groups. Existing Product remote retirement
and
independent result-root contracts remain enabled.

## Important scope boundary

This proves a supported **internal compiler/runtime scope ownership
contract**.
It does not prove an actual SQL planner currently creates the asymmetric
probe
placement in this fixture. It does not establish the first cancellation
owner
or the root cause of Nightly Run 37484909730's information_schema
metadata JOIN
failure. Natural three-CN and DOP=2 incident probes passed without
reaching the
repeated-CN independent-probe domain. Do not interpret this PR as fully
fixing
or closing that incident/Issue #29642. PR #29643 is the already-deployed
Product
ownership fix; it is not the original incident's Issue number.

## Validation

Go 1.27.0; exact-base verified CGo artifacts; CPU 0/1, GOMAXPROCS=2 and
4GiB Go
memory budget. No production cluster or foreign service was touched.

These were run from the MatrixOne worktree with verified native
prerequisites.
The commands below are directly executable with the same Go/native
setup:

```sh
GOTOOLCHAIN=go1.27.0 GOMAXPROCS=2 GOMEMLIMIT=4GiB \
  .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -count=1 -timeout=180s ./pkg/sql/compile
GOTOOLCHAIN=go1.27.0 GOMAXPROCS=2 GOMEMLIMIT=4GiB \
  .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -race -count=1 -timeout=180s ./pkg/sql/compile
GOTOOLCHAIN=go1.27.0 GOMAXPROCS=2 GOMEMLIMIT=4GiB \
  .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -race \
  -run '^TestBroadcastHashJoinSharedProducerOwnership$' -count=2 -timeout=120s ./pkg/sql/compile
GOTOOLCHAIN=go1.27.0 GOMAXPROCS=2 GOMEMLIMIT=4GiB \
  .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -race \
  -run '^TestBroadcastLoopJoinSharedProducerOwnership$' -count=2 -timeout=120s ./pkg/sql/compile
```

Final narrowed production guard: normal compile package **PASS 7.224s**;
full compile package under `-race` **PASS 9.606s**; exact
HashJoin/LoopJoin
two repetitions **PASS 3.211s / 3.195s**. Before the guard was narrowed
to
these same Hash/Loop paths, each exact test was also adaptively stressed
29
times under race (1.02s measured test, 30s budget): **PASS 30.887s /
31.333s**.

Related runtime package checks were also run:

```sh
GOTOOLCHAIN=go1.27.0 GOMAXPROCS=2 GOMEMLIMIT=4GiB \
  .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -race -count=1 -timeout=180s \
  ./pkg/sql/colexec/hashbuild ./pkg/sql/colexec/hashjoin ./pkg/sql/colexec/loopjoin \
  ./pkg/sql/colexec/dispatch ./pkg/vm/message ./pkg/vm/pipeline ./pkg/vm/process
```

All seven packages **PASS** (1.973s, 11.624s, 1.676s, 1.316s, 1.219s,
1.188s and 2.262s respectively). This is supporting dependency evidence,
not a public remote-source performance test.

Official Main linter **v2.14.0, built with Go1.27.0** was run with
matching
Go1.27 PATH/GOROOT and repository CGo include/library paths:

```sh
GOTOOLCHAIN=go1.27.0 GOMAXPROCS=2 GOMEMLIMIT=4GiB GOWORK=off \
  CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
  CGO_LDFLAGS="-L$(pwd)/thirdparties/install/lib" \
  golangci-lint run --concurrency=2 --timeout=5m -c .golangci.yml ./pkg/sql/compile
git diff --check
```

Final narrowed version: linter **PASS, exit 0, 0 issues**;
`git diff --check` **PASS**. No older Go1.21 or golangci v2.6 tooling
was used
as a final gate. Detailed terminal evidence is retained locally.

Root additionally combined this patch with the independent minimal
vector
and catalogue patches (#29664 and #29662) in a temporary exact-base
worktree.
Full vector/mergeutil/compile/frontend package tests passed; the
authenticated
two-CN `TestIssue29414PublicationWaitsForPhysicalDatabaseDrop` public
SQL
consumer passed rollback, commit, replacement and cancellation (9.660s).
This checks composition and ordinary public SQL behavior; it is **not**
a
natural reproduction or a performance A/B of the special repeated-CN
domain.

---------

Co-authored-by: XuPeng-SH <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — 2db0311b Deployed Oct 6, 2026 by XuPeng-SH
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/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants