This is an automated email from the ASF dual-hosted git repository.

SteNicholas pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/celeborn.git


The following commit(s) were added to refs/heads/main by this push:
     new 4474f81760 [MINOR] Fix flaky bytesWritten assertion in 
Hash/SortBasedShuffleWriterSuiteJ caused by a metrics race
4474f81760 is described below

commit 4474f817602ae35e8b1d506fc4a35ea8e02ab349
Author: ForVic <[email protected]>
AuthorDate: Sun Nov 8 12:03:52 2026 +0800

    [MINOR] Fix flaky bytesWritten assertion in 
Hash/SortBasedShuffleWriterSuiteJ caused by a metrics race
    
    ### What changes were proposed in this pull request?
    
    Fix an intermittent failure in `HashBasedShuffleWriterSuiteJ` and 
`SortBasedShuffleWriterSuiteJ`. The exact-count assertion in 
`CelebornShuffleWriterSuiteBase.check()`, added in CELEBORN-2479, sometimes 
fails:
    
    ```java
    assertEquals(expectedCompressedBytes, metrics.bytesWritten());
    ```
    
    It fails with `bytesWritten()` slightly lower than expected. Any test that 
goes through `check()` can hit it, e.g. `testMergeSmallBlock`, 
`testGiantRecord`, `testGiantRecordAndMergeSmallBlock` and their 
`WithFastWrite` variants.
    
    The test is correct. It exposes a real race in the writers, and this PR 
fixes that race:
    
    - In `HashBasedShuffleWriter` and `SortBasedShuffleWriter`, route every 
`ShuffleWriteMetrics.incBytesWritten` call through a private `synchronized` 
helper, including the `afterPush` callback handed to `DataPusher` / 
`SortBasedPusher`.
    - Correct the comment in `HashBasedShuffleWriter.closeWrite()`, which 
wrongly claimed the pusher thread has no in-flight data at that point.
    
    ### Why are the changes needed?
    
    `bytesWritten` is updated from two threads at once:
    
    - the `DataPusher` thread, via the `afterPush` callback after each async 
push, and
    - the task thread, via giant-record pushes during `write()`, the residual 
`mergeData` in `HashBasedShuffleWriter.closeWrite()` (which runs before 
`dataPusher.waitOnTermination()`), and `SortBasedPusher.pushData`'s merge path.
    
    Spark's `LongAccumulator.add` (`_sum += v; _count += 1`) is not atomic, so 
when both threads add at the same time one update can be lost. The test 
compares `bytesWritten` against the exact sum of pushed batch sizes, so a lost 
update makes it fail now and then. In production the only effect is a slightly 
under-reported shuffle "bytes written" metric. `mapStatusLengths` and 
`MapperMetrics` use `LongAdder` and are not affected, so shuffle data and map 
status are correct.
    
    A lock keeps the metric updating live during the task, unlike collecting 
the count and adding it once at close. The lock is taken at most once per push 
batch (each a network push of up to `celeborn.client.push.buffer.max.size`), so 
the added cost is negligible next to the push itself.
    
    ### Does this PR resolve a correctness bug?
    
    - [ ] Yes
    
    It fixes a flaky test and the metrics accuracy bug behind it. Shuffle data 
and map status are unaffected.
    
    ### Does this PR introduce _any_ user-facing change?
    
    - [ ] No
    
    ### How was this patch tested?
    
    `HashBasedShuffleWriterSuiteJ` (12 tests) and 
`SortBasedShuffleWriterSuiteJ` (13 tests) pass locally with Spark 3.5 / JDK 17. 
The race depends on timing, so it can't be reproduced on demand. The existing 
exact-count assertion is the regression check, and it should no longer flake.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Closes #3947 from ForVic/ForVic/fix-bytes-written-race.
    
    Authored-by: ForVic <[email protected]>
    Signed-off-by: Nicholas Jiang <[email protected]>
---
 .../shuffle/celeborn/HashBasedShuffleWriter.java   | 22 +++++++++++++++++-----
 .../shuffle/celeborn/SortBasedShuffleWriter.java   | 16 ++++++++++++++--
 2 files changed, 31 insertions(+), 7 deletions(-)

diff --git 
a/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/HashBasedShuffleWriter.java
 
b/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/HashBasedShuffleWriter.java
index f9c281df9c..3e1f8bc37d 100644
--- 
a/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/HashBasedShuffleWriter.java
+++ 
b/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/HashBasedShuffleWriter.java
@@ -67,6 +67,7 @@ public class HashBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
   private final ShuffleDependency<K, V, C> dep;
   private final Partitioner partitioner;
   private final ShuffleWriteMetricsReporter writeMetrics;
