GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [SPARK-56279][CORE] Enable zero-copy sendfile for FileRegion in native Netty transports by LuciferYang · Pull Request #55087 · apache/spark

Conversation

@LuciferYang

@LuciferYang LuciferYang commented Mar 30, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

What changes were proposed in this pull request?

This PR modifies MessageEncoder to emit the header ByteBuf and FileRegion as separate objects in the outbound message list when the body is a FileRegion backed by FileSegmentManagedBuffer, instead of wrapping them together in a MessageWithHeader.

Previously, all messages with a body were unconditionally wrapped in MessageWithHeader. This caused native transports (EPOLL, KQUEUE) to fall into a generic FileRegion.transferTo() fallback path that copies data through user-space, bypassing the optimized sendfile() / splice() zero-copy path that Netty's native transports provide.

The split is only applied when the ManagedBuffer is a FileSegmentManagedBuffer, whose release() is a no-op, making it safe to emit the FileRegion independently of write lifecycle management. Other ManagedBuffer types (e.g., BlockManagerManagedBuffer) still use the MessageWithHeader wrapper because they perform resource cleanup in release() that must be tied to MessageWithHeader.deallocate().

Why are the changes needed?

When using native transports (AUTO/EPOLL on Linux), file-backed shuffle fetch performance was severely degraded compared to NIO mode. The root cause lies in how Netty's native transports dispatch FileRegion writes.

In AbstractEpollStreamChannel.doWriteSingle() (and the analogous KQueue path), Netty uses an instanceof check to choose between two write strategies:

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L474-L493

} else if (msg instanceof DefaultFileRegion) {
    return writeDefaultFileRegion(in, (DefaultFileRegion) msg);  // → socket.sendFile() (zero-copy)
} else if (msg instanceof FileRegion) {
    return writeFileRegion(in, (FileRegion) msg);                // → region.transferTo() (user-space copy)
}
  • writeDefaultFileRegion() calls socket.sendFile(), which maps directly to the Linux sendfile() syscall — a true zero-copy path where data is transferred from the file page cache to the socket buffer entirely within the kernel, with no user-space copy.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L367-L386

    private int writeDefaultFileRegion(ChannelOutboundBuffer in, DefaultFileRegion region) throws Exception {
        final long offset = region.transferred();
        final long regionCount = region.count();
        if (offset >= regionCount) {
            in.remove();
            return 0;
        }

        final long flushedAmount = socket.sendFile(region, region.position(), offset, regionCount - offset);
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= regionCount) {
                in.remove();
            }
            return 1;
        } else if (flushedAmount == 0) {
            validateFileRegion(region, offset);
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
  • writeFileRegion() falls back to region.transferTo(WritableByteChannel), which writes data through a SocketWritableByteChannel wrapper — effectively a user-space copy path.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L402-L420

private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception {
        if (region.transferred() >= region.count()) {
            in.remove();
            return 0;
        }

        if (byteChannel == null) {
            byteChannel = new EpollSocketWritableByteChannel();
        }
        final long flushedAmount = region.transferTo(byteChannel, region.transferred());
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= region.count()) {
                in.remove();
            }
            return 1;
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }

Spark's MessageWithHeader extends AbstractFileRegion (not DefaultFileRegion). When MessageEncoder wraps a DefaultFileRegion body inside MessageWithHeader, the resulting object is a generic FileRegion from Netty's perspective. This means Netty dispatches it to the writeFileRegion() fallback, which calls MessageWithHeader.transferTo():

// MessageWithHeader.java, line 121
if (body instanceof FileRegion fileRegion) {
    writtenBody = fileRegion.transferTo(target, totalBytesTransferred - headerLength);
}

Here, even though the inner body is a DefaultFileRegion, its transferTo() is invoked with a WritableByteChannel (not a file descriptor), so the data is read from the file into a user-space buffer and then written to the socket — the zero-copy opportunity is lost.

By emitting the DefaultFileRegion directly into Netty's outbound buffer (instead of wrapping it in MessageWithHeader), Netty's native transport recognizes it via instanceof DefaultFileRegion and routes it to socket.sendFile(), restoring the zero-copy sendfile() path.

