Skip to content

fix join spill ownership and lifecycle - #26412

Merged
XuPeng-SH merged 10 commits into
mainfrom
agent/systematic-join-spill-lifecycle
Jul 30, 2026
Merged

XuPeng-SH merged 10 commits into
mainfrom
agent/systematic-join-spill-lifecycle

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed

  • Replace split spill files / FD tokens / budget references on JoinMap with one atomic move-only SpillBuildPayload, and migrate hashjoin, dedupjoin, and rightdedupjoin consumers.
  • Reject invalid or shared spill publication and make Take / FreeMemory cleanup race-safe and exactly-once.
  • Scope bitmap channels, DedupJoin mailboxes, generated parallel scopes, and borrowed spill file services to one execution generation.
  • Propagate previously ignored join output failures; restore Dedup UPDATE vector ownership on error; put RightDedup probe-only hashmaps under the shared build budget.
  • Add cancellation checks at hash-build, spill record, physical I/O, rebuild, iterator, probe-read, and final bucket-flush boundaries.
  • Cache SpillEngine file-service resolution, skip semantically unused build-only buckets, preserve explicit remote spill thresholds, and bound spill FD admission against runtime RLIMIT_NOFILE.
  • Make reduced spill fanout correct: validate 1..32 power-of-two fanout before consuming probe input and partition probes using the build payload's actual fanout.
  • Fix DedupJoin multi-bucket finalize state so a worker reset between rounds publishes an abort for the next round instead of leaving the merger blocked forever.
  • Treat a 1..15 byte trailing frame header as corruption, and release an empty decoded build's builder before handing its probe file to the caller.
  • Validate compiler-real DedupJoin UPDATE map shapes, legacy payload budget identity, and pre-cancel FD ownership with end-to-end operator and live-resource tests.

Why

Issue #26408 exposed a split-ownership protocol shared by hashjoin, dedupjoin, and rightdedupjoin. The normal broadcast topology currently cannot produce that payload because non-shuffle HashBuild never spills, so the reported shared-broadcast failure is latent rather than normally reachable. The production-visible design gap is broader: broadcast joins have no spill fallback, while the existing spill path also had ownership, generation reuse, error propagation, cancellation, memory-budget, file-descriptor, file-corruption, and multi-round lifecycle weaknesses.

This PR closes the unsafe cross-join protocol and the concrete reachable unhappy paths without pretending to implement a broadcast spill scheduler or redesign the on-disk format in the same patch.

First-principles closure

  • Q1 — cleanup: every file, FD token, disk token, memory reservation, decoded batch, capture vector, generated scope, and result vector has one terminal owner on success, error, cancellation, Reset, and publication loss.
  • Q2 — termination: waits observe context or an explicit terminal mailbox/channel status; physical I/O is checked immediately before entry; DedupJoin publishes one status per worker per finalize round.
  • Q3 — boundedness: memory/disk/FD admission is finite, recursive passes and queue depth are bounded, invalid fanout fails before child consumption, and cancellation polls remain at batch/record/I/O boundaries rather than per row.

Real and unhappy-path validation

  • A canceled initial spill writes to a real physical file and proves file size, spill bytes, and spill rows all remain zero.
  • A real one-bucket build payload scatters 1,000 probe rows and proves exact row conservation; 0/3/33 buckets fail before reading child input.
  • A real two-record spill stream cancels at the second frame boundary and proves the second payload is never decoded and all batch/token memory is released.
  • A real valid record plus a partial trailing header returns io.ErrUnexpectedEOF, clears the decoded destination and reservation, and returns budget usage to zero.
  • A two-round DedupJoin mailbox reproduces normal worker early-stop between spill buckets and proves Reset publishes the nil-error abort required to terminate the merger.
  • An empty physical build file uses a constant-key executor that owns mpool memory at Prepare time; both keep-probe and skip-probe branches return CurrNB to baseline and zero memory/disk/FD ledgers.
  • A real HashBuild -> JoinMap -> DedupJoin UPDATE pipeline covers compact and duplicate GroupSels maps, matched and unmatched-finalize paths, emitted value/NULL semantics, vector-owner restoration, and terminal mpool=0.
  • Legacy payload transfer proves the consumer receives the exact process budget generation and that the moved FD is released once; pre-cancel reader/writer/scatter/probe/re-spill tests use live tracked FDs to prove retain-on-cancel and release-on-cleanup.
  • Real capped-budget hashjoin initial spill plus re-spill passes 10/10 with row conservation; local guardrail time was 0.57–0.80 s total, depending on concurrent load.
  • A checked-in 4,096-row embedded-cluster SQL regression generates a real optimizer range-shuffle plan on one runtime bucket, executes resident and constrained-spill variants through the MySQL protocol, requires positive SpillRows / SpillSize plus depth-1 spill and depth-2 re-spill metrics, and proves the skewed equal-key batch neither panics nor loses rows.