+  private final Object bytesWrittenLock = new Object();
   private final int shuffleId;
   private final int mapId;
   private final int encodedAttemptId;
@@ -157,7 +158,7 @@ public class HashBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
               conf,
               shuffleClient,
               pushTaskQueue,
-              writeMetrics::incBytesWritten,
+              this::incBytesWritten,
               mapStatusLengths);
     } catch (InterruptedException e) {
       TaskInterruptedHelper.throwTaskKillException();
@@ -307,7 +308,7 @@ public class HashBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
             numPartitions);
     long delta = System.nanoTime() - start;
     mapStatusLengths[partitionId].add(bytesWritten);
-    writeMetrics.incBytesWritten(bytesWritten);
+    incBytesWritten(bytesWritten);
     writeMetrics.incWriteTime(delta);
     uncompressedBytesWritten += numBytes;
   }
@@ -347,8 +348,8 @@ public class HashBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
 
   protected void closeWrite() throws IOException {
     // merge and push residual data to reduce network traffic
-    // NB: since dataPusher thread have no in-flight data at this point,
-    //     we now push merged data by task thread will not introduce any 
contention
+    // NB: the dataPusher thread may still have in-flight push tasks at this 
point, so any state
+    //     shared with it (e.g. the bytes-written metric) must be updated 
thread-safely.
     for (int i = 0; i < numPartitions; i++) {
       final int size = sendOffsets[i];
       if (size > 0) {
@@ -374,7 +375,7 @@ public class HashBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
             numMappers,
             numPartitions);
     mapStatusLengths[partitionId].add(bytesWritten);
-    writeMetrics.incBytesWritten(bytesWritten);
+    incBytesWritten(bytesWritten);
     uncompressedBytesWritten += length;
   }
 
@@ -420,6 +421,17 @@ public class HashBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
             bmId, SparkUtils.unwrap(mapStatusLengths), 
taskContext.taskAttemptId());
   }
 
+  /**
+   * Adds to the bytes-written metric. Called from both the task thread and 
the {@link
+   * org.apache.celeborn.client.write.DataPusher} thread, while Spark's metric 
accumulators are not
+   * thread-safe, so updates are serialized to avoid losing increments.
+   */
+  private void incBytesWritten(long bytes) {
+    synchronized (bytesWrittenLock) {
+      writeMetrics.incBytesWritten(bytes);
+    }
+  }
+
   private void updateRecordsWrittenMetrics() {
     writeMetrics.incRecordsWritten(tmpRecordsWritten);
     tmpRecordsWritten = 0;
diff --git 
a/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/SortBasedShuffleWriter.java
 
b/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/SortBasedShuffleWriter.java
index 2440a23b01..4f00d9d514 100644
--- 
a/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/SortBasedShuffleWriter.java
+++ 
b/client-spark/spark-3/src/main/java/org/apache/spark/shuffle/celeborn/SortBasedShuffleWriter.java
@@ -61,6 +61,7 @@ public class SortBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
   private final ShuffleDependency<K, V, C> dep;
   private final Partitioner partitioner;
   private final ShuffleWriteMetricsReporter writeMetrics;
+  private final Object bytesWrittenLock = new Object();
   private final int shuffleId;
   private final int mapId;
   private final int encodedAttemptId;
@@ -154,7 +155,7 @@ public class SortBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
               numMappers,
               numPartitions,
               conf,
-              writeMetrics::incBytesWritten,
+              this::incBytesWritten,
               mapStatusLengths,
               conf.clientPushSortMemoryThreshold(),
               sendBufferPool);
@@ -372,11 +373,22 @@ public class SortBasedShuffleWriter<K, V, C> extends 
ShuffleWriter<K, V> {
             numPartitions);
     long delta = System.nanoTime() - start;
     mapStatusLengths[partitionId].add(bytesWritten);
-    writeMetrics.incBytesWritten(bytesWritten);
+    incBytesWritten(bytesWritten);
     writeMetrics.incWriteTime(delta);
     giantRecordBytesWritten += numBytes;
   }
 
+  /**
+   * Adds to the bytes-written metric. Called from both the task thread and 
the {@link
+   * org.apache.celeborn.client.write.DataPusher} thread, while Spark's metric 
accumulators are not
+   * thread-safe, so updates are serialized to avoid losing increments.
+   */
+  private void incBytesWritten(long bytes) {
+    synchronized (bytesWrittenLock) {
+      writeMetrics.incBytesWritten(bytes);
+    }
+  }
+
   private void cleanupPusher() throws IOException {
     if (pusher != null) {
       pusher.close(false);

Reply via email to