Benchmark results (File-Backed Shuffle Fetch) show dramatic improvement:

Scenario Before (ms) After (ms) Improvement
AUTO, sequential fetch (JDK17) 2075 362 ~5.7x faster
AUTO, parallel fetch (JDK17) 676 202 ~3.3x faster
AUTO, sequential fetch (JDK21) 2093 360 ~5.8x faster
AUTO, parallel fetch (JDK21) 677 204 ~3.3x faster
AUTO, sequential fetch (JDK25) 1918 411 ~4.7x faster
AUTO, parallel fetch (JDK25) 652 196 ~3.3x faster

With this fix, AUTO (EPOLL) mode now matches or exceeds NIO performance for file-backed shuffle fetches, achieving the expected ~1.0X relative performance (previously ~0.2X).

Does this PR introduce any user-facing change?

No. This is an internal optimization to the Netty transport layer. Users benefit from improved shuffle fetch performance when using native transports (the default on Linux) without any configuration changes.

How was this patch tested?

  • Updated MergedBlockMetaSuccessSuite to validate the new encoder output format (2 separate objects: ByteBuf header + DefaultFileRegion, instead of a single MessageWithHeader).
  • Re-ran NettyTransportBenchmark across JDK 17, JDK 21, and JDK 25 to confirm the performance improvement. Updated benchmark result files accordingly.

Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code 4.6

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@LuciferYang
fix
64e30c8
@LuciferYang LuciferYang changed the title [SPARK-56279][CORE] Enable native zero-copy sendfile for file-backed shuffle transfer [SPARK-56279][CORE] Enable zero-copy sendfile for FileRegion in native Netty transports Mar 30, 2026
dongjoon-hyun
dongjoon-hyun reviewed Mar 30, 2026
View reviewed changes
Comment thread core/benchmarks/NettyTransportBenchmark-jdk21-results.txt
AUTO, parallel fetch (4 clients) 677 787 113 0.0 6769621.7 0.5X
NIO, sequential fetch 366 372 9 0.0 3655386.3 1.0X
NIO, parallel fetch (4 clients) 200 211 11 0.0 2002026.0 1.8X
AUTO, sequential fetch 360 369 13 0.0 3600497.3 1.0X

@dongjoon-hyun dongjoon-hyun Mar 30, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
dongjoon-hyun
dongjoon-hyun reviewed Mar 30, 2026
View reviewed changes
Comment thread core/benchmarks/NettyTransportBenchmark-results.txt
AUTO, parallel fetch (4 clients) 676 814 129 0.0 6757222.9 0.6X
NIO, sequential fetch 384 386 3 0.0 3844405.1 1.0X
NIO, parallel fetch (4 clients) 209 217 9 0.0 2091358.0 1.8X
AUTO, sequential fetch 362 372 14 0.0 3615964.2 1.1X

@dongjoon-hyun dongjoon-hyun Mar 30, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, too.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
dongjoon-hyun
dongjoon-hyun reviewed Mar 30, 2026
View reviewed changes
Comment thread core/benchmarks/NettyTransportBenchmark-jdk25-results.txt
AUTO, parallel fetch (4 clients) 652 730 116 0.0 6517014.3 0.6X
NIO, sequential fetch 411 419 13 0.0 4112689.7 1.0X
NIO, parallel fetch (4 clients) 213 214 1 0.0 2131475.4 1.9X
AUTO, sequential fetch 411 416 4 0.0 4112489.8 1.0X

@dongjoon-hyun dongjoon-hyun Mar 30, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
dongjoon-hyun
dongjoon-hyun reviewed Mar 30, 2026
View reviewed changes

