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 — FlowControlHandler: preserve reads requested during a read cycle by Asthenia0412 · Pull Request #17647 · netty/netty

Conversation

@Asthenia0412

@Asthenia0412 Asthenia0412 commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Motivation

When auto-read is disabled, a downstream handler can request the next read re-entrantly while processing a message. FlowControlHandler currently consumes that request when the current upstream read cycle completes, which can leave a relay stalled. The issue reproducer stopped after forwarding about 34,750 bytes of a 1 MiB request.

Modification

Keep reads requested after the last delivered message outstanding for the next upstream read cycle. Add an EmbeddedChannel regression test for the read-complete ordering and a socket-based HTTP relay test matching the reported scenario.

Result

Both regression tests reproduce the stall before the fix and pass with the updated read-cycle accounting.

Fixes #17628

Tests

  • mvn -pl codec-http -am '-Dtest=FlowControlHandlerTest,HttpServerCodecFlowControlTest' -Dsurefire.failIfNoSpecifiedTests=false test

Sorry, something went wrong.

Uh oh!

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

All reactions
allthingssecurity
allthingssecurity reviewed Sep 29, 2026
View reviewed changes

@allthingssecurity allthingssecurity left a comment

Copy link
Copy Markdown
Contributor

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.

Thanks for picking this up. I ran the change against our reproducers for #17628 and #17050.

Verified: it fixes the reported case.

  • On 4.1 without the fix, HttpServerCodecFlowControlTest stalls at 34,750 of 1,048,576 bytes and
    testReadIssuedAfterMessageSurvivesSameReadComplete fails.
  • With this PR, both pass, and so do all 22 FlowControlHandlerTest tests.
  • A standalone reproducer has a reader that calls read() from channelRead(), and the next message arrives in a later
    read cycle. Its stall count drops from 10/10 to 0/10 on NIO, and from 1000/1000 to 0/1000 on EmbeddedChannel.
  • I also used a randomized model of the NIO read loop. A fake transport honours readPending, and each read cycle
    delivers 1 to 3 messages. The reader either reads re-entrantly, reads later from a task, mixes the two, or reads on
    channelReadComplete. Over 2,000 schedules per reader, there were no stalls and no message was delivered without a
    matching read().

Still stalls: a read cycle that delivers no message.

channelReadComplete now sets unsatisfiedReads = readsAfterLastMessage (FlowControlHandler.java:225). If the
upstream cycle had no channelRead at all, readsAfterLastMessage is 0. Every outstanding read() is then consumed,
just as before this PR. The transport, however, keeps reading, so the next message is queued with
unsatisfiedReads == 0 and never delivered.

This happens routinely:

  • A decoder in front of the handler receives a partial frame. ByteToMessageDecoder emits nothing, calls ctx.read()
    itself, and fires channelReadComplete (ByteToMessageDecoder.java:369-374).
  • NIO does the same on a zero-byte read: readPending stays true and channelReadComplete still fires
    (AbstractNioByteChannel.java:156-175).

Measured with this PR:

  • Chunked relay. This is the #17628 relay, with the body sent as Transfer-Encoding: chunked and each chunk-size
    line split across two TCP writes ("40", then "00\r\n" + 16 KiB + "\r\n"). It stalls 10/10, after relaying 64 to
    320 KiB of 1 MiB. The same relay with Content-Length passes 10/10.
  • Split frame. With FixedLengthFrameDecoder(4), a FlowControlHandler and a reader that asks for one message at
    a time, a frame split across two reads stalls 20/20 on NIO when the reader calls read() inside channelRead(). It
    also stalls, on both NIO and EmbeddedChannel, when the reader calls read() from a later task.
  • Randomized model. When cycles with no message are allowed, 1,961 of 2,000 schedules stall.

These two tests fail with this PR (and on 4.1). They could go into FlowControlHandlerTest:

