← Back to Pull requests

Prevent use-after-free when aborting multithreaded shuffle writes #17160

Closed
unknown closed this pull request without merging on Dec 01, 2026 06:58 UTC
View on GitHub
unknown unknown commented on Nov 26, 2026 05:43 UTC
Author

Fixes #17081.

Description

When RapidsShuffleWriter.stop(false) is called while RapidsShuffleThreadedWriterBase still has active BatchMerger tasks running, cleanupTempData() aborts RapidsLocalDiskShuffleMapOutputWriter instances immediately, which calls SpillablePartialFileHandle.close() and frees the off-heap HostMemoryBuffer. Because SpillablePartialFileHandle.write() was unsynchronized against close()/doClose(), a rapids-shuffle-merger thread copying compressed bytes into host via setBytes() (Unsafe.copyMemory / jbyte_disjoint_arraycopy) could write into freed native memory and crash the JVM with SIGSEGV.

This change fixes both layers of the race:

  • Coordinate SpillablePartialFileHandle.write() with close()/doClose() and finishWrite() via a writeInProgress flag checked under brief entry/exit handle monitors (withActiveWrite), with doClose() waiting on spillInProgress || writeInProgress so HostMemoryBuffer cannot be freed mid-write and post-close writes fail cleanly with IllegalStateException, while keeping expandBuffer()/HostMemoryBuffer.allocate() outside the handle monitor so concurrent expansions under finite host memory cannot deadlock with SpillFramework spill selection (and spillable short-circuits !protectedFromSpill before super.spillable).

  • Guard RapidsLocalDiskShuffleMapOutputWriter's aborted state and partialFileHandle initialization/abort/commitAllPartitions transitions under brief writer-monitor state changes (committing flag with abort() waiting outside nested locks, and @volatile reads with non-optional handle lookup on the write path so normal writes add no extra writer lock), ensuring concurrent abort() cannot cause a non-empty disk commit to write an index with a null data file while preserving legitimate empty commits.

  • Guard mapOutputWriters and stopping in RapidsShuffleWriter (both spark330 and spark400db173 shims), add an onAbort() hook implemented by RapidsShuffleThreadedWriterBase (tracking active batches in an $O(1)$ HashMap by batchId) to signal the limiter and cancel/drain every active BatchMerger before aborting map output writers, and atomically transfer map-output writer ownership to the shuffle catalog via transferMapOutputWritersIfNotStopping so stop(false) cannot close published handles and a stopped writer cannot publish aborted handles.

  • Add deterministic regression tests across SpillablePartialFileHandleSuite (close() and finishWrite() waiting on an in-flight write(), a CyclicBarrier(2) concurrent-expansion test under a 288 KiB HostAlloc budget with failure-safe daemon/store teardown verified to fail cleanly against 86d28cdec, plus 40-round concurrent write + close stress coverage), RapidsLocalDiskShuffleMapOutputWriterSuite (stream, channel, partition-writer, and commitAllPartitions operations after abort() throw IllegalStateException, non-aborted empty commits succeed, and abort() waits for an in-flight commitAllPartitions() without deleting temp data), and RapidsShuffleThreadedWriterSuite (two active BatchMerger threads held in OutputStream.write() verifying stop(false) drains mergers before abort() and exits via CancellationException/IOException, write() after stop(false) aborting the newly created writer, stop(false) landing between second-writer registration and active-batch registration, stop(false) racing with cleanupBatch draining an active merger, both orderings of concurrent stop(false) vs skip-merge catalog publication, and concurrent stop(false) before non-catalog disk commit).
  • Validation (Java 17)

  • Spark 4.0.1 (buildver=401, Scala 2.13, GPU): SpillablePartialFileHandleSuite, SpillablePartialFileHandleMetricSuite, RapidsLocalDiskShuffleMapOutputWriterSuite, and RapidsShuffleThreadedWriterSuite passed 72/72 on fab06e199 (plus the deadlock regression test verified to fail cleanly in 33s with exit code 1 against 86d28cdec, and 3 consecutive parallel-mode -Drapids.parallelUnitTests=true runs of RapidsShuffleThreadedWriterSuite passed 28/28 each on ae85b3271).

  • Spark 3.5.6 (buildver=356, Scala 2.12, GPU): SpillablePartialFileHandleSuite and RapidsShuffleThreadedWriterSuite passed 55/55.

  • All-module Scalastyle (2,127 files, 0 errors/warnings) and Apache RAT passed.

  • Shim compatibility preflight (base=139e06a62, head=fab06e199): review returned PASS across 34 sql-plugin buildvers (including 400db173 and 410db183, 4,442 checked requirements, 0 new findings). advisory noted file overlap with open PRs #15150, #16041, #17099, #17131, and WIP #17142.

  • Not verified locally: Databricks 17.3/18.3 runtime execution (auto-triggered via spark400db173 shim change).
  • AI assistance from Devin was used to diagnose, implement, and validate this fix.

    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

  • Not required
  • Performance

  • Tests ran and results are added in the PR description

  • Issue filed with a link in the PR description

  • Not required
  • Measured before (5f903a242) vs after (9b9f97200, using the final writeInProgress entry/exit monitor design and non-optional currentPartialFileHandle()) write throughput on RapidsLocalDiskShuffleMapOutputWriter -> PartitionWriterStream.write() -> SpillablePartialFileHandle.write() (MEMORY_WITH_SPILL, 8 partitions, 64 MiB per iteration, 5 warmup + 15 measured iterations, 3 interleaved rounds, Java 17; exercises only the partition-writer write hot path, not RapidsShuffleThreadedWriterBase batch cleanup):

    | Chunk Size | Writes / 64 MiB | Before (5f903a242) | After (9b9f97200) | Delta |
    | --- | ---: | ---: | ---: | ---: |
    | 4 KiB | 16,384 | 27.199 ms (2.30 GiB/s) | 27.819 ms (2.25 GiB/s) | +0.62 ms (+2.3%, ~38 ns/write) |
    | 64 KiB | 1,024 | 27.220 ms (2.30 GiB/s) | 27.343 ms (2.29 GiB/s) | +0.12 ms (+0.45%, noise) |

    RapidsLocalDiskShuffleMapOutputWriter uses @volatile reads on the write path (no extra lock per write), and activeBatches uses an O(1) HashMap keyed by batchId. The NDS SF10 run below was collected on 86d28cdec (prior single-monitor write() design) on a single local node and is scoped to that workload.

    End-to-end NDS SF10 GPU benchmark (19 shuffle-heavy queries: q4, q11, q14a, q14b, q17, q23a, q23b, q25, q29, q50, q64, q67, q72, q74, q75, q78, q80, q93, q95) comparing back-to-back Spark 4.0.1 / Scala 2.13 distribution JARs built from 5f903a242 (before) vs 86d28cdec (after) with identical cuDF (5dfab722b) and JNI (560a5ce8c) snapshots, spark.rapids.shuffle.mode=MULTITHREADED (writer.threads=4, reader.threads=4, pinnedPool.size=2g, local[8], RTX 5880 Ada, ABBA order before_1 -> after_1 -> after_2 -> before_2, 1 warmup + 2 measured passes per JVM; all 19 queries matched exact row counts and output SHA-256 digests, and GpuColumnarExchange plans were verified):

    | Variant | Warmup passes (ms) | Measured 19-query passes (ms) | Median (ms) | Mean (ms) | Delta (After - Before) |
    | --- | --- | --- | ---: | ---: | ---: |
    | Before (5f903a242) | 51,270.0, 51,386.8 | 41,511.3, 41,508.9, 41,432.7, 40,547.5 | 41,470.8 | 41,250.1 | — |
    | After (86d28cdec) | 51,479.3, 50,860.4 | 41,306.7, 40,541.7, 41,507.0, 40,615.4 | 40,961.1 | 40,992.7 | -509.7 ms (-1.23%) median / -257.4 ms (-0.62%) mean |

    Paired ABBA deltas are -585.9 ms (pair 1) and +71.1 ms (pair 2), with the heaviest shuffle queries (q72: +0.18%, q64: -0.96%, q4: -1.12%) all within local run-to-run variance (no measurable regression; local single-node scope).

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: thirtiseven Review duration: 7275m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #17160"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 56.8% · Lower = rushed or shallow review
    56.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: 22.5% · Safe to merge
    22.5%