@dongjoon-hyun dongjoon-hyun left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you so much, @LuciferYang !

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
dongjoon-hyun
dongjoon-hyun reviewed Mar 30, 2026
View reviewed changes
Comment thread common/network-common/src/main/java/org/apache/spark/network/protocol/MessageEncoder.java
out.add(new MessageWithHeader(in.body(), header, body, bodyLength));
if (body instanceof FileRegion && in.body() instanceof FileSegmentManagedBuffer) {
// Emit header and FileRegion as separate objects so that native transports
// (EPOLL, KQUEUE) can apply zero-copy sendfile/splice on the FileRegion directly.

@dongjoon-hyun dongjoon-hyun Mar 30, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for adding this comment. It's really tricky.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dongjoon-hyun

dongjoon-hyun commented Mar 30, 2026

Copy link
Copy Markdown
Member

cc @yaooqinn , too

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LuciferYang

LuciferYang commented Mar 30, 2026

Copy link
Copy Markdown
Contributor Author

Additionally, I have also submitted a PR in the Netty community to explore the possibility of using io_uring in Apache Spark going forward.

  • Add generic FileRegion support in io_uring stream channel netty/netty#16571
dongjoon-hyun reacted with thumbs up emoji dongjoon-hyun reacted with heart emoji
All reactions
  • 👍 1 reaction
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

dongjoon-hyun
dongjoon-hyun approved these changes Mar 30, 2026
View reviewed changes

@dongjoon-hyun dongjoon-hyun left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1, LGTM (Pending CIs).

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dongjoon-hyun

dongjoon-hyun commented Mar 30, 2026

Copy link
Copy Markdown
Member

I converted SPARK-56279 as a bug because this was a regression at 4.1.x. Can we have this at branch-4.1 too, @LuciferYang ? I'm also okay to backport the Netty benchmark to branch-4.1 too.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LuciferYang

LuciferYang commented Mar 30, 2026

Copy link
Copy Markdown
Contributor Author

I converted SPARK-56279 as a bug because this was a regression at 4.1.x. Can we have this at branch-4.1 too, @LuciferYang ? I'm also okay to backport the Netty benchmark to branch-4.1 too.

Okay, I will manually check them later and backport them to branch-4.1.

dongjoon-hyun reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dongjoon-hyun

dongjoon-hyun commented Mar 30, 2026

Copy link
Copy Markdown
Member

Thank you so much!

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LuciferYang

LuciferYang commented Mar 30, 2026

Copy link
Copy Markdown
Contributor Author

All test passed

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@LuciferYang LuciferYang closed this in 15ffa54 Mar 30, 2026
@LuciferYang

LuciferYang commented Mar 30, 2026

Copy link
Copy Markdown
Contributor Author

Merged into master. Thanks @dongjoon-hyun
For branch-4.1, I will submit a separate pr later.

dongjoon-hyun reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

LuciferYang added a commit to LuciferYang/spark that referenced this pull request Mar 31, 2026
@LuciferYang
[SPARK-56279][CORE] Enable zero-copy sendfile for FileRegion in nativ…
982dc46
…e Netty transports

This PR modifies `MessageEncoder` to emit the header `ByteBuf` and `FileRegion` as **separate objects** in the outbound message list when the body is a `FileRegion` backed by `FileSegmentManagedBuffer`, instead of wrapping them together in a `MessageWithHeader`.

Previously, all messages with a body were unconditionally wrapped in `MessageWithHeader`. This caused native transports (EPOLL, KQUEUE) to fall into a generic `FileRegion.transferTo()` fallback path that copies data through user-space, bypassing the optimized `sendfile()` / `splice()` zero-copy path that Netty's native transports provide.

The split is only applied when the `ManagedBuffer` is a `FileSegmentManagedBuffer`, whose `release()` is a no-op, making it safe to emit the `FileRegion` independently of write lifecycle management. Other `ManagedBuffer` types (e.g., `BlockManagerManagedBuffer`) still use the `MessageWithHeader` wrapper because they perform resource cleanup in `release()` that must be tied to `MessageWithHeader.deallocate()`.

When using native transports (AUTO/EPOLL on Linux), file-backed shuffle fetch performance was severely degraded compared to NIO mode. The root cause lies in how Netty's native transports dispatch `FileRegion` writes.

In `AbstractEpollStreamChannel.doWriteSingle()` (and the analogous KQueue path), Netty uses an `instanceof` check to choose between two write strategies:

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L474-L493

```java
} else if (msg instanceof DefaultFileRegion) {
    return writeDefaultFileRegion(in, (DefaultFileRegion) msg);  // → socket.sendFile() (zero-copy)
} else if (msg instanceof FileRegion) {
    return writeFileRegion(in, (FileRegion) msg);                // → region.transferTo() (user-space copy)
}
```

- **`writeDefaultFileRegion()`** calls `socket.sendFile()`, which maps directly to the Linux `sendfile()` syscall — a true zero-copy path where data is transferred from the file page cache to the socket buffer entirely within the kernel, with no user-space copy.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L367-L386

```java
    private int writeDefaultFileRegion(ChannelOutboundBuffer in, DefaultFileRegion region) throws Exception {
        final long offset = region.transferred();
        final long regionCount = region.count();
        if (offset >= regionCount) {
            in.remove();
            return 0;
        }

        final long flushedAmount = socket.sendFile(region, region.position(), offset, regionCount - offset);
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= regionCount) {
                in.remove();
            }
            return 1;
        } else if (flushedAmount == 0) {
            validateFileRegion(region, offset);
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
```

- **`writeFileRegion()`** falls back to `region.transferTo(WritableByteChannel)`, which writes data through a `SocketWritableByteChannel` wrapper — effectively a user-space copy path.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L402-L420

```java
private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception {
        if (region.transferred() >= region.count()) {
            in.remove();
            return 0;
        }

        if (byteChannel == null) {
            byteChannel = new EpollSocketWritableByteChannel();
        }
        final long flushedAmount = region.transferTo(byteChannel, region.transferred());
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= region.count()) {
                in.remove();
            }
            return 1;
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
```

Spark's `MessageWithHeader extends AbstractFileRegion` (not `DefaultFileRegion`). When `MessageEncoder` wraps a `DefaultFileRegion` body inside `MessageWithHeader`, the resulting object is a generic `FileRegion` from Netty's perspective. This means Netty dispatches it to the `writeFileRegion()` fallback, which calls `MessageWithHeader.transferTo()`:

```java
// MessageWithHeader.java, line 121
if (body instanceof FileRegion fileRegion) {
    writtenBody = fileRegion.transferTo(target, totalBytesTransferred - headerLength);
}
```

Here, even though the inner body is a `DefaultFileRegion`, its `transferTo()` is invoked with a `WritableByteChannel` (not a file descriptor), so the data is read from the file into a user-space buffer and then written to the socket — **the zero-copy opportunity is lost**.

By emitting the `DefaultFileRegion` directly into Netty's outbound buffer (instead of wrapping it in `MessageWithHeader`), Netty's native transport recognizes it via `instanceof DefaultFileRegion` and routes it to `socket.sendFile()`, restoring the zero-copy `sendfile()` path.

**Benchmark results (File-Backed Shuffle Fetch) show dramatic improvement:**

| Scenario | Before (ms) | After (ms) | Improvement |
|---|---|---|---|
| AUTO, sequential fetch (JDK17) | 2075 | 362 | **~5.7x faster** |
| AUTO, parallel fetch (JDK17) | 676 | 202 | **~3.3x faster** |
| AUTO, sequential fetch (JDK21) | 2093 | 360 | **~5.8x faster** |
| AUTO, parallel fetch (JDK21) | 677 | 204 | **~3.3x faster** |
| AUTO, sequential fetch (JDK25) | 1918 | 411 | **~4.7x faster** |
| AUTO, parallel fetch (JDK25) | 652 | 196 | **~3.3x faster** |

With this fix, AUTO (EPOLL) mode now matches or exceeds NIO performance for file-backed shuffle fetches, achieving the expected ~1.0X relative performance (previously ~0.2X).

No. This is an internal optimization to the Netty transport layer. Users benefit from improved shuffle fetch performance when using native transports (the default on Linux) without any configuration changes.

- Updated `MergedBlockMetaSuccessSuite` to validate the new encoder output format (2 separate objects: `ByteBuf` header + `DefaultFileRegion`, instead of a single `MessageWithHeader`).
- Re-ran `NettyTransportBenchmark` across JDK 17, JDK 21, and JDK 25 to confirm the performance improvement. Updated benchmark result files accordingly.

Generated-by:  Claude Code 4.6

Closes apache#55087 from LuciferYang/SPARK-56279.

Authored-by: yangjie01 <[email protected]>
Signed-off-by: yangjie01 <[email protected]>
@SteNicholas SteNicholas mentioned this pull request Apr 6, 2026
[CELEBORN-2301] MessageEncoder enables zero-copy sendfile for FileRegion in Netty native transports apache/celeborn#3649
Closed
SteNicholas added a commit to apache/celeborn that referenced this pull request Apr 15, 2026
@SteNicholas @pan3793
[CELEBORN-2301] MessageEncoder enables zero-copy sendfile for FileReg…
95419e1
…ion in Netty native transports

### What changes were proposed in this pull request?

`MessageEncoder` enables zero-copy sendfile for `FileRegion` in Netty native transports, which emits the header `ByteBuf` and `FileRegion` as **separate objects** in the outbound message list when the body is a `FileRegion` backed by `FileSegmentManagedBuffer`, instead of wrapping them together in a `MessageWithHeader`.

Previously, all messages with a body were unconditionally wrapped in `MessageWithHeader`. This caused native transports (EPOLL, KQUEUE) to fall into a generic `FileRegion.transferTo()` fallback path that copies data through user-space, bypassing the optimized `sendfile()` / `splice()` zero-copy path that Netty's native transports provide.

The split is only applied when the `ManagedBuffer` is a `FileSegmentManagedBuffer`, whose `release()` is a no-op, making it safe to emit the `FileRegion` independently of write lifecycle management. Other `ManagedBuffer` types (e.g., `BlockManagerManagedBuffer`) still use the `MessageWithHeader` wrapper because they perform resource cleanup in `release()` that must be tied to `MessageWithHeader.deallocate()`.

Backport: apache/spark#55087.

### Why are the changes needed?

When using native transports (AUTO/EPOLL on Linux), file-backed shuffle fetch performance was severely degraded compared to NIO mode. The root cause lies in how Netty's native transports dispatch `FileRegion` writes.

In `AbstractEpollStreamChannel.doWriteSingle()` (and the analogous KQueue path), Netty uses an `instanceof` check to choose between two write strategies:

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L474-L493

```java
} else if (msg instanceof DefaultFileRegion) {
    return writeDefaultFileRegion(in, (DefaultFileRegion) msg);  // → socket.sendFile() (zero-copy)
} else if (msg instanceof FileRegion) {
    return writeFileRegion(in, (FileRegion) msg);                // → region.transferTo() (user-space copy)
}
```

- **`writeDefaultFileRegion()`** calls `socket.sendFile()`, which maps directly to the Linux `sendfile()` syscall — a true zero-copy path where data is transferred from the file page cache to the socket buffer entirely within the kernel, with no user-space copy.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L367-L386

```java
    private int writeDefaultFileRegion(ChannelOutboundBuffer in, DefaultFileRegion region) throws Exception {
        final long offset = region.transferred();
        final long regionCount = region.count();
        if (offset >= regionCount) {
            in.remove();
            return 0;
        }

        final long flushedAmount = socket.sendFile(region, region.position(), offset, regionCount - offset);
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= regionCount) {
                in.remove();
            }
            return 1;
        } else if (flushedAmount == 0) {
            validateFileRegion(region, offset);
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
```

- **`writeFileRegion()`** falls back to `region.transferTo(WritableByteChannel)`, which writes data through a `SocketWritableByteChannel` wrapper — effectively a user-space copy path.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L402-L420

```java
private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception {
        if (region.transferred() >= region.count()) {
            in.remove();
            return 0;
        }

        if (byteChannel == null) {
            byteChannel = new EpollSocketWritableByteChannel();
        }
        final long flushedAmount = region.transferTo(byteChannel, region.transferred());
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= region.count()) {
                in.remove();
            }
            return 1;
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
```

Spark's `MessageWithHeader extends AbstractFileRegion` (not `DefaultFileRegion`). When `MessageEncoder` wraps a `DefaultFileRegion` body inside `MessageWithHeader`, the resulting object is a generic `FileRegion` from Netty's perspective. This means Netty dispatches it to the `writeFileRegion()` fallback, which calls `MessageWithHeader.transferTo()`:

```java
// MessageWithHeader.java, line 121
if (body instanceof FileRegion fileRegion) {
    writtenBody = fileRegion.transferTo(target, totalBytesTransferred - headerLength);
}
```

Here, even though the inner body is a `DefaultFileRegion`, its `transferTo()` is invoked with a `WritableByteChannel` (not a file descriptor), so the data is read from the file into a user-space buffer and then written to the socket — **the zero-copy opportunity is lost**.

By emitting the `DefaultFileRegion` directly into Netty's outbound buffer (instead of wrapping it in `MessageWithHeader`), Netty's native transport recognizes it via `instanceof DefaultFileRegion` and routes it to `socket.sendFile()`, restoring the zero-copy `sendfile()` path.

**Benchmark results (File-Backed Shuffle Fetch) show dramatic improvement:**

| Scenario | Before (ms) | After (ms) | Improvement |
|---|---|---|---|
| EPOLL, sequential fetch (JDK8) | 524 | 134 | **~3.9x faster** |
| EPOLL, parallel fetch (JDK8) | 191 | 55 | **~3.4x faster** |

### Does this PR resolve a correctness bug?

No.

### Does this PR introduce _any_ user-facing change?

No. This is an internal optimization to the Netty transport layer. Users benefit from improved shuffle fetch performance when using native transports (the default on Linux) without any configuration changes.

### How was this patch tested?

- Re-ran `NettyTransportBenchmark` with JDK8 to confirm the performance improvement. Updated benchmark result files accordingly.

Closes #3649 from SteNicholas/CELEBORN-2301.

Lead-authored-by: SteNicholas <[email protected]>
Co-authored-by: Cheng Pan <[email protected]>
Signed-off-by: SteNicholas <[email protected]>
akpatnam25 pushed a commit to akpatnam25/incubator-celeborn that referenced this pull request May 15, 2026
@SteNicholas @pan3793 @akpatnam25
[CELEBORN-2301] MessageEncoder enables zero-copy sendfile for FileReg…
3d7e190
…ion in Netty native transports

### What changes were proposed in this pull request?

`MessageEncoder` enables zero-copy sendfile for `FileRegion` in Netty native transports, which emits the header `ByteBuf` and `FileRegion` as **separate objects** in the outbound message list when the body is a `FileRegion` backed by `FileSegmentManagedBuffer`, instead of wrapping them together in a `MessageWithHeader`.

Previously, all messages with a body were unconditionally wrapped in `MessageWithHeader`. This caused native transports (EPOLL, KQUEUE) to fall into a generic `FileRegion.transferTo()` fallback path that copies data through user-space, bypassing the optimized `sendfile()` / `splice()` zero-copy path that Netty's native transports provide.

The split is only applied when the `ManagedBuffer` is a `FileSegmentManagedBuffer`, whose `release()` is a no-op, making it safe to emit the `FileRegion` independently of write lifecycle management. Other `ManagedBuffer` types (e.g., `BlockManagerManagedBuffer`) still use the `MessageWithHeader` wrapper because they perform resource cleanup in `release()` that must be tied to `MessageWithHeader.deallocate()`.

Backport: apache/spark#55087.

### Why are the changes needed?

When using native transports (AUTO/EPOLL on Linux), file-backed shuffle fetch performance was severely degraded compared to NIO mode. The root cause lies in how Netty's native transports dispatch `FileRegion` writes.

In `AbstractEpollStreamChannel.doWriteSingle()` (and the analogous KQueue path), Netty uses an `instanceof` check to choose between two write strategies:

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L474-L493

```java
} else if (msg instanceof DefaultFileRegion) {
    return writeDefaultFileRegion(in, (DefaultFileRegion) msg);  // → socket.sendFile() (zero-copy)
} else if (msg instanceof FileRegion) {
    return writeFileRegion(in, (FileRegion) msg);                // → region.transferTo() (user-space copy)
}
```

- **`writeDefaultFileRegion()`** calls `socket.sendFile()`, which maps directly to the Linux `sendfile()` syscall — a true zero-copy path where data is transferred from the file page cache to the socket buffer entirely within the kernel, with no user-space copy.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L367-L386

```java
    private int writeDefaultFileRegion(ChannelOutboundBuffer in, DefaultFileRegion region) throws Exception {
        final long offset = region.transferred();
        final long regionCount = region.count();
        if (offset >= regionCount) {
            in.remove();
            return 0;
        }

        final long flushedAmount = socket.sendFile(region, region.position(), offset, regionCount - offset);
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= regionCount) {
                in.remove();
            }
            return 1;
        } else if (flushedAmount == 0) {
            validateFileRegion(region, offset);
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
```

- **`writeFileRegion()`** falls back to `region.transferTo(WritableByteChannel)`, which writes data through a `SocketWritableByteChannel` wrapper — effectively a user-space copy path.

https://github.com/netty/netty/blob/eeb5674526f0b49a142580686a5a9a7147ddadec/transport-classes-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java#L402-L420

```java
private int writeFileRegion(ChannelOutboundBuffer in, FileRegion region) throws Exception {
        if (region.transferred() >= region.count()) {
            in.remove();
            return 0;
        }

        if (byteChannel == null) {
            byteChannel = new EpollSocketWritableByteChannel();
        }
        final long flushedAmount = region.transferTo(byteChannel, region.transferred());
        if (flushedAmount > 0) {
            in.progress(flushedAmount);
            if (region.transferred() >= region.count()) {
                in.remove();
            }
            return 1;
        }
        return WRITE_STATUS_SNDBUF_FULL;
    }
```

Spark's `MessageWithHeader extends AbstractFileRegion` (not `DefaultFileRegion`). When `MessageEncoder` wraps a `DefaultFileRegion` body inside `MessageWithHeader`, the resulting object is a generic `FileRegion` from Netty's perspective. This means Netty dispatches it to the `writeFileRegion()` fallback, which calls `MessageWithHeader.transferTo()`:

```java
// MessageWithHeader.java, line 121
if (body instanceof FileRegion fileRegion) {
    writtenBody = fileRegion.transferTo(target, totalBytesTransferred - headerLength);
}
```

Here, even though the inner body is a `DefaultFileRegion`, its `transferTo()` is invoked with a `WritableByteChannel` (not a file descriptor), so the data is read from the file into a user-space buffer and then written to the socket — **the zero-copy opportunity is lost**.

By emitting the `DefaultFileRegion` directly into Netty's outbound buffer (instead of wrapping it in `MessageWithHeader`), Netty's native transport recognizes it via `instanceof DefaultFileRegion` and routes it to `socket.sendFile()`, restoring the zero-copy `sendfile()` path.

**Benchmark results (File-Backed Shuffle Fetch) show dramatic improvement:**

| Scenario | Before (ms) | After (ms) | Improvement |
|---|---|---|---|
| EPOLL, sequential fetch (JDK8) | 524 | 134 | **~3.9x faster** |
| EPOLL, parallel fetch (JDK8) | 191 | 55 | **~3.4x faster** |

### Does this PR resolve a correctness bug?

No.

### Does this PR introduce _any_ user-facing change?

No. This is an internal optimization to the Netty transport layer. Users benefit from improved shuffle fetch performance when using native transports (the default on Linux) without any configuration changes.

### How was this patch tested?

- Re-ran `NettyTransportBenchmark` with JDK8 to confirm the performance improvement. Updated benchmark result files accordingly.

Closes apache#3649 from SteNicholas/CELEBORN-2301.

Lead-authored-by: SteNicholas <[email protected]>
Co-authored-by: Cheng Pan <[email protected]>
Signed-off-by: SteNicholas <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@dongjoon-hyun dongjoon-hyun dongjoon-hyun approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@LuciferYang @dongjoon-hyun
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.