@Test
public void testReadSurvivesUpstreamCycleWithoutMessage() throws Exception {
    final List<String> received = new ArrayList<String>();
    EmbeddedChannel channel = new EmbeddedChannel(false, false, new FlowControlHandler(),
            new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    received.add((String) msg);
                }
            });
    channel.config().setAutoRead(false);
    channel.register();

    channel.read();
    channel.flushInbound();          // upstream read cycle that produced nothing (e.g. a partial frame)
    channel.writeInbound("msg");     // the transport keeps reading: the read() is still outstanding

    assertEquals(Arrays.asList("msg"), received);   // was: []
    assertFalse(channel.finishAndReleaseAll());
}

@Test
public void testReadInChannelReadSurvivesFrameSplitAcrossReads() throws Exception {
    final List<String> received = new ArrayList<String>();
    EmbeddedChannel channel = new EmbeddedChannel(false, false, new FixedLengthFrameDecoder(4),
            new FlowControlHandler(),
            new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    received.add(((ByteBuf) msg).toString(CharsetUtil.US_ASCII));
                    ReferenceCountUtil.release(msg);
                    ctx.read();
                }
            });
    channel.config().setAutoRead(false);
    channel.register();

    channel.read();
    channel.writeInbound(Unpooled.copiedBuffer("m1..", CharsetUtil.US_ASCII));
    channel.writeInbound(Unpooled.copiedBuffer("m2", CharsetUtil.US_ASCII));   // half a frame, no message
    channel.writeInbound(Unpooled.copiedBuffer("..", CharsetUtil.US_ASCII));

    assertEquals(Arrays.asList("m1..", "m2.."), received);   // was: [m1..]
    assertFalse(channel.finishAndReleaseAll());
}

