← Back to Pull requests

Shorten final hash join resource lifetimes [databricks] #16360

Merged
wjxiz1992 merged 4 files (283 lines) on Oct 26, 2026 19:25 UTC
View on GitHub
wjxiz1992 wjxiz1992 commented on Oct 15, 2026 07:46 UTC
Author

JaCoCo production line coverage: +31 lines (sql-plugin +31; Spark 3.3/shim 330, main a97083ad; 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.

  • Finish filtering before converting the owning filtered table into output columns. Release the stream iterator, tracker, and input wrappers between those stages, protecting the filtered output if iterator cleanup throws.

  • Protect the checkpoint-to-retry ownership handoff, and keep filtering and null-column allocation inside spill-aware retry scopes.

  • Return None before batch conversion when filtering leaves no unmatched build rows; preserve retained references and iterator ownership for nonempty output.
  • joinTime includes 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):

  • The filtering-retry regression tests close their preallocated tracker batch if a failing retry never transfers ownership, and check that RMM allocation returns to baseline for both build sides. This follow-up changes tests only.

  • Final Spark 3.3 Maven package run: 15 Scala tests succeeded, 0 failed, 13 Java tests passed, and all 18 reactor modules succeeded. Root verification passed style checks on 2,027 files with zero errors/warnings, plus license and resource checks.

  • Removing the tracker retry temporarily made exactly the two filtering-retry tests fail with GpuRetryOOM, with zero LEAKED diagnostics. The production source was restored byte-for-byte before the final passing run.
  • Previously recorded review follow-up, after merging main a97083ad:

  • Spark 3.3: mvn package -pl tests -am -Dbuildver=330 with GpuShuffledHashJoinExecSuite, 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.

  • Both build sides now force one native retry OOM after filtering and before null stream-column allocation, verify the retry count, check build values and null output columns, and assert that RMM allocation returns to its baseline. The filter-retry tests also verify checkpoint(), restore(), and allowSpilling().

  • Independent negative checks: replacing the second retry scope with plain resource cleanup makes exactly the two new allocation-retry tests fail with GpuRetryOOM; removing build-state restoration makes exactly the two filter-retry tests fail at the restore() verification. Each mutation was restored before final validation, and the final suite passed again.

  • Spark 3.3/Python 3.10: 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.

  • CI documentation follow-up: the DBR 18.3 README inherited a link to the removed install_deps.py from main. It now points to build/gen-spark-home-deps.py and 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.

  • Distribution/integration-test package build and root 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 and git diff --check passed.

  • Fresh JaCoCo fix-line measurement uses the complete final PR diff, one final Maven execution file, and 3,885 production classfiles selected from the actual test runtime classpath. It covers 31/48 added production lines with no class-ID mismatch. Only sql-plugin has added JVM production lines in this PR.
  • <details>
    <summary>Previously recorded validation on earlier PR heads</summary>

  • CI follow-up: the final-output regression explicitly sets spark.sql.ansi.enabled=false so 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.

  • Spark 3.3: mvn package -pl tests -am -Dbuildver=330 with GpuShuffledHashJoinExecSuite, BroadcastHashJoinSuite, and JoinsSuite, 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.

  • The new iterator-cleanup regression fails against the predecessor f3dc60c1d class with 12 bytes left allocated, and passes with the fix. The checkpoint-failure regression also passes. Two deterministic final-filter retry tests inject GpuRetryOOM, verify a second attempt, and check retained build values and null stream columns for both build sides.

  • Spark 3.3/Python 3.10: 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.

  • Final distribution and integration-test package build: BUILD SUCCESS. Root mvn verify -N -DskipTests: BUILD SUCCESS, including style (1,951 files, zero errors/warnings), license, and resource checks. git diff --check and 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 de30e6bce and candidate f3dc60c1d were 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

  • Updated for new or modified user-facing features or behaviors

  • No user-facing change
  • Testing

  • Added or modified tests to cover new code paths

  • Covered by existing tests

  • (Please provide the names of the existing tests in the PR description.)
  • Not required
  • Performance

  • Tests ran and results are added in the PR description

  • Issue filed with a link in the PR description

  • Not required
  • Diff: 283 lines (+235 / -48) across 4 files Reviewer: gerashegalov Review duration: 16538m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.41) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.41 · 283 lines diff across 4 files
    0.41
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.78 · 5 substantive comment(s)
    0.78
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.338
    Real PR Conversation Timeline
    41 items
    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 15, 2026 07:49 UTC
    Reviewer

    <!-- 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:

  • Releases tracker and input wrappers before output-batch conversion.

  • Extends full outer join tests across both build sides and matched/unmatched cases.

  • Removes the resolved nesting-baseline entry.
  • | 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-apps[bot] greptile-apps[bot] commented on Oct 15, 2026 07:49 UTC
    Bot

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

  • Full outer joins release filtering resources before building their final batch.
  • <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>

    thirtiseven thirtiseven commented on code on Oct 15, 2026 10:06 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2732,18 +2732,22 @@ class HashOuterJoinIterator(
           streamJoinIter.releaseBuiltSideTracker() match {
             case None => None
             case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    +          val (filteredTable, builtTypes) = withResource(tracker) { _ =>
    +            withResource(tracker.getColumnarBatch()) { trackerBatch =>
                   withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
                     val batch = built.getBatch
    +                val builtTypes = GpuColumnVector.extractTypes(batch)
                     withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    -                  }
    +                  (builtTable.filter(trackerTab.getColumn(0)), builtTypes)
                     }
                   }
                 }
               }
    +          // filter returns an owning table. Release the tracker and input table wrappers before
    +          // retaining the filtered columns in the output batch.
    +          val filteredBatch = withResource(filteredTable) { _ =>

    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.

    greptile-apps[bot] greptile-apps[bot] commented on code on Oct 15, 2026 11:13 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,47 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    -                  }
    -                }
    -              }
    +      val builtTypes = built.dataTypes
    +      val filteredTable = withResource(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          val trackerTable = withResource(tracker) { _ =>
    +            withResource(tracker.getColumnarBatch()) { trackerBatch =>
    +              GpuColumnVector.from(trackerBatch)
                 }
               }
    -          // Combine build-side columns with null columns for stream side
    -          withResource(filteredBatch) { builtBatch =>
    -            val numFilterRows = builtBatch.numRows()
    -            if (numFilterRows > 0) {
    -              val streamColumns = streamAttributes.safeMap { attr =>
    -                GpuColumnVector.fromNull(numFilterRows, attr.dataType)
    -              }
    -              withResource(new ColumnarBatch(streamColumns.toArray, numFilterRows)) { streamBatch =>
    -                buildSide match {
    -                  case GpuBuildRight =>
    -                    Some(GpuColumnVector.combineColumns(streamBatch, builtBatch))
    -                  case GpuBuildLeft =>
    -                    Some(GpuColumnVector.combineColumns(builtBatch, streamBatch))
    -                }
    +          withResource(trackerTable) { _ =>
    +            withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
    +              builtTable.filter(trackerTable.getColumn(0))

    <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)

    greptile-apps[bot] greptile-apps[bot] commented on code on Oct 15, 2026 11:29 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,60 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      val filteredTable = withResource(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          built.checkpoint()
    +          try {
    +            withRetryNoSplit(tracker) { trackerAttempt =>
    +              withRestoreOnRetry(built) {
    +                withResource(trackerAttempt.getColumnarBatch()) { trackerBatch =>
    +                  withResource(GpuColumnVector.from(trackerBatch)) { trackerTable =>
    +                    withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
    +                      builtTable.filter(trackerTable.getColumn(0))
    +                    }
                       }
                     }
                   }
                 }
    +          } finally {
    +            built.allowSpilling()
    +          }
    +        }
    +      }
    +
    +      filteredTable.flatMap { filtered =>
    +        // filter returns an owning table. Release the stream iterator, tracker, and input table
    +        // wrappers before retaining the filtered columns in the output batch.
    +        val filteredBatch = withResource(filtered) { _ =>
    +          GpuColumnVector.from(filtered, builtTypes)
    +        }
    +        val numFilterRows = filteredBatch.numRows()
    +        if (numFilterRows > 0) {
    +          val spillableFiltered = closeOnExcept(filteredBatch) {
    +            SpillableColumnarBatch(_, SpillPriorities.ACTIVE_ON_DECK_PRIORITY)
               }
               // Combine build-side columns with null columns for stream side
    -          withResource(filteredBatch) { builtBatch =>
    -            val numFilterRows = builtBatch.numRows()
    -            if (numFilterRows > 0) {
    +          Some(withRetryNoSplit(spillableFiltered) { filteredAttempt =>
    +            withResource(filteredAttempt.getColumnarBatch()) { builtBatch =>
                   val streamColumns = streamAttributes.safeMap { attr =>
                     GpuColumnVector.fromNull(numFilterRows, attr.dataType)
                   }
    -              withResource(new ColumnarBatch(streamColumns.toArray, numFilterRows)) { streamBatch =>
    -                buildSide match {
    -                  case GpuBuildRight =>
    -                    Some(GpuColumnVector.combineColumns(streamBatch, builtBatch))
    -                  case GpuBuildLeft =>
    -                    Some(GpuColumnVector.combineColumns(builtBatch, streamBatch))
    -                }
    +              withResource(new ColumnarBatch(streamColumns.toArray, numFilterRows)) {
    +                streamBatch =>
    +                  buildSide match {
    +                    case GpuBuildRight =>
    +                      GpuColumnVector.combineColumns(streamBatch, builtBatch)
    +                    case GpuBuildLeft =>
    +                      GpuColumnVector.combineColumns(builtBatch, streamBatch)
    +                  }
                   }
    -            } else {
    -              None
                 }
    -          }
    +          })
    +        } else {
    +          filteredBatch.close()
    +          None

    <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)

    wjxiz1992 wjxiz1992 commented on Oct 16, 2026 07:13 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 16, 2026 08:33 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 16, 2026 16:49 UTC
    Author

    build

    thirtiseven thirtiseven commented on code on Oct 19, 2026 01:54 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,59 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      val filteredTable = withResource(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          built.checkpoint()

    Do we need to protect tracker when built.checkpoint()?

    thirtiseven thirtiseven commented on code on Oct 19, 2026 01:57 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,59 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      val filteredTable = withResource(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          built.checkpoint()
    +          try {
    +            withRetryNoSplit(tracker) { trackerAttempt =>
    +              withRestoreOnRetry(built) {
    +                withResource(trackerAttempt.getColumnarBatch()) { trackerBatch =>
    +                  withResource(GpuColumnVector.from(trackerBatch)) { trackerTable =>
    +                    withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
    +                      builtTable.filter(trackerTable.getColumn(0))
    +                    }
                       }
                     }
                   }
                 }
    +          } finally {
    +            built.allowSpilling()
    +          }
    +        }
    +      }
    +
    +      filteredTable.flatMap { filtered =>
    +        // filter returns an owning table. Release the stream iterator, tracker, and input table

    Should this comment be placed at around line 2730?

    thirtiseven thirtiseven commented on code on Oct 19, 2026 02:04 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,59 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      val filteredTable = withResource(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          built.checkpoint()
    +          try {
    +            withRetryNoSplit(tracker) { trackerAttempt =>
    +              withRestoreOnRetry(built) {
    +                withResource(trackerAttempt.getColumnarBatch()) { trackerBatch =>
    +                  withResource(GpuColumnVector.from(trackerBatch)) { trackerTable =>
    +                    withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
    +                      builtTable.filter(trackerTable.getColumn(0))
    +                    }
                       }
                     }
                   }
                 }
    +          } finally {
    +            built.allowSpilling()
    +          }
    +        }
    +      }
    +
    +      filteredTable.flatMap { filtered =>
    +        // filter returns an owning table. Release the stream iterator, tracker, and input table
    +        // wrappers before retaining the filtered columns in the output batch.
    +        val filteredBatch = withResource(filtered) { _ =>
    +          GpuColumnVector.from(filtered, builtTypes)
    +        }
    +        val numFilterRows = filteredBatch.numRows()
    +        if (numFilterRows > 0) {
    +          val spillableFiltered = closeOnExcept(filteredBatch) {
    +            SpillableColumnarBatch(_, SpillPriorities.ACTIVE_ON_DECK_PRIORITY)
               }
               // Combine build-side columns with null columns for stream side
    -          withResource(filteredBatch) { builtBatch =>
    -            val numFilterRows = builtBatch.numRows()
    -            if (numFilterRows > 0) {
    +          Some(withRetryNoSplit(spillableFiltered) { filteredAttempt =>
    +            withResource(filteredAttempt.getColumnarBatch()) { builtBatch =>
                   val streamColumns = streamAttributes.safeMap { attr =>
                     GpuColumnVector.fromNull(numFilterRows, attr.dataType)
                   }
    -              withResource(new ColumnarBatch(streamColumns.toArray, numFilterRows)) { streamBatch =>
    -                buildSide match {
    -                  case GpuBuildRight =>
    -                    Some(GpuColumnVector.combineColumns(streamBatch, builtBatch))
    -                  case GpuBuildLeft =>
    -                    Some(GpuColumnVector.combineColumns(builtBatch, streamBatch))
    -                }
    +              withResource(new ColumnarBatch(streamColumns.toArray, numFilterRows)) {
    +                streamBatch =>
    +                  buildSide match {
    +                    case GpuBuildRight =>
    +                      GpuColumnVector.combineColumns(streamBatch, builtBatch)
    +                    case GpuBuildLeft =>
    +                      GpuColumnVector.combineColumns(builtBatch, streamBatch)
    +                  }
                   }
    -            } else {
    -              None
                 }
    -          }
    +          })
    +        } else {
    +          withResource(filteredBatch) { _ => None }

    [optional] We can early return None in withResource(filtered) to save a GpuColumnVector.from(filtered, builtTypes)

    thirtiseven thirtiseven commented on Oct 19, 2026 02:08 UTC
    Reviewer

    Some minor findings. And could we also update the pr descirption?

    wjxiz1992 wjxiz1992 commented on Oct 19, 2026 02:45 UTC
    Author

    build

    thirtiseven thirtiseven commented on Oct 19, 2026 02:53 UTC
    Reviewer

    LGTM, thank you for addressing the comments

    gerashegalov gerashegalov commented on code on Oct 19, 2026 05:50 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,63 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      // filter returns an owning table. Release the stream iterator, tracker, and input table
    +      // wrappers before retaining the filtered columns in the output batch.
    +      val filteredTable = withResource(streamJoinIter) { _ =>

    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.

    gerashegalov gerashegalov commented on code on Oct 19, 2026 05:50 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,63 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {

    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.

    gerashegalov gerashegalov commented on code on Oct 19, 2026 05:50 UTC
    Code Review
    integration_tests/src/main/python/join_test.py:1
    @@ -1657,18 +1659,16 @@ def test_distinct_full_outer_join(build_side):
         }
     
         def do_join(spark):
    -        left_df = spark.createDataFrame([
    -            (None, "left_null"),
    -            (1, "left_match"),
    -            (2, "left_only"),
    -            (4, "left_match_2"),
    -        ], ["join_key", "left_value"])
    -        right_df = spark.createDataFrame([
    -            (None, "right_null"),
    -            (1, "right_match"),
    -            (3, "right_only"),
    -            (4, "right_match_2"),
    -        ], ["join_key", "right_value"])
    +        if unmatched_build_rows:
    +            left_rows = [(None, "left_null"), (1, "left_match"),
    +                         (2, "left_only"), (4, "left_match_2")]
    +            right_rows = [(None, "right_null"), (1, "right_match"),
    +                          (3, "right_only"), (4, "right_match_2")]
    +        else:
    +            left_rows = [(1, "left_match"), (2, "left_match_2")]

    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.

    wjxiz1992 wjxiz1992 commented on Oct 19, 2026 06:40 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 19, 2026 11:16 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 19, 2026 12:37 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 19, 2026 13:51 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 19, 2026 16:25 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on code on Oct 21, 2026 07:56 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2732,18 +2732,22 @@ class HashOuterJoinIterator(
           streamJoinIter.releaseBuiltSideTracker() match {
             case None => None
             case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    +          val (filteredTable, builtTypes) = withResource(tracker) { _ =>
    +            withResource(tracker.getColumnarBatch()) { trackerBatch =>
                   withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
                     val batch = built.getBatch
    +                val builtTypes = GpuColumnVector.extractTypes(batch)
                     withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    -                  }
    +                  (builtTable.filter(trackerTab.getColumn(0)), builtTypes)
                     }
                   }
                 }
               }
    +          // filter returns an owning table. Release the tracker and input table wrappers before
    +          // retaining the filtered columns in the output batch.
    +          val filteredBatch = withResource(filteredTable) { _ =>

    Thanks, updated.

    wjxiz1992 wjxiz1992 commented on code on Oct 21, 2026 07:56 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,63 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {

    Confirmed: iterator cleanup is now included in joinTime; this is documented in the PR description.

    wjxiz1992 wjxiz1992 commented on code on Oct 21, 2026 07:59 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,63 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      // filter returns an owning table. Release the stream iterator, tracker, and input table
    +      // wrappers before retaining the filtered columns in the output batch.
    +      val filteredTable = withResource(streamJoinIter) { _ =>

    Updated. The shared-helper extraction remains a follow-up, as suggested.

    wjxiz1992 wjxiz1992 commented on code on Oct 21, 2026 07:59 UTC
    Code Review
    integration_tests/src/main/python/join_test.py:1
    @@ -1657,18 +1659,16 @@ def test_distinct_full_outer_join(build_side):
         }
     
         def do_join(spark):
    -        left_df = spark.createDataFrame([
    -            (None, "left_null"),
    -            (1, "left_match"),
    -            (2, "left_only"),
    -            (4, "left_match_2"),
    -        ], ["join_key", "left_value"])
    -        right_df = spark.createDataFrame([
    -            (None, "right_null"),
    -            (1, "right_match"),
    -            (3, "right_only"),
    -            (4, "right_match_2"),
    -        ], ["join_key", "right_value"])
    +        if unmatched_build_rows:
    +            left_rows = [(None, "left_null"), (1, "left_match"),
    +                         (2, "left_only"), (4, "left_match_2")]
    +            right_rows = [(None, "right_null"), (1, "right_match"),
    +                          (3, "right_only"), (4, "right_match_2")]
    +        else:
    +            left_rows = [(1, "left_match"), (2, "left_match_2")]

    Updated.

    wjxiz1992 wjxiz1992 commented on Oct 23, 2026 05:33 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 23, 2026 09:12 UTC
    Author

    build

    gerashegalov gerashegalov commented on code on Oct 25, 2026 00:16 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,66 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      // filter returns an owning table. Release the stream iterator, tracker, and input table
    +      // wrappers before retaining the filtered columns in the output batch.
    +      val filteredTable = closeOnExcept(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          closeOnExcept(tracker) { _ =>
    +            built.checkpoint()
    +          }
    +          try {
    +            withRetryNoSplit(tracker) { trackerAttempt =>
    +              withRestoreOnRetry(built) {
    +                withResource(trackerAttempt.getColumnarBatch()) { trackerBatch =>
    +                  withResource(GpuColumnVector.from(trackerBatch)) { trackerTable =>
    +                    withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
    +                      builtTable.filter(trackerTable.getColumn(0))
    +                    }
                       }
                     }
                   }
                 }
    +          } finally {
    +            built.allowSpilling()
    +          }
    +        }
    +      }
    +      closeOnExcept(filteredTable) { _ =>
    +        streamJoinIter.close()
    +      }
    +
    +      filteredTable.flatMap { filtered =>
    +        val filteredBatch = withResource(filtered) { _ =>
    +          if (filtered.getRowCount > 0) {
    +            Some(GpuColumnVector.from(filtered, builtTypes))
    +          } else {
    +            None
    +          }
    +        }
    +        filteredBatch.map { nonEmptyBatch =>
    +          val numFilterRows = nonEmptyBatch.numRows()
    +          val spillableFiltered = closeOnExcept(nonEmptyBatch) { _ =>
    +            SpillableColumnarBatch(nonEmptyBatch, SpillPriorities.ACTIVE_ON_DECK_PRIORITY)
               }
               // Combine build-side columns with null columns for stream side
    -          withResource(filteredBatch) { builtBatch =>
    -            val numFilterRows = builtBatch.numRows()
    -            if (numFilterRows > 0) {
    +          withRetryNoSplit(spillableFiltered) { filteredAttempt =>

    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.

    gerashegalov gerashegalov commented on code on Oct 25, 2026 00:16 UTC
    Code Review
    scripts/with_resource_nesting_baseline.json:1
    @@ -149,14 +149,9 @@
           "resource": "withResource(offSets)"
         },
         {
    +      "resource": "withResource(getNullScalar)",

    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?

    gerashegalov gerashegalov commented on code on Oct 25, 2026 00:16 UTC
    Code Review
    integration_tests/src/main/python/join_test.py:1
    @@ -1656,36 +1656,45 @@ def do_join(spark):
     
     @validate_execs_in_gpu_plan("GpuShuffledHashJoinExec")
     @ignore_order(local=True)
    +@pytest.mark.inject_oom
    +@pytest.mark.parametrize("use_condition", [False, True], ids=["EQUI", "CONDITION"])
     @pytest.mark.parametrize(
         "build_side", ["left", "right"], ids=["BUILD_LEFT", "BUILD_RIGHT"])
    -def test_distinct_full_outer_join(build_side):
    +@pytest.mark.parametrize(
    +    "unmatched_build_rows", [False, True], ids=["MATCHED", "UNMATCHED"])

    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.

    wjxiz1992 wjxiz1992 commented on Oct 25, 2026 01:06 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 25, 2026 02:54 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on code on Oct 26, 2026 03:57 UTC
    Code Review
    sql-plugin/src/main/scala/org/apache/spark/sql/rapids/execution/GpuHashJoin.scala:1
    @@ -2729,40 +2726,66 @@ class HashOuterJoinIterator(
     
       private def getFinalBatch(): Option[ColumnarBatch] = {
         NvtxIdWithMetrics(NvtxRegistry.GET_FINAL_BATCH, joinTime) {
    -      streamJoinIter.releaseBuiltSideTracker() match {
    -        case None => None
    -        case Some(tracker) =>
    -          val filteredBatch = withResource(tracker) { scb =>
    -            withResource(scb.getColumnarBatch()) { trackerBatch =>
    -              withResource(GpuColumnVector.from(trackerBatch)) { trackerTab =>
    -                val batch = built.getBatch
    -                withResource(GpuColumnVector.from(batch)) { builtTable =>
    -                  withResource(builtTable.filter(trackerTab.getColumn(0))) { filterTab =>
    -                    GpuColumnVector.from(filterTab, GpuColumnVector.extractTypes(batch))
    +      val builtTypes = built.dataTypes
    +      // filter returns an owning table. Release the stream iterator, tracker, and input table
    +      // wrappers before retaining the filtered columns in the output batch.
    +      val filteredTable = closeOnExcept(streamJoinIter) { _ =>
    +        streamJoinIter.releaseBuiltSideTracker().map { tracker =>
    +          closeOnExcept(tracker) { _ =>
    +            built.checkpoint()
    +          }
    +          try {
    +            withRetryNoSplit(tracker) { trackerAttempt =>
    +              withRestoreOnRetry(built) {
    +                withResource(trackerAttempt.getColumnarBatch()) { trackerBatch =>
    +                  withResource(GpuColumnVector.from(trackerBatch)) { trackerTable =>
    +                    withResource(GpuColumnVector.from(built.getBatch)) { builtTable =>
    +                      builtTable.filter(trackerTable.getColumn(0))
    +                    }
                       }
                     }
                   }
                 }
    +          } finally {
    +            built.allowSpilling()
    +          }
    +        }
    +      }
    +      closeOnExcept(filteredTable) { _ =>
    +        streamJoinIter.close()
    +      }
    +
    +      filteredTable.flatMap { filtered =>
    +        val filteredBatch = withResource(filtered) { _ =>
    +          if (filtered.getRowCount > 0) {
    +            Some(GpuColumnVector.from(filtered, builtTypes))
    +          } else {
    +            None
    +          }
    +        }
    +        filteredBatch.map { nonEmptyBatch =>
    +          val numFilterRows = nonEmptyBatch.numRows()
    +          val spillableFiltered = closeOnExcept(nonEmptyBatch) { _ =>
    +            SpillableColumnarBatch(nonEmptyBatch, SpillPriorities.ACTIVE_ON_DECK_PRIORITY)
               }
               // Combine build-side columns with null columns for stream side
    -          withResource(filteredBatch) { builtBatch =>
    -            val numFilterRows = builtBatch.numRows()
    -            if (numFilterRows > 0) {
    +          withRetryNoSplit(spillableFiltered) { filteredAttempt =>

    Updated.

    wjxiz1992 wjxiz1992 commented on Oct 26, 2026 07:42 UTC
    Author

    build

    gerashegalov gerashegalov commented on code on Oct 26, 2026 08:25 UTC
    Code Review
    tests/src/test/scala/com/nvidia/spark/rapids/GpuShuffledHashJoinExecSuite.scala:1
    @@ -41,6 +44,151 @@ class GpuShuffledHashJoinExecSuite extends AnyFunSuite with MockitoSugar {
       private val attrs = Array(AttributeReference("a1", IntegerType, nullable=false)())
       private val buildGoals = Seq(RequireSingleBatch, RequireSingleBatchWithFilter(GpuLiteral(true)))
     
    +  test("final outer join batch closes the released tracker if checkpoint fails") {
    +    TestUtils.withGpuSparkSession(new SparkConf()) { _ =>
    +      val built = mock[LazySpillableColumnarBatch]
    +      when(built.dataTypes).thenReturn(Array[DataType](IntegerType))
    +      val failure = new IllegalStateException("injected checkpoint failure")
    +      doThrow(failure).when(built).checkpoint()
    +      val tracker = mock[SpillableColumnarBatch]
    +      val joinOptions = new RapidsConf(new SparkConf()).getJoinOptions(TARGET_SIZE_BIG)
    +      withResource(new HashOuterJoinIterator(
    +          FullOuter, built, Seq.empty, None, Some(tracker), Iterator.empty,
    +          Seq.empty, attrs, None, joinOptions, GpuBuildRight,
    +          false, None, NoopMetric, NoopMetric)) { iter =>
    +        assert(intercept[IllegalStateException](iter.hasNext) eq failure)
    +        verify(tracker, times(1)).close()
    +      }
    +    }
    +  }
    +
    +  test("final outer join batch closes the filtered table if iterator cleanup fails") {
    +    TestUtils.withGpuSparkSession(new SparkConf()) { _ =>
    +      val baseline = Rmm.getTotalBytesAllocated
    +      withResource(newOneIntColumnTable()) { table =>
    +        withResource(GpuColumnVector.from(table, Array[DataType](IntegerType))) { builtBatch =>
    +          val built = mock[LazySpillableColumnarBatch]
    +          when(built.dataTypes).thenReturn(Array[DataType](IntegerType))
    +          when(built.getBatch).thenReturn(builtBatch)
    +          val failure = new IllegalStateException("injected iterator cleanup failure")
    +          doThrow(failure).when(built).close()
    +          val tracker = withResource(ColumnVector.fromBooleans(true, false, true, false, true)) {
    +            mask =>
    +              SpillableColumnarBatch(
    +                new ColumnarBatch(Array(GpuColumnVector.from(mask.incRefCount(), BooleanType)), 5),
    +                SpillPriorities.ACTIVE_ON_DECK_PRIORITY)
    +          }
    +          val joinOptions = new RapidsConf(new SparkConf()).getJoinOptions(TARGET_SIZE_BIG)
    +          withResource(new HashOuterJoinIterator(
    +              FullOuter, built, Seq.empty, None, Some(tracker), Iterator.empty,
    +              Seq.empty, attrs, None, joinOptions, GpuBuildRight,
    +              false, None, NoopMetric, NoopMetric)) { iter =>
    +            assert(intercept[IllegalStateException](iter.hasNext) eq failure)
    +          }
    +        }
    +      }
    +      assert(Rmm.getTotalBytesAllocated == baseline)
    +    }
    +  }
    +
    +  Seq(GpuBuildLeft, GpuBuildRight).foreach { buildSide =>
    +    test(s"final outer join batch retries filtering for $buildSide") {
    +      TestUtils.withGpuSparkSession(new SparkConf()) { _ =>
    +        withResource(newOneIntColumnTable()) { table =>
    +          withResource(GpuColumnVector.from(table, Array[DataType](IntegerType))) { builtBatch =>
    +            val built = mock[LazySpillableColumnarBatch]
    +            when(built.dataTypes).thenReturn(Array[DataType](IntegerType))
    +            when(built.getBatch).thenReturn(builtBatch)
    +            val tracker = mock[SpillableColumnarBatch]
    +            val trackerBatch = withResource(

    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.

    gerashegalov gerashegalov commented on Oct 26, 2026 08:25 UTC
    Reviewer

    LGTM

    wjxiz1992 wjxiz1992 commented on Oct 26, 2026 11:47 UTC
    Author

    build

    wjxiz1992 wjxiz1992 commented on Oct 26, 2026 12:25 UTC
    Author

    build

    gerashegalov gerashegalov approved these changes on Oct 26, 2026 19:22 UTC
    Approved Reviewer

    LGTM

    Reviewers
    Assignees
    wjxiz1992 wjxiz1992
    Labels
    risk: low confidence: 85.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 41.2% (MEDIUM) · Higher = larger blast radius
    41.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.8% · Lower = rushed or shallow review
    85.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.9% · Safe to merge
    5.9%