← Back to Pull requests

Complete a close deferred by a failed spill #16476

Merged
gerashegalov merged 2 files (373 lines) on Oct 26, 2026 19:27 UTC
View on GitHub
gerashegalov gerashegalov commented on Oct 21, 2026 07:26 UTC
Author

Fixes #16333.

Description

If close() is called on a spillable handle while a spill is running, the close is deferred to the spilling thread. When that spill then failed, SpillableHandle.executeSpill reset spilling but never completed the deferred close. The handle was left closed with its resource never released, and it stayed in its store, where later spill plans could still pick it.

A failed spill now completes a close that was deferred to it:

  • It does so only if the spill still owned the handle, that is, spilling was still set. A spill that already reset spilling and handled the close itself, then threw later, does not close a second time.

  • Host handles close in the spilling thread. Device handles must not release device memory before the post-spill device synchronize (#16198). A failed device spill therefore keeps spilling set, as a successful one does, whether or not the handle was closed yet. The store's spill plan hands the handle to postSpill, which synchronizes the device and then calls releaseSpilled. After a failed spill, releaseSpilled keeps the device data, resets spilling, and completes the close if the handle was closed during the spill or before the synchronize. While spilling is set no other spill can start, so the handle is released exactly once.

  • A caller that spills a device handle directly, outside a store, already has to call releaseSpilled after a successful spill. The spill() scaladoc now says it must also synchronize the device and call releaseSpilled after a failed one that left spillFailed set, which is the check the spill store uses. Only the spill store calls spill() in production code.

  • The spill exception stays primary and is rethrown. A failure from the close is attached to it as suppressed.

  • A handle that was not closed keeps its data. If the spill failed before publishing its host copy, the handle can be spilled again.
  • SharedRecomputableHandle.spill now moves the evicted object to its pending-release list in the same locked block that removes it, rather than in a second block. Nothing can fail between the two steps any more, so its spill no longer needs the failure path. The existing post-spill releaseSpilled still releases the object and completes any deferred close, subject to outstanding leases and rebuilds.

    The spill() scaladoc said a failed spill does not restore state and is unrecoverable. It now describes the actual behavior.

    Apart from a try around each handle's spill in the spill plan and one flag check in device releaseSpilled, only the failure path changes. SharedRecomputableHandle also does its eviction in one locked block instead of two.

    Out of scope:

  • A disk-staged spill that fails after its spill file is created leaves the partial file behind. That is #16205, which this PR does not change.

  • This PR handles failures inside the spill body. A failure while a spill retains its data, before the body starts, leaves spilling set. A failure after the spill has published its host copy keeps both copies until the handle is closed. Both predate this PR and are tracked in #16526.
  • Tests

    New latch-controlled cases in SpillLifecycleReplaySuite. Each pauses a spill and then injects a failure: a device spill after its host copy has read the device data, a host spill when it opens its spill file. Device spills run through the device store, which is also paused at its post-spill synchronize. At that point the test checks that the handle is still owned by the spill and its device data has not been released. The cases run in these modes:

  • Closed during the spill: close() is called from another thread while the spill is paused. The spill error reaches the caller, the resource is released, the handle is no longer spillable, and the device, host and disk stores are empty.

  • Left open: the spill error reaches the caller, and the handle keeps its data, which is materialized and checked. The handle stays spillable, and closing it afterwards releases everything.

  • Closed after the failure (device handles only): close() is called after the spill has failed but before the post-spill synchronize. The device data is kept until the synchronize and released after it.
  • The first two modes cover these handle variants:

  • Device to host, with a host copy that fails after reading the device data: SpillableDeviceBufferHandle, SpillableColumnarBatchHandle, SpillableColumnarBatchFromBufferHandle, SpillableCompressedColumnarBatchHandle (host staging and disk staging) and SpillableTableHandle.

  • Host to disk, with a failure when the spill file is opened: SpillableHostBufferHandle and SpillableHostColumnarBatchHandle.
  • Two single-threaded cases cover a direct spill() of a device handle that fails, left open and closed: the handle stays owned by the spill until releaseSpilled, which keeps the data of the open handle and releases the closed one.

    Two more single-threaded cases cover error handling:

  • When the deferred close also throws, the spill error stays primary, the close error is suppressed, and doClose runs once, even after a second close().

  • When a spill has already reset spilling and completed the close before throwing, doClose is not called again.
  • Validation:

  • On main without the fix, all eight original cases fail: the seven closed-during-spill variants and the suppressed-error case. The open-handle cases guard against closing too much, so they are expected to pass on main. The double-close case fails against this PR's first revision, which closed twice.

  • Each device-path assertion was confirmed to fail when the fix is broken, on the GPU:

  • - If a failed device spill resets spilling in the spilling thread, as this PR's first two revisions did, all 18 failed-spill device cases and both direct-spill cases fail.
    - If it keeps waiting for the synchronize only when the handle was already closed, the 6 closed-after-the-failure cases, the 6 left-open cases and both direct-spill cases fail.
    - If it keeps spilling set but still closes in the spilling thread, the 6 closed-during-the-spill device cases fail because the device data was released before the synchronize.
    - If the spill plan does not hand the failed handle to postSpill, all 18 failed-spill device cases fail with spilling left set, as does the existing partial-plan failure test.
    - If releaseSpilled releases the device data after a failed spill, the 6 left-open device cases and the open direct-spill case fail.
  • With the fix, SpillLifecycleReplaySuite, SpillFrameworkSuite and SharedRecomputableHandleSuite pass 138/138 on Spark 3.5.0.

  • Scalastyle reports no errors, and sql-plugin compiles for Scala 2.13 with Spark 4.0.0.
  • This change was developed with AI assistance (Claude Code). I reviewed the complete diff and this description before updating the PR.

    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
  • The successful spill path changes slightly: the spill plan wraps each handle's spill in a try, device releaseSpilled checks one flag under a lock it already holds, and SharedRecomputableHandle.spill does one locked block instead of two. A temporary probe, not part of this PR, timed successful device-to-host spills through the device store: 1,000 handles of 4 KiB per round, one store spill per handle, 15 rounds with the first 5 dropped as warm-up. On a Quadro RTX 6000 with Spark 3.5.0, alternating between main and this PR showed no measurable difference:

    | Build | Median per spill, run 1 | Median per spill, run 2 | Fastest round |
    |---|---|---|---|
    | main | 278.7 µs | 272.7 µs | 265.6 µs |
    | This PR | 280.9 µs | 269.6 µs | 264.7 µs |

    Round-to-round variation within a run was 265 to 330 µs, much larger than any difference between the builds.

    🤖 Generated with Claude Code

    Diff: 373 lines (+348 / -25) across 2 files Reviewer: thirtiseven Review duration: 7921m
    All Vouch review confidence checks passed
    Residual risk 0.12 = Change Risk (0.40) × (1 − Review Confidence (0.69)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.40 · 373 lines diff across 2 files
    0.40
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.57 · 5 substantive comment(s)
    0.57
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    68%
    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.354
    Real PR Conversation Timeline
    18 items
    thirtiseven thirtiseven commented on code on Oct 21, 2026 07:36 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -250,8 +257,14 @@ trait SpillableHandle extends StoreHandle with Logging {
           } catch {
             case e: Throwable =>
               logWarning(s"Failed to spill $this", e)
    -          synchronized {
    +          val closeNow = synchronized {
                 spilling = false
    +            closeAfterFailedSpill
    +          }

    Non-blocking: should this only close when this thread still owns the spill? Some spill bodies clear spilling and complete the deferred close themselves, then can still throw. For example, SpillableHostColumnarBatchHandle closes the DiskHandleBuilder after publishing, so this catch would call doClose() a second time. Today's doClose implementations happen to be idempotent, so this is defensive:

              val closeNow = synchronized {
                val ownsSpill = spilling
                spilling = false
                ownsSpill && closeAfterFailedSpill
              }
    

    thirtiseven thirtiseven commented on code on Oct 21, 2026 07:36 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -629,6 +642,10 @@ class SharedRecomputableHandle[T <: AutoCloseable] private[spill] (
         }
       }
     
    +  // Same condition as releaseSpilled; with a lease outstanding, releaseLease closes instead.
    +  override protected def closeAfterFailedSpill: Boolean =
    +    closed && pinCount == 0 && !rebuilding

    Non-blocking alternative: spill() removes dev under the lock but appends it to pendingRelease in a second synchronized inside executeSpill, so a failure in between drops the evicted object. Moving pendingRelease = pendingRelease ++ dev.toSeq into the same block that sets dev = None closes that window. spill() then no longer needs executeSpill, and this override becomes unnecessary.

    thirtiseven thirtiseven commented on code on Oct 21, 2026 07:36 UTC
    Code Review
    tests/src/test/scala/com/nvidia/spark/rapids/spill/SpillLifecycleReplaySuite.scala:1
    @@ -598,4 +631,113 @@ class SpillLifecycleReplaySuite extends SpillUnitTestBase {
         handle.releaseSpilled()
         assertResult(0)(deviceStore.numHandles)
       }
    +
    +  private def runFailedSpillClose(
    +      handle: SpillableHandle,
    +      started: CountDownLatch,
    +      resume: CountDownLatch,
    +      released: () => Boolean): Unit = {
    +    val executor = Executors.newSingleThreadExecutor()
    +    try {
    +      val spilled = executor.submit(new Callable[Long] {
    +        override def call(): Long = handle.spill()
    +      })
    +      await(started)
    +      handle.close()
    +      resume.countDown()
    +      val failure = intercept[ExecutionException] {
    +        spilled.get(timeoutSeconds, TimeUnit.SECONDS)
    +      }
    +      assert(failure.getCause.getMessage.startsWith("injected"))
    +      assert(!handle.spilling)
    +      assert(released())
    +      assert(!handle.spillable)
    +      assertResult(0)(SpillFramework.stores.deviceStore.numHandles)
    +      assertResult(0)(SpillFramework.stores.hostStore.numHandles)
    +      assertResult(0)(SpillFramework.stores.diskStore.numHandles)
    +    } finally {
    +      resume.countDown()
    +      executor.shutdown()
    +      if (!executor.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) {
    +        executor.shutdownNow()
    +      }
    +      handle.close()
    +    }
    +  }
    +
    +  test("device buffer completes a close deferred by a failed spill") {
    +    val hostStore = new PausingFailingHostStore
    +    SpillFramework.stores.hostStore = hostStore
    +    val handle = createHandle()
    +    runFailedSpillClose(handle, hostStore.copyStarted, hostStore.resumeCopy,
    +      () => handle.dev.isEmpty)
    +  }
    +
    +  for (handleCase <- siblingHandles if !handleCase.diskBacked) {

    Non-blocking: a variant where the spill fails while the handle is still open would guard against over-closing: the data should be kept and the handle should stay spillable. The disk-staged compressed-batch case also seems easy to include here.

    thirtiseven thirtiseven commented on code on Oct 21, 2026 07:36 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -230,10 +230,17 @@ trait SpillableHandle extends StoreHandle with Logging {
        */
       private[spill] def doClose(): Unit
     
    +  /**
    +   * Whether a failed spill must complete a `close` deferred to it. Called while holding this
    +   * handle's lock, after `spilling` is reset.
    +   */
    +  protected def closeAfterFailedSpill: Boolean = closed
    +
       /**
        * Executes a spill operation while handling exceptions.
        * If an exception occurs during spilling (e.g. InterruptedException), this method
    -   * catches it, logs a warning, resets the spilling state to false, and rethrows the exception.
    +   * catches it, logs a warning, resets the spilling state to false, completes any close

    Nit: the spill() scaladoc above still says a failed spill makes no attempt to restore state and is non-recoverable. That has been outdated since #12705, and this change also completes a deferred close on failure.

    gerashegalov gerashegalov commented on code on Oct 22, 2026 05:18 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -250,8 +257,14 @@ trait SpillableHandle extends StoreHandle with Logging {
           } catch {
             case e: Throwable =>
               logWarning(s"Failed to spill $this", e)
    -          synchronized {
    +          val closeNow = synchronized {
                 spilling = false
    +            closeAfterFailedSpill
    +          }

    Good catch. Adopted: executeSpill now records whether spilling was still set before resetting it, and closes only in that case. I also added "failed spill does not repeat a close its block already completed", which fails against the previous revision (doClose ran twice) and passes now.

    gerashegalov gerashegalov commented on code on Oct 22, 2026 05:18 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -629,6 +642,10 @@ class SharedRecomputableHandle[T <: AutoCloseable] private[spill] (
         }
       }
     
    +  // Same condition as releaseSpilled; with a lease outstanding, releaseLease closes instead.
    +  override protected def closeAfterFailedSpill: Boolean =
    +    closed && pinCount == 0 && !rebuilding

    Done. The evicted object now moves to pendingRelease in the same locked block that clears dev. spill() no longer goes through executeSpill, and the closeAfterFailedSpill hook is gone along with its override.

    gerashegalov gerashegalov commented on code on Oct 22, 2026 05:18 UTC
    Code Review
    tests/src/test/scala/com/nvidia/spark/rapids/spill/SpillLifecycleReplaySuite.scala:1
    @@ -598,4 +631,113 @@ class SpillLifecycleReplaySuite extends SpillUnitTestBase {
         handle.releaseSpilled()
         assertResult(0)(deviceStore.numHandles)
       }
    +
    +  private def runFailedSpillClose(
    +      handle: SpillableHandle,
    +      started: CountDownLatch,
    +      resume: CountDownLatch,
    +      released: () => Boolean): Unit = {
    +    val executor = Executors.newSingleThreadExecutor()
    +    try {
    +      val spilled = executor.submit(new Callable[Long] {
    +        override def call(): Long = handle.spill()
    +      })
    +      await(started)
    +      handle.close()
    +      resume.countDown()
    +      val failure = intercept[ExecutionException] {
    +        spilled.get(timeoutSeconds, TimeUnit.SECONDS)
    +      }
    +      assert(failure.getCause.getMessage.startsWith("injected"))
    +      assert(!handle.spilling)
    +      assert(released())
    +      assert(!handle.spillable)
    +      assertResult(0)(SpillFramework.stores.deviceStore.numHandles)
    +      assertResult(0)(SpillFramework.stores.hostStore.numHandles)
    +      assertResult(0)(SpillFramework.stores.diskStore.numHandles)
    +    } finally {
    +      resume.countDown()
    +      executor.shutdown()
    +      if (!executor.awaitTermination(timeoutSeconds, TimeUnit.SECONDS)) {
    +        executor.shutdownNow()
    +      }
    +      handle.close()
    +    }
    +  }
    +
    +  test("device buffer completes a close deferred by a failed spill") {
    +    val hostStore = new PausingFailingHostStore
    +    SpillFramework.stores.hostStore = hostStore
    +    val handle = createHandle()
    +    runFailedSpillClose(handle, hostStore.copyStarted, hostStore.resumeCopy,
    +      () => handle.dev.isEmpty)
    +  }
    +
    +  for (handleCase <- siblingHandles if !handleCase.diskBacked) {

    Added both. Every failed-spill variant now also runs with the handle left open. The test checks that the data survives by materializing and verifying it, that the handle stays spillable, and that a later close() releases everything. The disk-staged compressed batch is included, with a check that no spill file is left behind.

    gerashegalov gerashegalov commented on code on Oct 22, 2026 05:18 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -230,10 +230,17 @@ trait SpillableHandle extends StoreHandle with Logging {
        */
       private[spill] def doClose(): Unit
     
    +  /**
    +   * Whether a failed spill must complete a `close` deferred to it. Called while holding this
    +   * handle's lock, after `spilling` is reset.
    +   */
    +  protected def closeAfterFailedSpill: Boolean = closed
    +
       /**
        * Executes a spill operation while handling exceptions.
        * If an exception occurs during spilling (e.g. InterruptedException), this method
    -   * catches it, logs a warning, resets the spilling state to false, and rethrows the exception.
    +   * catches it, logs a warning, resets the spilling state to false, completes any close

    Updated. The scaladoc now says that a failed spill propagates the exception and keeps the data, or completes the close if the handle was closed during the spill.

    greptile-apps[bot] greptile-apps[bot] commented on code on Oct 22, 2026 05:23 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -602,11 +611,10 @@ class SharedRecomputableHandle[T <: AutoCloseable] private[spill] (
         // Logically evict the object under the handle lock but do not free it yet.
         // The thread that spills removes dev and sets spilling to true so that only
         // one thread spills.
    -    var evicted: Option[T] = None
         val thisThreadSpills = synchronized {
           if (!closed && dev.isDefined && pinCount == 0 && !spilling) {
             spilling = true
    -        evicted = dev
    +        pendingRelease = pendingRelease ++ dev.toSeq

    <a href="#"><img alt="P0" src="https://greptile-static-assets.s3.amazonaws.com/badges/p0.svg?v=9" align="top"></a> Performance exemption misses successful spills

    SharedRecomputableHandle.spill() now queues the resource under the first lock and removes the executeSpill call on successful spills. This contradicts the description’s reason for marking performance testing unnecessary: that only failed spills change.

    The repository requires performance results or a verifiable explanation that runtime performance cannot change. Add results for successful shared-handle spills or revise the exemption to cover this change.

    Rule Used: Report Performance: Not required as a high-severity finding unless the pull request is documentation-only or test-only, or its description gives a verifiable reason the change cannot affect runtime performance. A bug-fix label, small diff, or rarel... (source)

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

    gerashegalov gerashegalov commented on code on Oct 22, 2026 06:36 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -602,11 +611,10 @@ class SharedRecomputableHandle[T <: AutoCloseable] private[spill] (
         // Logically evict the object under the handle lock but do not free it yet.
         // The thread that spills removes dev and sets spilling to true so that only
         // one thread spills.
    -    var evicted: Option[T] = None
         val thisThreadSpills = synchronized {
           if (!closed && dev.isDefined && pinCount == 0 && !spilling) {
             spilling = true
    -        evicted = dev
    +        pendingRelease = pendingRelease ++ dev.toSeq

    The description was updated alongside this commit to cover it (see the Performance note). On the successful path, SharedRecomputableHandle.spill() now takes its lock once instead of twice and no longer goes through executeSpill. For this handle, executeSpill is the base SpillableHandle version: a try/catch around a closure, without the spill timing or byte metrics that DeviceSpillableHandle adds (SharedRecomputableHandle extends DeviceStoreHandle directly). It performs the same state updates in the same order, without the second lock or the closure, so the change can only remove work and not add any.

    greptile-apps[bot] greptile-apps[bot] commented on code on Oct 22, 2026 06:37 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -602,11 +611,10 @@ class SharedRecomputableHandle[T <: AutoCloseable] private[spill] (
         // Logically evict the object under the handle lock but do not free it yet.
         // The thread that spills removes dev and sets spilling to true so that only
         // one thread spills.
    -    var evicted: Option[T] = None
         val thisThreadSpills = synchronized {
           if (!closed && dev.isDefined && pinCount == 0 && !spilling) {
             spilling = true
    -        evicted = dev
    +        pendingRelease = pendingRelease ++ dev.toSeq

    You're right—the updated Performance note addresses the successful-path change, and the implementation supports that explanation. SharedRecomputableHandle uses the base executeSpill implementation, so removing that wrapper and its second lock does not remove the timing or byte metrics added by DeviceSpillableHandle. The state updates remain in order, with less work on the successful path. I retract my request for performance results.

    I couldn't post this as a PR comment because permission to submit it was not granted.

    amahussein amahussein commented on code on Oct 22, 2026 16:31 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -250,8 +251,16 @@ trait SpillableHandle extends StoreHandle with Logging {
           } catch {
             case e: Throwable =>
               logWarning(s"Failed to spill $this", e)
    -          synchronized {
    +          val closeNow = synchronized {
    +            // A block that already reset spilling has also handled any deferred close.
    +            val ownsSpill = spilling
                 spilling = false
    +            ownsSpill && closed
    +          }
    +          if (closeNow) {
    +            try doClose() catch {
    +              case t: Throwable => SpillFramework.addFailure(e, t)
    +            }

    when a device handle was closed during the spill, this doClose() frees dev inside trySpill, before postSpill calls synchronizeDevice(). That breaks the rule in releaseSpilled's scaladoc and reopens #16198 on the failure path. Handing it to postSpill, as a successful spill does, would fix it.

    Let me know if you need help with writing tunit-tests to trigger that scenario.

    amahussein amahussein commented on code on Oct 22, 2026 16:32 UTC
    Code Review
    tests/src/test/scala/com/nvidia/spark/rapids/spill/SpillLifecycleReplaySuite.scala:1
    @@ -89,6 +89,40 @@ class SpillLifecycleReplaySuite extends SpillUnitTestBase {
         }
       }
     
    +  private class PausingFailingHostStore(maxSizeInBytes: Long)
    +    extends SpillableHostStore(Some(maxSizeInBytes)) {
    +    val copyStarted = new CountDownLatch(1)
    +    val resumeCopy = new CountDownLatch(1)
    +
    +    override def makeBuilder(
    +        handle: SpillableHostBufferHandle): SpillableHostBufferHandleBuilder = {
    +      val underlying = super.makeBuilder(handle)
    +      new SpillableHostBufferHandleBuilder {
    +        override def copyNext(buffer: DeviceMemoryBuffer, length: Long,
    +            stream: Cuda.Stream): Unit = {
    +          copyStarted.countDown()
    +          await(resumeCopy)
    +          throw new IllegalStateException("injected host copy failure")
    +        }

    This throws before underlying.copyNext opens the spill file, so the disk-staged stagingRemoved check passes whatever the cleanup does. With the throw after the write, the file is left behind on this head, which is #16205. Could you fix #16205 here and take this change, or drop the check and the description's claim?

            override def copyNext(buffer: DeviceMemoryBuffer, length: Long,
                stream: Cuda.Stream): Unit = {
              underlying.copyNext(buffer, length, stream)
              copyStarted.countDown()
              await(resumeCopy)
              throw new IllegalStateException("injected host copy failure")
            }
    

    gerashegalov gerashegalov commented on code on Oct 22, 2026 20:04 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -250,8 +251,16 @@ trait SpillableHandle extends StoreHandle with Logging {
           } catch {
             case e: Throwable =>
               logWarning(s"Failed to spill $this", e)
    -          synchronized {
    +          val closeNow = synchronized {
    +            // A block that already reset spilling has also handled any deferred close.
    +            val ownsSpill = spilling
                 spilling = false
    +            ownsSpill && closed
    +          }
    +          if (closeNow) {
    +            try doClose() catch {
    +              case t: Throwable => SpillFramework.addFailure(e, t)
    +            }

    Good catch, and thanks for the offer of tests. Fixed in 4a1fd23a9f and 7bf8515091: a failed device spill now keeps spilling set, as a successful one does, whether or not the handle was closed yet. The spill plan hands it to postSpill, so after synchronizeDevice() releaseSpilled resets spilling, keeps the device data, and completes a close that arrived during the spill or before the synchronize. That also covers a close that arrives after the failure. Host handles still close in the spilling thread. The failed-spill tests now run device spills through the device store and pause at the synchronize. There they check that the spill still owns the handle and its device data is intact, with the handle closed during the spill, closed after the failure, or left open. Each of those checks was confirmed to fail on the GPU with the fix broken. Two failure points outside the spill body, before it starts and after the host copy is published, predate this PR and are tracked in #16526.

    gerashegalov gerashegalov commented on code on Oct 22, 2026 20:04 UTC
    Code Review
    tests/src/test/scala/com/nvidia/spark/rapids/spill/SpillLifecycleReplaySuite.scala:1
    @@ -89,6 +89,40 @@ class SpillLifecycleReplaySuite extends SpillUnitTestBase {
         }
       }
     
    +  private class PausingFailingHostStore(maxSizeInBytes: Long)
    +    extends SpillableHostStore(Some(maxSizeInBytes)) {
    +    val copyStarted = new CountDownLatch(1)
    +    val resumeCopy = new CountDownLatch(1)
    +
    +    override def makeBuilder(
    +        handle: SpillableHostBufferHandle): SpillableHostBufferHandleBuilder = {
    +      val underlying = super.makeBuilder(handle)
    +      new SpillableHostBufferHandleBuilder {
    +        override def copyNext(buffer: DeviceMemoryBuffer, length: Long,
    +            stream: Cuda.Stream): Unit = {
    +          copyStarted.countDown()
    +          await(resumeCopy)
    +          throw new IllegalStateException("injected host copy failure")
    +        }

    You're right, the throw came before the spill file was created, so that check proved nothing. I took your change: the failure now comes after underlying.copyNext. I dropped the check and the description's claim rather than folding #16205 in. DiskHandleBuilder takes a startPos for shared files, so deleting on close needs its own design and review. The test now removes the leftover file in cleanup and points at #16205.

    amahussein amahussein commented on code on Oct 23, 2026 00:38 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -1762,7 +1790,14 @@ trait SpillableStore[T <: SpillableHandle]
           val it = spillableHandles.iterator()
           while (it.hasNext) {
             val handle = it.next()
    -        val spilled = handle.spill()
    +        val spilled = try handle.spill() catch {
    +          case t: Throwable =>
    +            // postSpill calls releaseSpilled for a failed spill that awaits the synchronize
    +            if (handle.synchronized(handle.spillFailed)) {
    +              spilledHandles.add(handle)
    +            }
    +            throw t
    +        }

    nit: can the spillFailed be called twice? If another thread's spill() of this handle throws while the failure waits for its sync, that plan adds the handle too, and the second releaseSpilled frees an open handle's only copy.

    gerashegalov gerashegalov commented on code on Oct 23, 2026 06:24 UTC
    Code Review
    sql-plugin/src/main/scala/com/nvidia/spark/rapids/spill/SpillFramework.scala:1
    @@ -1762,7 +1790,14 @@ trait SpillableStore[T <: SpillableHandle]
           val it = spillableHandles.iterator()
           while (it.hasNext) {
             val handle = it.next()
    -        val spilled = handle.spill()
    +        val spilled = try handle.spill() catch {
    +          case t: Throwable =>
    +            // postSpill calls releaseSpilled for a failed spill that awaits the synchronize
    +            if (handle.synchronized(handle.spillFailed)) {
    +              spilledHandles.add(handle)
    +            }
    +            throw t
    +        }

    Good question. At 0c53d5e6c5 it can't happen: while a failed spill waits for its synchronize, spilling stays set and dev is still present. So another thread's spillable can't throw, since every override throws only when the data is missing, and its claim sees spilling and returns 0. Only the thread whose spill failed can reach that check with spillFailed set.

    Reviewers
    Assignees
    gerashegalov gerashegalov
    Labels
    risk: low confidence: 68.9% 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: 39.9% (MEDIUM) · Higher = larger blast radius
    39.9%
    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: 68.9% · Lower = rushed or shallow review
    68.9%
    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: 12.4% · Safe to merge
    12.4%