A smaller change that covers both cases. Keep the 4.1 code as it is and delete only the reset in
channelReadComplete (unsatisfiedReads = 0;, line 208 before this PR). Keep the if that decides whether to forward
the completion. The patch adds no fields. With it:

  • all of these pass: the two tests above, your new testReadIssuedAfterMessageSurvivesSameReadComplete,
    HttpServerCodecFlowControlTest, and HttpContentDecompressorTest (the reproducer from #16837);
  • the randomized model shows 0 of 2,000 stalls for every reader, with or without empty cycles, and never delivers a
    message without a matching read();
  • the chunked relay stalls 0/10, and the split frame 0/10.

Only one existing assertion changes: the last block of testMultipleReadsOnEmptyQueue (lines 845-849, "quick check
that internal state is not broken"). It asserts that msg2 is not delivered after three read() calls and an empty
cycle, and that is the #17628 stall. With the change, lines 849-850 become assertEquals(2, reads.get()) and
assertEquals(3, readCompletes.get()). The assertions after the following read() stay as they are. I checked the
whole sequence with the one-line variant (reads/readCompletes after each step): 1/0, 1/1, 1/2, 2/3, 2/3.

The trade-off is that outstanding reads now survive empty cycles, so N read() calls give N messages. That matches the
class javadoc ("only one message per read()") and the behaviour before #16837. The maintainers should confirm it is
the intended contract (see the discussion in #17046).

Minor. readsAfterLastMessage++ (line 179) runs before dequeue(), and nothing undoes it when that same read()
is satisfied from the queue. On EmbeddedChannel, this sequence delivers both a and b for a single read():

writeOneInbound("a"); writeOneInbound("b"); read(); flushInbound(); writeInbound("c")

It needs a read() served from the queue between channelRead and channelReadComplete. I could not produce that on a
real transport, so this is low priority. It also disappears with the one-line variant.

About #17046. That PR targets 4.2. It re-issues ctx.read() from channelReadComplete while reads are
outstanding, which also covers empty cycles: it had 0 stalls in all the runs above. But two of the open blockers raised
in its review still reproduce:

  • A reader that takes one message at a time never gets a channelReadComplete. The count was 0 in both the split-frame
    and the read-in-read runs.
  • setAutoRead(true) does not forward a read upstream: 0 upstream reads.

So neither PR supersedes the other. This one is closer to mergeable once the empty-cycle case is handled.

Claude Code on behalf of allthingssecurity

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java Resolved

Uh oh!

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

Comment thread handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java Resolved

Uh oh!

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

Asthenia0412 and others added 2 commits October 13, 2026 15:12
@Asthenia0412 Trae Agent
FlowControlHandler: preserve reads requested during a read cycle
9337891
yancy Trae Agent
[Fix] Keep reads pending across empty read cycles
f99f811
@Asthenia0412
Asthenia0412 force-pushed the codex/fix-17628-flow-control-relay-stall branch from 7f2c328 to f99f811 Compare October 13, 2026 15:12
@testlens-app

testlens-app Bot commented Oct 13, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown

🚨 Jobs failed without executing tests 🚨

Failed Jobs without Test Failures

❌ Build PR / verify-pr
❌ CodeQL / Analyze (cpp)
❌ CodeQL / Analyze (java)

🏷️ Commit: f99f811
▶️ Tests: 0 executed
⚪️ Checks: 8/8 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

All reactions

Sorry, something went wrong.

Uh oh!

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

@hachen-r7

hachen-r7 commented Nov 12, 2026

Copy link
Copy Markdown

Hi @Asthenia0412, thanks for this fix. #17628 is blocking a Netty upgrade for us, so I'd like to help get this merged. Here is a follow-up patch on top of the PR head (f99f81140d) that should unblock it:

  1. CI fix. verify-pr fails at compile time because 4.1 builds with -source 1.6, and HttpServerCodecFlowControlTest uses lambdas, try-with-resources and StandardCharsets. The patch rewrites those with anonymous classes, an explicit finally, and CharsetUtil.US_ASCII.
  2. Simplification. After the second commit, readCycleHasMessage and readsAfterLastMessage are written but never read, so nothing depends on them. The effective change is only that channelReadComplete no longer resets unsatisfiedReads. The patch removes the two fields and updates the unsatisfiedReads javadoc, which still says an upstream channelReadComplete satisfies a read. This also removes the minor readsAfterLastMessage++ ordering issue mentioned in the review above.

Verified locally on JDK 21:

  • With the patch, all of these pass: FlowControlHandlerTest (24/24), HttpServerCodecFlowControlTest, HttpContentDecompressorTest, HttpServerCodecTest and HttpObjectAggregatorTest.
  • With FlowControlHandler reverted to 4.1, the five new or changed tests fail, and the relay stalls at exactly 34,750 of 1,048,576 bytes, as in FlowControlHandler: relay stalls from 4.1.136.Final when auto-read is disabled per the documented pattern #17628.

For the maintainers: outstanding reads now survive empty upstream cycles, so N read() calls yield N messages. That matches the class javadoc and the 4.1.135 behaviour, where shouldConsume was also not cleared on channelReadComplete. The difference is that 4.1.135 capped this at a single pending read, because it used a boolean flag rather than a counter.

Apply with git apply on top of f99f81140d:

Patch
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerCodecFlowControlTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerCodecFlowControlTest.java
index 6859dcf407..0e872fc431 100644
--- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerCodecFlowControlTest.java
+++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerCodecFlowControlTest.java
@@ -20,6 +20,7 @@ import io.netty.bootstrap.ServerBootstrap;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;
 import io.netty.channel.ChannelInitializer;
@@ -30,13 +31,13 @@ import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.nio.NioServerSocketChannel;
 import io.netty.channel.socket.nio.NioSocketChannel;
 import io.netty.handler.flow.FlowControlHandler;
+import io.netty.util.CharsetUtil;
 import io.netty.util.ReferenceCountUtil;
 import org.junit.jupiter.api.Test;
 
 import java.io.OutputStream;
 import java.net.InetSocketAddress;
 import java.net.Socket;
-import java.nio.charset.StandardCharsets;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
@@ -82,7 +83,7 @@ class HttpServerCodecFlowControlTest {
                                 private Channel outbound;
 
                                 @Override
-                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
+                                public void channelRead(final ChannelHandlerContext ctx, Object msg) {
                                     if (msg instanceof HttpRequest) {
                                         ctx.channel().config().setAutoRead(false);
                                         Bootstrap bootstrap = new Bootstrap().group(ctx.channel().eventLoop())
@@ -94,9 +95,12 @@ class HttpServerCodecFlowControlTest {
                                                 });
                                         ChannelFuture connect = bootstrap.connect("127.0.0.1", targetPort);
                                         outbound = connect.channel();
-                                        connect.addListener(future -> {
-                                            if (future.isSuccess()) {
-                                                ctx.channel().read();
+                                        connect.addListener(new ChannelFutureListener() {
+                                            @Override
+                                            public void operationComplete(ChannelFuture future) {
+                                                if (future.isSuccess()) {
+                                                    ctx.channel().read();
+                                                }
                                             }
                                         });
                                         ReferenceCountUtil.release(msg);
@@ -104,11 +108,15 @@ class HttpServerCodecFlowControlTest {
                                         ByteBuf body = ((HttpContent) msg).content().retain();
                                         ReferenceCountUtil.release(msg);
                                         if (body.isReadable()) {
-                                            outbound.writeAndFlush(body).addListener(future -> {
-                                                if (future.isSuccess()) {
-                                                    ctx.channel().read();
-                                                }
-                                            });
+                                            outbound.writeAndFlush(body).addListener(
+                                                    new ChannelFutureListener() {
+                                                        @Override
+                                                        public void operationComplete(ChannelFuture future) {
+                                                            if (future.isSuccess()) {
+                                                                ctx.channel().read();
+                                                            }
+                                                        }
+                                                    });
                                         } else {
                                             body.release();
                                             ctx.channel().read();
@@ -122,19 +130,32 @@ class HttpServerCodecFlowControlTest {
                     }).bind("127.0.0.1", 0).sync().channel();
             final int proxyPort = ((InetSocketAddress) proxy.localAddress()).getPort();
 
-            Thread client = new Thread(() -> {
-                try (Socket socket = new Socket("127.0.0.1", proxyPort)) {
-                    OutputStream out = socket.getOutputStream();
-                    out.write(("PUT /upload HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: " + bodySize
-                            + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
-                    byte[] chunk = new byte[16 * 1024];
-                    for (int written = 0; written < bodySize; written += chunk.length) {
-                        out.write(chunk);
-                        out.flush();
+            Thread client = new Thread(new Runnable() {
+                @Override
+                public void run() {
+                    Socket socket = null;
+                    try {
+                        socket = new Socket("127.0.0.1", proxyPort);
+                        OutputStream out = socket.getOutputStream();
+                        out.write(("PUT /upload HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: " + bodySize
+                                + "\r\n\r\n").getBytes(CharsetUtil.US_ASCII));
+                        byte[] chunk = new byte[16 * 1024];
+                        for (int written = 0; written < bodySize; written += chunk.length) {
+                            out.write(chunk);
+                            out.flush();
+                        }
+                        targetReceivedBody.await(10, TimeUnit.SECONDS);
+                    } catch (Exception ignored) {
+                        // A blocked client write is part of the relay-stall failure mode.
+                    } finally {
+                        if (socket != null) {
+                            try {
+                                socket.close();
+                            } catch (Exception ignored) {
+                                // ignore
+                            }
+                        }
                     }
-                    targetReceivedBody.await(10, TimeUnit.SECONDS);
-                } catch (Exception ignored) {
-                    // A blocked client write is part of the relay-stall failure mode.
                 }
             }, "flow-control-relay-client");
             client.setDaemon(true);
diff --git a/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java b/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java
index 3ca36be7ff..fff4a0b243 100644
--- a/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java
+++ b/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java
@@ -76,15 +76,16 @@ public class FlowControlHandler extends ChannelDuplexHandler {
 
     /**
      * Number of unsatisfied downstream {@code read()} calls. A downstream {@code read()} is considered unsatisfied
-     * if auto-read is off and if it has not yet been paired with a {@code fireChannelRead} or
-     * a cumulative {@code fireChannelReadComplete}.
+     * if auto-read is off and if it has not yet been paired with a {@code fireChannelRead}.
      * <p>
-     * A {@code read()} can be satisfied in three ways, whichever comes first:
+     * A {@code read()} can be satisfied in two ways, whichever comes first:
      * <ul>
      *     <li>inside the {@code read()} call itself, by {@code dequeue()}ing a message</li>
      *     <li>in a {@code channelRead()}</li>
-     *     <li>in a {@code channelReadComplete()}</li>
      * </ul>
+     * An upstream {@code channelReadComplete()} does not satisfy outstanding reads, as the upstream read cycle may
+     * not have produced any message for this handler.
+     * <p>
      * A {@code read()} can be satisfied with auto-read on.
      * <p>
      * When one or more {@code read()} calls are unsatisfied, a downstream {@code channelReadComplete} is fired
@@ -96,16 +97,6 @@ public class FlowControlHandler extends ChannelDuplexHandler {
      */
     private int unsatisfiedReads;
 
-    /**
-     * {@code true} after a message was received and before its upstream read cycle completes.
-     */
-    private boolean readCycleHasMessage;
-
-    /**
-     * Number of downstream reads requested after the most recently received message.
-     */
-    private int readsAfterLastMessage;
-
     /**
      * {@code true} while a {@link #dequeue(ChannelHandlerContext)} loop is on the stack.
      */
@@ -175,9 +166,6 @@ public class FlowControlHandler extends ChannelDuplexHandler {
     public void read(ChannelHandlerContext ctx) throws Exception {
         if (!config.isAutoRead()) {
             unsatisfiedReads++;
-            if (readCycleHasMessage) {
-                readsAfterLastMessage++;
-            }
         }
 
         boolean didSatisfyARead = dequeue(ctx);
@@ -200,8 +188,6 @@ public class FlowControlHandler extends ChannelDuplexHandler {
 
     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-        readCycleHasMessage = true;
-        readsAfterLastMessage = 0;
         if (queue == null) {
             queue = RecyclableArrayDeque.newInstance();
         }
@@ -217,13 +203,12 @@ public class FlowControlHandler extends ChannelDuplexHandler {
 
     @Override
     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
-        // Upstream closed the read cycle. Preserve outstanding reads across empty cycles because a decoder may
-        // issue another upstream read after receiving only a partial frame. Spurious upstream completions with
-        // no pending read are dropped.
-        boolean hadUnsatisfiedReads = unsatisfiedReads > 0;
-        readsAfterLastMessage = 0;
-        readCycleHasMessage = false;
-        if (config.isAutoRead() || hadUnsatisfiedReads) {
+        // Upstream closed the read cycle. Outstanding reads are NOT reset here: the upstream read cycle may have
+        // produced no message for us (e.g. a decoder in front of us received only a partial frame), or the
+        // downstream handler may have requested another read while processing the last message of this cycle.
+        // In both cases the transport keeps reading and the next message must still be delivered.
+        // Spurious upstream completions with no pending read are dropped.
+        if (config.isAutoRead() || unsatisfiedReads > 0) {
             ctx.fireChannelReadComplete();
         }
     }

Prepared with Claude Code.

All reactions

Sorry, something went wrong.

Uh oh!

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

@hachen-r7 hachen-r7 mentioned this pull request Nov 18, 2026
FlowControlHandler: don't drop outstanding reads on channelReadComplete #18472
Open
@hachen-r7

hachen-r7 commented Nov 18, 2026

Copy link
Copy Markdown

Since there's been no activity here, I've opened #18472. It is this PR squashed onto the current 4.1, plus the follow-up patch above, which fixes the Java 6 compile error and removes the unused fields. Both commit authors from this PR are credited as co-authors, and the review above is credited in the description. @Asthenia0412, if you'd rather carry this forward here, let me know and I'll close mine.

All reactions

Sorry, something went wrong.

Uh oh!

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

1 more reviewer
@allthingssecurity allthingssecurity allthingssecurity left review comments
Reviewers whose approvals may not affect merge requirements

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.

3 participants

@Asthenia0412 @hachen-r7 @allthingssecurity
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.