Spill regression test plan

BVT remains the minimum SQL correctness and plan smoke layer; this PR does not add a large spill dataset to BVT. Spill correctness is covered by a parameterized regression job in which data size is an input, not a correctness oracle.

Harness and scale contract

  • Generate deterministic physical build/probe tables from a seed and a configurable scale N. CI, nightly, and soak jobs may use different N, DOP, and CN counts; expected results are derived from the generated keys and are never hard-coded to a particular row count.
  • The checked-in presubmit SQL case defaults to N=4096 and accepts only 1024 <= N <= 65536. The upper bound protects CI hosts from accidental OOM; larger nightly/soak scales belong in a dedicated external harness rather than BVT or this presubmit test.
  • Run each semantic case twice against the same data snapshot: once with a resident-memory configuration as the reference, and once with a constrained spill configuration.
  • Require EXPLAIN to contain the intended join and shuffle topology. A spill run passes only when EXPLAIN ANALYZE reports SpillRows > 0 and SpillSize > 0; a query that happens not to spill is unexercised, not passed.
  • Trigger spill primarily by constraining the admitted working set relative to the generated data. Increasing N is optional, so the regression can run at any practical data scale.
  • For re-spill cases, require an explicit spill-depth/round metric greater than one when available; until then, require SpillRows to exceed the computed single-pass build-plus-probe row total. The comparison uses generated row counts, not a fixed constant.

Required coverage

  1. HashJoin semantics: INNER, LEFT, RIGHT, FULL, SEMI, ANTI, and MARK joins; uniform and highly skewed keys; matched, unmatched, duplicate, and NULL keys. Cover signed and unsigned integers, strings, expression keys, and supported composite keys.
  2. Range-shuffle regression: generate a real join plan containing the Shuffle operator and execute highly skewed integer batches. With one runtime bucket, verify constant/equal/ordered batches do not panic or lose rows and all rows reach bucket 0. With multiple buckets and no effective sampled boundary, verify the min/max fallback distributes every row. Exercise signed, unsigned, NULL, expression, and zonemap consumers so an empty boundary is never treated as an enabled sampled range.
  3. Initial spill and recursive re-spill: exercise build spill, probe scatter, bucket rebuild, multiple spill rounds, and the maximum-depth path. Verify successful cases against the resident reference and verify the depth limit returns a controlled error with complete cleanup.
  4. DML and dedup operators: run INSERT ... ON DUPLICATE KEY UPDATE for primary-key-only and multiple-UNIQUE targets, including mixed matched/new rows and UPDATE expressions that reference nullable or absent source columns. Cover INSERT IGNORE, REPLACE, and RightDedup where their execution topology supports spill. Compare final table contents, affected rows, PK/UK cardinalities, NULL results, and duplicate rejection with the resident run.
  5. Lifecycle and unhappy paths: cancel before spill-file creation, during scatter/write/read/rebuild, and between buckets; repeat prepared executions and operator reset/reuse; inject truncated/corrupt frames and constrained disk/FD budgets. Assert bounded completion, no partial output, no double cleanup, zero live spill files, and memory/disk/FD ledgers returning to baseline.
  6. Topology matrix: cover one and multiple shuffle buckets, reduced fanout, one CN, and multi-CN where the test environment supports it. Broadcast topology remains an explicit capability test: until it has a scheduler path for spill, it must stay resident or fail fast rather than silently claiming spill coverage.

