Shorten final hash join resource lifetimes [databricks] #16360
<!-- ccr-overview-v2 -->
🟢 Approval recommended
The supplied reviews support the ownership handoff, and reported validation covers the affected join paths with no blocking issues identified.
0 open findings
<details>
<summary><strong>What changed in this PR</strong></summary>
Shortens final hash-join resource lifetimes as part of #15997, preserving output ownership and ordering.
Changes:
| File | Description |
| ---- | ----------- |
| sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala | Shortens resource scopes around final-batch conversion. |
| scripts/with_resource_nesting_baseline.json | Removes the WR-034 fingerprint. |
| integration_tests/src/main/python/join_test.py | Adds zero-unmatched-row coverage for both build sides. |
</details>
🧠 Review effort: Balanced
---
💡 <a href="/NVIDIA/cudf-spark/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>
<!-- greptile_summary -->
<h2><a href="https://app.greptile.com/api/retrigger?id=81315897"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a><a href="https://app.greptile.com/nvidia-public-github/github/NVIDIA/cudf-spark/-/pull/16360"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img alt="View in Greptile" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2" align="right"></picture></a>Confidence Score: 5/5</h2>
[Medium impact] The reviewed changes appear safe to merge.
<h3>Summary</h3>
This PR releases outer hash join inputs before preparing the final output. It keeps filtering and null-column allocation inside retry blocks and skips batch conversion when no unmatched rows remain.
<h3>Diagram</h3>
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Stream batches exhausted] --> B[Filter unmatched build rows with retry]
B --> C[Release tracker and close stream iterator]
C --> D{Unmatched rows remain?}
D -->|No| E[Return no batch]
D -->|Yes| F[Retain filtered columns]
F --> G[Create null stream columns with retry]
G --> H[Return columns in build-side order]
<!-- greptile_confidence_score:5 -->
<sub>Reviews (14) · Last reviewed commit: "test: close untransferred hash join retr..." · Reviewed by Greptile</sub>
Optional: Would it be possible to close streamJoinIter earlier, once filteredTable owns the filtered columns, to further shorten resource lifetimes here? It currently keeps the original build batch referenced until getFinalBatch() returns, including while the null stream-side columns are allocated. This is pre-existing behavior, but seems worth considering within this cleanup.
For example, the two stages could be structured along these lines:
val builtTypes = built.dataTypes
val filteredTable = withResource(streamJoinIter) { _ =>
streamJoinIter.releaseBuiltSideTracker().map { tracker =>
val trackerTable = withResource(tracker) { scb =>
withResource(scb.getColumnarBatch()) { trackerBatch =>
GpuColumnVector.from(trackerBatch)
}
}
withResource(trackerTable) { trackerTab =>
withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
builtTable.filter(trackerTab.getColumn(0))
}
}
}
}
filteredTable.flatMap { table =>
val filteredBatch = withResource(table) { filtered =>
GpuColumnVector.from(filtered, builtTypes)
}
withResource(filteredBatch) { builtBatch =>
// Existing zero-row handling, null-column construction, and combineColumns logic.
}
}
The explicit streamJoinIter.close() after getFinalBatch() in hasNext would then be redundant. For callers passing a spill-only wrapper, this would allow the build data to spill rather than necessarily free it immediately.
<a href="#"><img alt="P0" src="https://greptile-static-assets.s3.amazonaws.com/badges/p0.svg?v=9" align="top"></a> Final batch allocations lack retry
getFinalBatch calls Table.filter and creates null GPU columns with GpuColumnVector.fromNull without withRetry or withRetryNoSplit. This violates the repository requirement that GPU memory allocations use an idempotent retry block with spillable inputs. Recoverable GPU memory pressure can therefore fail the join instead of letting it retry.
Keep tracker ownership outside the retry block, retry the allocating work, and close streamJoinIter after filtering succeeds.
Rule Used: GPU memory-allocating code must be wrapped in withRetry/withRetryNoSplit from RmmRapidsRetryIterator. The retry function must be idempotent. Input should be SpillableColumnarBatch before entering retry. (source)
<a href="#"><img alt="P0" src="https://greptile-static-assets.s3.amazonaws.com/badges/p0.svg?v=9" align="top"></a> Empty results bypass required cleanup
When no unmatched rows remain, the new branch calls filteredBatch.close() directly. The repository requires GPU resources to use withResource or closeOnExcept and forbids bare .close() calls. Replace this branch with withResource(filteredBatch) { _ => None } to satisfy the cleanup rule before merging.
withResource(filteredBatch) { _ => None }
Rule Used: GPU resources must use withResource() or closeOnExcept() from Arm.scala. Never use bare .close() on GPU resources. (source)
build
build
build
Do we need to protect tracker when built.checkpoint()?
Should this comment be placed at around line 2730?
[optional] We can early return None in withResource(filtered) to save a GpuColumnVector.from(filtered, builtTypes)
Some minor findings. And could we also update the pr descirption?
build
LGTM, thank you for addressing the comments
nit: Two small things here:
1. If streamJoinIter.close() throws, the filtered table that was just created is never closed. That's unlikely, but wrapping the result in closeOnExcept would prevent the leak.
2. This checkpoint/retry/allow-spilling block is the same as the one at line 1353. A small shared helper would keep the two copies from drifting apart. This is fine as a follow-up.
nit: Closing the stream iterator used to happen outside this timer. Now it happens inside, so it counts toward joinTime. Probably fine, just noting the metric change.
In the MATCHED case every row matches, so the final batch is always empty and the new retry code never runs. The retry code was only tested by hand. Could you add a test that forces an out-of-memory retry here for both build sides? It would help to include a join with a condition and a stream side with more than one batch.
build
build
build
build
build
Thanks, updated.
Confirmed: iterator cleanup is now included in joinTime; this is documented in the PR description.
Updated. The shared-helper extraction remains a follow-up, as suggested.
Updated.
build
build
No test fails if this retry is removed. I replaced withRetryNoSplit here with a plain withResource, and all 13 tests in GpuShuffledHashJoinExecSuite and all 8 cases of test_distinct_full_outer_join still passed. The Scala retry tests only throw from tracker.getColumnarBatch(), which is in the first retry block. The inject_oom marker does reach this block, but it only injects inside retry blocks that already exist, so it can't notice one going missing. Removing withRestoreOnRetry(built) at line 2739 isn't caught either.
Could you add a test that forces a retry OOM inside this block (for example RmmSpark.forceRetryOOM with a skip count) for both build sides? It should check that a retry happened, that the output is correct, and that nothing leaks. A verify on built.checkpoint(), restore() and allowSpilling() would cover line 2739 as well.
nit: #16440 has merged, so this key reordering is no longer needed. This is now the only record whose key order differs from what --print-baseline generates, so the next --update-baseline will flip it back. I merged the PR with current main and the nesting audit passes either way. Could you drop the reordering?
nit: The MATCHED label is misleading in the CONDITION variant. Key 1 fails 1 + 1 > 2, so that case does produce unmatched build rows. Only MATCHED-EQUI reaches the path where no unmatched rows remain. Maybe rename the ids, for example ALL_KEYS_MATCH and SOME_KEYS_UNMATCHED, or add a comment.
build
build
Updated.
build
nit: trackerBatch is created outside any resource scope, and ownership only moves to the code under test on the second getColumnarBatch() call. If a regression drops the tracker retry, the GpuRetryOOM escapes on the first call. The test still fails as it should, but trackerBatch is never closed, so the run also logs LEAKED errors from the test itself and leaks GPU memory into the tests that follow. Could you close it in a finally when it wasn't handed over, for example when getColumnarBatch() was called fewer than two times? Separately, an Rmm.getTotalBytesAllocated == baseline check, like the other two new tests have, would catch leaks on passing runs.
LGTM
build
build
LGTM
gerashegalov
wjxiz1992
JaCoCo production line coverage: +31 lines (
sql-plugin +31; Spark 3.3/shim 330, maina97083ad; single final Maven run, 31/48 added production lines covered; other JVM modules have no added production lines in this PR)Contributes to #15997 (package 14, WR-034).
Description
This resource-lifetime refactor releases outer hash join inputs before preparing the final output batch, reducing their overlap with output preparation. It also closes resources if checkpointing or iterator cleanup fails and avoids creating a batch when no unmatched build rows remain. Successful joins retain the same rows and column order.
Nonebefore batch conversion when filtering leaves no unmatched build rows; preserve retained references and iterator ownership for nonempty output.joinTimeincludes stream-iterator cleanup during finalization. The WR-034 nesting-baseline entry is removed; the resource audit passes without adding a baseline exception.AI assistance: The changes and PR description were prepared with AI assistance.
Validation
Latest test cleanup follow-up (
2e93c8d3d):GpuRetryOOM, with zeroLEAKEDdiagnostics. The production source was restored byte-for-byte before the final passing run.Previously recorded review follow-up, after merging main
a97083ad:mvn package -pl tests -am -Dbuildver=330withGpuShuffledHashJoinExecSuite, a worktree-local Maven cache, and all three GPU allocation limits: 15 Scala tests succeeded, 0 failed, plus 13 Java tests passed; all 18 reactor modules passed on the final formatted source.checkpoint(),restore(), andallowSpilling().GpuRetryOOM; removing build-state restoration makes exactly the two filter-retry tests fail at therestore()verification. Each mutation was restored before final validation, and the final suite passed again.join_test.py::test_distinct_full_outer_join --test_oom_injection_mode=always: 8 passed, comparing CPU/GPU rows and requiring the GPU hash-join plan. Dataset ids now describe whether all input keys have matches, including the separate residual-condition dimension.install_deps.pyfrom main. It now points tobuild/gen-spark-home-deps.pyand describes the runtime dependency BOM. Local CI-pinned Lychee 0.24.2 validation of tracked Markdown, using the repository configuration in offline mode, passed with zero link errors.mvn verify -N -DskipTests: BUILD SUCCESS. Style checked 2,026 files with zero errors/warnings; license and resource checks passed. Nesting audit: 23 baseline entries; checker unit tests: 32 passed. Python compilation andgit diff --checkpassed.sql-pluginhas added JVM production lines in this PR.<details>
<summary>Previously recorded validation on earlier PR heads</summary>
spark.sql.ansi.enabled=falseso its residual integer addition can execute in GPU AST on runtimes whose default is ANSI mode. With a session default of ANSI enabled, the predecessor reproduced all four conditional CPU-fallback failures locally; the corrected test passed all 8 CPU/GPU cases with forced OOM injection and the GPU hash-join assertion enabled. This changes only the test configuration. Matching Databricks confirmation is pending CI.mvn package -pl tests -am -Dbuildver=330withGpuShuffledHashJoinExecSuite,BroadcastHashJoinSuite, andJoinsSuite, a worktree-local Maven cache, and GPU allocation limits: 54 Scala tests succeeded, 0 failed, plus 9 Java tests passed; all 18 reactor modules passed.f3dc60c1dclass with 12 bytes left allocated, and passes with the fix. The checkpoint-failure regression also passes. Two deterministic final-filter retry tests injectGpuRetryOOM, verify a second attempt, and check retained build values and null stream columns for both build sides.join_test.py::test_distinct_full_outer_join, with--test_oom_injection_mode=always: 8 passed. Every case requests OOM injection and compares CPU/GPU rows with a GPU shuffled-hash-join plan assertion. The matrix covers both build sides, matched/unmatched keys, an additional join condition that rejects an equi-key match, and multiple stream batches. The condition dimension doubles the prior four-case matrix.mvn verify -N -DskipTests: BUILD SUCCESS, including style (1,951 files, zero errors/warnings), license, and resource checks.git diff --checkand Python compilation passed.</details>
Performance
The current review follow-up changes tests, baseline formatting, and the dependency-documentation paragraph only; it adds no production runtime work. Main was merged to retain canonical baseline formatting without reintroducing a conflict.
For the earlier iterator-cleanup review update, the successful finalization path adds one JVM exception guard around the same iterator close, once per finalization. It adds no GPU allocation, kernel, data copy, synchronization, or per-row work. Filtering, null-column allocation, and their retry boundaries are unchanged by this update. This is a source-based impact analysis; the earlier-head timings below were not rerun for this cleanup guard.
<details>
<summary>Previously recorded performance measurements on earlier PR heads</summary>
In the preceding review update, PR head
de30e6bceand candidatef3dc60c1dwere compared on the local RTX 5880 Ada with Spark 3.3: a shuffled full outer join over 10 million rows per input, two partitions, both fully matched and partially unmatched inputs. Each trial creates a fresh execution plan, verifies that the GPU hash join actually executed, and checks an independently calculated row count and checksum. Runs alternated base/candidate/base/candidate, with two warmups and eight timed trials per scenario in each run.| Scenario | Base run medians | Final-source run medians |
|---|---|---|
| Fully matched, 10M output rows | 863.20 / 846.30 ms | 849.28 / 852.99 ms |
| Partially unmatched, 15M output rows | 837.82 / 831.53 ms | 832.00 / 837.67 ms |
Trial ranges overlap. This sample does not establish a throughput or peak-memory improvement; the intended effect remains earlier input-resource release and avoiding empty-batch conversion.
<details>
<summary>Earlier PR-level performance evidence</summary>
The previous description recorded an exact-base/candidate Spark 3.3 comparison over 1M rows per input, with identical 1.5M-row results and GPU plans: base run medians 81.99/84.10 ms and candidate medians 91.21/83.68 ms. Those historical warmed-query timings are retained for context; the fresh-plan comparison above is the current review-update measurement.
</details>
</details>
Main-branch integration
#16440 has merged. This branch now includes main
a97083ad; baseline key order matches the checker output, and the final audit retains all 23 records required by the merged source.Checklists
Documentation
Testing
(Please provide the names of the existing tests in the PR description.)
Performance