Correctness oracles and execution tiers

  • The resident and spill runs must have identical row counts, stable-key checksums, grouped multiplicities, NULL/unmatched-row counts, and DML final tables. These checks detect loss and duplication without depending on result order.
  • The SQL-level range-shuffle case is the final regression for the empty-boundary panic; focused signed/unsigned/zonemap tests enforce the shared boundary contract below it.
  • Presubmit runs a small deterministic scale and the focused contract tests. Nightly varies scale, seed, skew, DOP, and topology. Soak adds repeated execution, cancellation, and resource-pressure cases.
  • Exit criteria are: the intended plan was generated, spill/re-spill was observed rather than inferred, output matches the resident oracle, and all resources are reclaimed without panic or hang.

Test matrix

  • Full tests and full -race runs pass for vm/message, vm/process, hashbuild, spillutil, hashjoin, dedupjoin, and rightdedupjoin.
  • TestIssue26408JoinSpillSQLRegression passes at the default 4,096-row scale, passes two consecutive focused -race runs, and its full owning pkg/tests/issues package passes -race; the test-only CGo compile and go vet -mod=readonly checks are clean.
  • Fourteen representative changed contracts were enumerated with go test -list, measured once under -race -json, then repeated with N=clamp(floor(30/T),1,100): the RLIMIT test ran 26 times from a 1.14 s sample; the other 13 ran 100 times each.
  • Affected compile topology, generation, mailbox/channel, and remote-threshold tests pass together under -race.
  • Full compile -race has exactly three Parquet empty-file fanout failures. The same three tests fail with the same assertions on a clean latest origin/main worktree at 2e68774061; they are not introduced by this PR.
  • The official current-head CI coverage merge passes at 291/376 changed blocks = 77.39% (approved=true, 75% threshold); the local affected-package-only profile was 285/375 = 76.00% before CI added cross-package UT/BVT profiles.
  • go vet and go build pass for all eight affected packages. Final CGo-wrapper compile checks, make err-check, and git diff --check are clean.

Performance evidence

For 8,192 build rows / 9,216 probe rows with initial spill and re-spill:

  • Shared file-service resolution reduces the hot path from roughly one resolution per create (~2,079) to two per engine.
  • The two-pass bucket classifier is about 8.14 µs per 8,192 rows with zero allocations versus about 105.5 µs for the legacy bucket-by-bucket row scan (~12.9x).
  • End-to-end remains roughly 57–80 ms/run under local load and about 85.7 MB allocated/run. File creation is still the dominant unresolved cost: about 2.1k creates/engine, with create sampled at roughly 38% CPU and scatter append/copy accounting for about 65.8 MB.
  • New cancellation checks are per batch/record/I/O boundary; fanout validation is O(1); no new admission or polling was added to row-at-a-time hash/probe loops.

Risks and follow-ups

  • Broadcast HashBuild still has no shared spill scheduler/rebuild task and remains fail-fast for multi-consumer spill.
  • Expression executors can retain a high-capacity result vector after a later small batch replaces/releases the corresponding budget charge; executor and reservation lifetime need one owner.
  • Anonymous create-and-unlink partition files force queued buckets to retain open FDs. Named/reopenable partition handles, active-window FD accounting, adaptive fanout, and skew-aware terminal fallback require a separate design.
  • Spill frames have structural checks but no version/checksum; already-started os.File.Read, os.File.Write, and unmarshal calls cannot be interrupted by context.
  • Resident and spill equality still need one typed-key canonicalization layer; known risk cases include DOUBLE +0/-0, NaN, JSON numeric forms, scaled FLOAT, and long VECF32 keys.
  • join_spill_mem still overloads values <=100000 as rows and larger values as bytes; explicit versioned units and migration are needed.
  • Removing the old exported split spill fields/APIs is a source-compatibility change; all in-repository callers are migrated.

Closes #26408.

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

Codex automated review

No actionable findings. Existing PR reviews and inline comments contain no reviewer findings. I traced ownership transfer, cancellation, mailbox, generation-reuse, range-shuffle, budget/FD, and error paths. Local package tests could not start because required CGo artifacts/headers are absent; no state was changed.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the latest changes, including spill payload ownership, cancellation/error cleanup, multi-round lifecycle, reuse-generation isolation, and the SQL regression coverage. No blocking issues 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

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: parallel broadcast dedupjoin/hashjoin spill consumers lose bucket ownership or wait forever

4 participants