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 must comply with its fundamental goal (ensured message for each read request) - behaviour broken in 4.2.15.Final (#17050) by ursaj · Pull Request #17046 · netty/netty

Conversation

@ursaj

@ursaj ursaj commented Jul 3, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

Fixes #17050

Motivation:

Recent changes #16837 (link) and followup #16949 led to essential breaches of class main contract: ensured message for each read request.

Modification:

Trigger read-complete event only and only when all FlowControllerHandler-managed requests are properly propagated to the downstream.

Sorry, something went wrong.

Uh oh!

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

danielflower reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
ursaj added 2 commits July 3, 2026 12:37
@ursaj
Revert FlowControlHandler readComplete behaviour to the state before …
4d8d14c
…4.2.15.Final. Making new behavior configurable via constructor argument.
@ursaj
Revert FlowControlHandler readComplete behaviour to the state before …
7c28996
…4.2.15.Final. Making new behavior configurable via constructor argument. (netty#17046)
ursaj
ursaj commented Jul 3, 2026
View reviewed changes
Comment thread handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java

@Override
public void read(ChannelHandlerContext ctx) throws Exception {
if (!config.isAutoRead()) {

@ursaj ursaj Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

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.

in some case we activate auto-read for upstream handlers to work properly during initial handshakes (TLS, WebSocket, FIX). on the first successful read we disable auto-read and rely on flow control handler to count produced messages. autoRead == true should have ZERO effect on this counter, only read() invocations and actually produced messages matter.

Sorry, something went wrong.

Uh oh!

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

All reactions
@ursaj ursaj mentioned this pull request Jul 3, 2026
FlowControlHandler: respect auto-read when toggled while dequeueing #16949
Merged
@lhotari

lhotari commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Adopting new behaviour across all our existing application would require ~2-4 month of work...

A simple workaround in the meantime is to copy the previous implementation into your code base and use that instead of the one provided by Netty.

All reactions

Sorry, something went wrong.

Uh oh!

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

@lhotari

lhotari commented Jul 3, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

on the first successful read we disable auto-read and rely on flow control handler to count produced messages. autoRead == true should have ZERO effect on this counter, only read() invocations and actually produced messages matter.

It would be helpful if you could share a more detailed explanation of the use case. Am I correct in assuming that you'd like to track how many messages each ctx.read() call results in? Why is that necessary for your use case?

There's no denying that #16837 & #16949 changed the previous behavior.

However, looking at the contract of ChannelInboundHandler.channelReadComplete:

Invoked when the last message read by the current read operation has been consumed by channelRead(ChannelHandlerContext, Object). If ChannelOption.AUTO_READ is off, no further attempt to read an inbound data from the current Channel will be made until ChannelHandlerContext.read() is called

The contract doesn't define what happens when multiple reads are "in flight", nor does it state that each read() call is paired with exactly one channelReadComplete. Is that the assumption your code relies on?

Trigger readComplete event only and only when all FlowControllerHandler-managed requests are properly propagated to the downstream. New behaviour could be configured via constructor parameter, default is set to behaviour of 4.2.12.Final release.

The previous behavior has effectively become part of the API contract per Hyrum's law, so providing an opt-in way to restore it could make sense.

In the meantime, a simple workaround would be to copy the previous FlowControlHandler implementation into your own code base and use that instead of the one provided by Netty. That would also give you the option to customize or optimize the handler specifically for your use case.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj

ursaj commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

It would be helpful if you could share a more detailed explanation of the use case. Am I correct in assuming that you'd like to track how many messages each ctx.read() call results in? Why is that necessary for your use case?

For example the following:

Mutual TLS -> HTTP Codec -> HTTP Proprietary Filters -> WebSocket Codec -> WS Proprietary Filters -> Proprietary Codec -> FlowControlHandler -> app-level control on consumed messages (number of ctx.read() calls)

Once pipeline is built we call ctx.read() on app level and set autoRead=true till the first app-level message received. Then switching to autoRead=false.

The contract doesn't define what happens when multiple reads are "in flight", nor does it state that each read() call is paired with exactly one channelReadComplete. Is that the assumption your code relies on?

ctx docs don't state anything. however FlowControlHandler is exactly the part we rely on to control requested/received messages flow. and the last decade I was under impression this handler was designed exactly for this purpose.

The previous behavior has effectively become part of the API contract per Hyrum's law, so providing an opt-in way to restore it could make sense.

In the meantime, a simple workaround would be to copy the previous FlowControlHandler implementation into your own code base and use that instead of the one provided by Netty. That would also give you the option to customize or optimize the handler specifically for your use case.

for the part I have direct access to - yes, not a problem. copy-paste old implementation is exactly how I've identified the problem in the first place. however for the huge distributed ecosystem, that is relying on our core libraries – it's a huge effort. mostly because of rework/test/release slow enterprise life-cycles. for the third-party dependencies (where I don't have access to sources) it's also a problem – we can't just patch-update to the newer versions.

for a time being we just keep using 4.2.12.Final

All reactions

Sorry, something went wrong.

Uh oh!

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

@lhotari

lhotari commented Jul 3, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

ctx docs don't state anything. however FlowControlHandler is exactly the part we rely on to control requested/received messages flow. and the last decade I was under impression this handler was designed exactly for this purpose.

Yes, it's for getting one message at a time. When ctx.read() is called, the contract is that you get one call to channelRead(ChannelHandlerContext, Object).
"The FlowControlHandler ensures that only one message per read() is sent downstream."
The FlowControlHandler contract doesn't mention channelReadComplete, however I think that the contact should be what ChannelInboundHandler.channelReadComplete defines, as mentioned in my previous message. The contract seems to be that when channelReadComplete is received, read() needs to be called to read more messages. Assuming that a read() is always paired with channelReadComplete isn't part of the contract at all.

quoting #16837:

2. Assume FlowControlHandler has just emptied its queue and correctly fired channelRead followed by channelReadComplete. If FlowControlHandler then receives one or more channelReadComplete events from upstream, it currently relays all of them downstream, resulting in duplicate channelReadComplete events. This is unexpected because, from the perspective of downstream handlers, there are no further read operations in progress.

From the API contract perspective of channelReadComplete, #16837 makes total sense.

for the part I have direct access to - yes, not a problem. copy-paste old implementation is exactly how I've identified the problem in the first place. however for the huge distributed ecosystem, that is relying on our core libraries – it's a huge effort. mostly because of rework/test/release slow enterprise life-cycles. for the third-party dependencies (where I don't have access to sources) it's also a problem – we can't just patch-update to the newer versions.

I feel your pain. It's a very hard problem to solve when there are breaking changes from the library consumer's perspective. From the Netty library perspective #16837 could be considered a bug fix, but for some users it is a breaking change (Hyrum's law).

All reactions

Sorry, something went wrong.

Uh oh!

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

@normanmaurer

normanmaurer commented Jul 3, 2026

Copy link
Copy Markdown
Member

I think the only "guarantee" we really give is that if there is no more data that will be read without a read call we will call channelReadComplete(...) which basically will give the user the chance to trigger another read. If one read triggers multiple channelReadComplete or not is not really defined at all.

lhotari 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.

@ursaj

ursaj commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Correct me if I'm wrong, but the first line in FlowControlHandler documentation states the following:

The {@link FlowControlHandler} ensures that only one message per {@code read()} is sent downstream.

Two key points: (a) ensures and (b) one message per read.

But now you are saying I can receive readComplete instead of guarantied message. Sounds not good.

If one read triggers multiple channelReadComplete or not is not really defined at all.

agree 100%. for all handlers except for FlowControlHandler

Imagine I've requested a single message with read() but received readComplete instead - how should I request the same first message? second read() may produce 2 messages according to the the very first line in docs. But I need only the first one...

We cannot trigger readComplete before producing requested and ensured message.

I do understand Hyrum's law. This is why I've added propagateReadComplete constructor argument to support BOTH flows:

  • strict: N x read =>N messages + readComplete and
  • relaxed: N x read => 0 .. N messages + readComplete

All happy - old/new behaviour could be configured on pipeline build.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj

ursaj commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

From the Netty library perspective #16837 could be considered a bug fix, but for some users it is a breaking change (Hyrum's law).

This PR does NOT revert bugfix, duplicate readComplete events are still suppressed.

All reactions

Sorry, something went wrong.

Uh oh!

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

@lhotari

lhotari commented Jul 3, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

But now you are saying I can receive readComplete instead of guarantied message. Sounds not good.

That seems to be the case even before #16837 for FlowControlHandler since it's goal was to fix it.

Imagine I've requested a single message with read() but received readComplete instead - how should I request the same first message? second read() may produce 2 messages according to the the very first line in docs. But I need only the first one...

We cannot trigger readComplete before producing requested and ensured message.

Good point. You (@ursaj) already pointed that out in https://github.com/netty/netty/pull/16837/changes#r3512883877.

netty/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java

Lines 202 to 210 in 8081e23

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// Upstream closed the read cycle. Collapse every outstanding read() into a single downstream
// channelReadComplete; spurious upstream completions with no pending read are dropped.
if (config.isAutoRead() || unsatisfiedReads > 0) {
unsatisfiedReads = 0;
ctx.fireChannelReadComplete();
}
}

I agree that the above seems wrong as you also pointed out in #16949 (comment).
To reach the goal that FlowControlHandler produces exactly the requested amount of messages, it would be necessary to trigger a new read without resetting unsatisfiedReads and firing readComplete to the downstream handler.

@ursaj I'd suggest creating an issue report with clear problem framing since it could be easier to find the information in the issue report. You have already shared in multiple locations and putting that into an issue report improves clarity for everyone.

btw. I just found your PR #9691 from 2019. Also related to the readComplete events.

All reactions

Sorry, something went wrong.

Uh oh!

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

ursaj added 2 commits July 3, 2026 18:47
@ursaj
Ensure no read-complete duplicate events triggered when `autoRead=fal…
f7b9008
…se` and `propagateReadComplete=true`. (netty#17046)
@ursaj
Ensure no read-complete duplicate events triggered when `autoRead=fal…
f2ea5d3
…se` and `propagateReadComplete=true`. (netty#17046)
@lhotari

lhotari commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

@ursaj I think that most of the changes in this PR are great, but the PR title and description could be improved. Adding the issue report would also make it easier to understand the problem and the motivation.

Revert FlowControlHandler readComplete DEFAULT behaviour to the state of 4.2.12.Final. Making new behaviour configurable via constructor argument.

The new behavior currently in 4.2 branch seems to be wrong (and you have already fixed some of the issues), so "making the new behavior configurable" isn't a useful goal. Referring to "default behavior" is also vague without explaining it. It's also possible that the problem that #16837 attempts to resolve is resolved with a single implementation. In that case, there wouldn't need to be a new option at all.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj ursaj changed the title Revert FlowControlHandler readComplete events DEFAULT behaviour to the state of 4.2.12.Final Revert FlowControlHandler readComplete events DEFAULT behaviour to the state of 4.2.12.Final (#17050) Jul 3, 2026
@ursaj ursaj changed the title Revert FlowControlHandler readComplete events DEFAULT behaviour to the state of 4.2.12.Final (#17050) FlowControlHandler must comply with its fundamental goal (ensured message for each read request) - behaviour broken in 4.2.15.Final (#17050) Jul 3, 2026
@ursaj

ursaj commented Jul 3, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor Author

@ursaj I think that most of the changes in this PR are great, but the PR title and description could be improved. Adding the issue report would also make it easier to understand the problem and the motivation.

sure. renamed, updated description, added #17050, added more tests.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj
Ensure no read-complete duplicate events triggered when `autoRead=tru…
82b1644
…e` (netty#17046, netty#17050)
@lhotari

lhotari commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

sure. renamed, updated description, added #17050, added more tests.

really clear now. good work

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj
Ensure no read-complete duplicate events triggered when `autoRead=tru…
57c5302
…e` (netty#17046, netty#17050)
lhotari
lhotari reviewed Jul 5, 2026
View reviewed changes

@lhotari lhotari 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.

good work. it could improve clarity to reference a specific test case that reproduces the regression introduced by #16837/#16949 changes.

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 Outdated
public class FlowControlHandler extends ChannelDuplexHandler {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(FlowControlHandler.class);

public static final boolean DEFAUT_RELEASE_MESSAGES = true;

@lhotari lhotari Jul 5, 2026

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.

nit: could this be private

Sorry, something went wrong.

Uh oh!

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

All reactions

@ursaj ursaj Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

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.

it will be impossible to reference it from outside, e.g.:

var releaseMessages = Optional.ofNullable(externallyConfiguredValue).orElse(???);
var handler = new FlowControlHandler(releaseMessages);

if you insist, I can make it private or just inline

Sorry, something went wrong.

Uh oh!

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

All reactions

@ursaj ursaj Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

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.

removed

Sorry, something went wrong.

Uh oh!

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

All reactions
danielflower added a commit to 3redronin/mu-server that referenced this pull request Jul 10, 2026
@danielflower
Disable netty 4.2 tests temporarily - due to netty/netty#17046 not 4.…
21af806
…2 build is working for all tests (older 4.2 version did not enforce max concurrent streams)

Match http2 config to mu3 branch
@danielflower danielflower mentioned this pull request Jul 27, 2026
mu-server (v2.3.2) does not work with latest Netty version 4.1.136.Final and 4.2.16.Final 3redronin/mu-server#143
Closed
@DaveCTurner DaveCTurner mentioned this pull request Aug 12, 2026
Bundled netty 4.1.135.Final has two unfixed CVEs; 4.1.136+ breaks the HTTP layer elastic/elasticsearch#156362
Closed
ursaj added 2 commits August 25, 2026 23:03
@ursaj
Removed/reverted public field DEFAUT_RELEASE_MESSAGES
24a0336
@ursaj
Remove/cleanup duplicated test
da960b2
@ursaj

ursaj commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

@lhotari what else could/should I improve to get this PR merged?

All reactions

Sorry, something went wrong.

Uh oh!

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

@lhotari

lhotari commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

@ursaj I spent some time verifying this against the branch and I want to lead with the
conclusion: the bug you report in #17050 is real, and this PR fixes it. I was able to
reproduce the breach on the current 4.2 branch and confirm the PR resolves it. Thanks for
sticking with this.

To answer your question directly:

@lhotari what else could/should I improve to get this PR merged?

One clarification first, so I don't overpromise: I'm not a Netty project member, so I can't merge
this and I can't tell you what it will take to get it merged — that call belongs to the
maintainers. What I can do is review it properly and approve it, and help make the case that
it's ready. Here's what I have.

Five things, roughly in priority order. The first three are what I'd want resolved before I could
approve; the last two are what stops them coming back.

  1. Don't swallow the auto-read resume. read() must still forward ctx.read() upstream when
    auto-read is on, even after a successful dequeue. Today the connection stalls permanently in the
    class javadoc's own use case. (Details and reproducer in "Blocking issue 1".)
  2. Don't gate the auto-read completion on unsatisfiedReads == 0. A message that was actually
    delivered should complete the auto-read cycle; today it can be delivered with no
    channelReadComplete at all, so a downstream that flushes on completion never flushes.
    ("Blocking issue 2".)
  3. Restore testSwallowedReadComplete to its original body and make it pass. The PR currently
    removes the three ctx.read() calls that make that test meaningful. It is the acceptance test
    for not regressing FlowControlHandler: Suppress duplicate channelReadComplete after draining queue (#15053) #16837, and with those calls restored it fails: READER_IDLE never fires.
    This one is really a design question rather than a straightforward fix, and it's the item most
    worth a maintainer's opinion — see that section.
  4. Add tests that would have caught 1 and 2. They need an upstream read() counter rather than
    EmbeddedChannel alone — EmbeddedChannel.doBeginRead() is a no-op, so a swallowed ctx.read()
    is invisible, which is why the current suite is green. Both reproducers below are written that
    way and can be dropped in as-is.
  5. Sync the docs with the new state machine. The unsatisfiedReads javadoc and two test
    comments now contradict the code directly beneath them. (Minor, but they will mislead the next
    person — list in "Smaller items".)

Nothing here asks you to give up what the PR achieves. Everything below is the evidence.

The fix works

read() with auto-read off, an upstream cycle that ends with no data, then data arrives:

after 4.2 branch this PR
the empty upstream cycle [#rc], 1 upstream read [], 2 upstream reads
data then arrives [#rc] — message queued, never delivered [1, #rc] — message delivered, then one completion

The current branch doesn't just fire an early channelReadComplete — it zeroes
unsatisfiedReads, so the outstanding read is consumed and lost. The message that arrives
afterwards stays in the queue and the application has to issue a compensating read(). That is
exactly the escalation you described, and it is a clear breach of the class's first javadoc line.
I was wrong earlier to frame this as mainly a Hyrum's-law problem; it is a genuine defect.

What this PR correctly preserves

I ran both predecessor reproducers against your handler:

  • FlowControlHandler no longer honors setAutoRead(false) made by a downstream handler while dequeuing (regression in 4.2.15) #16945 / FlowControlHandler: respect auto-read when toggled while dequeueing #16949 (auto-read disabled mid-drain) — passes. dequeue() still re-checks
    config.isAutoRead() on every iteration, so Pulsar-style rate limiting is not re-broken.
  • FlowControlHandler and HttpContentDecompressor do not play nicely together #15053 / FlowControlHandler: Suppress duplicate channelReadComplete after draining queue (#15053) #16837 (duplicate completion confusing HttpContentDecoder) — HttpContentDecompressorTest
    passes 8/8, including the reproducer FlowControlHandler: Suppress duplicate channelReadComplete after draining queue (#15053) #16837 added.

Good — those were my main worries going in.

Blocking issue 1: re-enabling auto-read no longer re-arms the transport

FlowControlHandler.java:192-202. The two branches are mutually exclusive, so when auto-read is on
and the queue was non-empty, ctx.read() is never forwarded:

if (dequeued && unsatisfiedReads == 0) {
    if (config.isAutoRead()) {
        autoReadComplete = true;        // <-- no ctx.read()
    } else {
        ctx.fireChannelReadComplete();
    }
} else if (!reading) {
    reading = true;
    ctx.read();
}

The previous code forwarded unconditionally under auto-read
(if (!didSatisfyARead || isAutoRead) { ctx.read(); }), and that matters:
DefaultChannelConfig.setAutoRead(true) implements resume as nothing but channel.read(), while
turning auto-read off already removed the read interest
(NioSocketChannel.NioSocketChannelConfig.autoReadCleared() -> clearReadPending(), and
AbstractNioByteChannel's if (!readPending && !config.isAutoRead()) removeReadOp()).
Swallowing that read() leaves the socket with no read interest and nothing to re-arm it. No
upstream channelReadComplete follows either, so autoReadComplete stays true and the
downstream never gets its completion for the drained batch.

This is the scenario in the class javadoc — pause on HttpRequest, resume afterwards:

@Test
public void autoReadResumeMustRearmTransport() throws Exception {
    final AtomicInteger upstreamReads = new AtomicInteger();
    final List<String> events = new ArrayList<String>();
    EmbeddedChannel ch = new EmbeddedChannel(false, false,
            new ChannelDuplexHandler() {
                @Override
                public void read(ChannelHandlerContext ctx) throws Exception {
                    upstreamReads.incrementAndGet();
                    super.read(ctx);
                }
            },
            new FlowControlHandler(),
            new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    events.add((String) msg);
                    if ("REQ".equals(msg)) {
                        ctx.channel().config().setAutoRead(false);   // javadoc example
                    }
                }
                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) {
                    events.add("#rc");
                }
            });

    ch.register();                       // auto-read on
    ch.writeInbound("REQ", "LAST");      // decoder emits two, handler pauses on the first
    int before = upstreamReads.get();

    ch.config().setAutoRead(true);       // application resumes and leaves auto-read on

    // 4.2 branch: 1 -> 2.   this PR: 1 -> 1, so the socket is never read again.
    assertTrue(upstreamReads.get() > before,
            "setAutoRead(true) must reach the transport");
}

Worth noting this spares the #16945 pattern, which re-disables auto-read on every message and so
recovers on the next resume. It bites the javadoc pattern, which turns auto-read back on and
leaves it on.

Blocking issue 2: a delivered message can arrive with no channelReadComplete

FlowControlHandler.java:214-220 only sets autoReadComplete when unsatisfiedReads == 0, and the
auto-read branch of channelReadComplete (:226-232) — unlike the auto-read-off branch — has no
ctx.read() re-issue to work the counter down. So reads left over from before auto-read was
enabled suppress the completion indefinitely:

@Test
public void deliveredMessageMustBeFollowedByReadComplete() throws Exception {
    final List<String> events = new ArrayList<String>();
    EmbeddedChannel ch = new EmbeddedChannel(false, false,
            new FlowControlHandler(),
            new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) { events.add((String) msg); }
                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) { events.add("#rc"); }
            });

    ch.config().setAutoRead(false);
    ch.register();
    ch.read();
    ch.read();                          // two explicit reads while auto-read is off
    ch.config().setAutoRead(true);      // then auto-read is enabled
    ch.writeInbound("1");               // one message arrives and IS delivered

    // 4.2 branch: [1, #rc].   this PR: [1].
    assertEquals(Arrays.asList("1", "#rc"), events);
}

The practical effect is that a downstream handler using the standard write-on-channelRead /
flush-on-channelReadComplete idiom receives the request and never flushes the response. For a
request/response protocol where the peer will not send again until answered, that deadlocks.

Note this is also arguably at odds with #17050's own requirement 3 ("read-complete MUST be
triggered only and only after POSITIVE (1+) number of messages is actually delivered") — a message
was delivered here.

The regression test from #16837 was weakened rather than kept passing

testSwallowedReadComplete is the test #16837 added for swallowed completions. This PR removes the
three ctx.read() calls from its downstream handler (channelActive, channelRead,
channelReadComplete) — which is precisely what removes the outstanding read that the test existed
to exercise. Restore the original test body against this handler and it fails: no READER_IDLE.

The mechanism: with auto-read off and a read outstanding, channelReadComplete re-issues
ctx.read() and never propagates the completion (:233-236). A downstream IdleStateHandler
therefore never clears its reading flag, and ReaderIdleTimeoutTask computes
nextDelay = readerIdleTimeNanos; if (!reading) { nextDelay -= elapsed; } — so nextDelay never
reaches zero and READER_IDLE never fires again for the life of the connection.
ReadTimeoutHandler extends IdleStateHandler and inherits this.

That also collides with what Norman stated on this PR: "if there is no more data that will be read
without a read call we will call channelReadComplete(...)". Here upstream says exactly that and
it is dropped. I think downstream needs to learn the read cycle ended even when it has a read
pending — those are independent obligations.

Related: reading gates every upstream read (:199) but is cleared only in channelReadComplete
(:225) — not in channelInactive, handlerRemoved, or on re-registration. With
ALLOW_HALF_CLOSURE, once inputClosedSeenErrorOnRead is set, AbstractNioByteChannel.read()
returns at shouldBreakReadReady without ever firing another completion, so the latch wedges on a
channel that is still active and writable, and every later read() is silently dropped.

Smaller items

  • FlowControlHandler.java:76-95 — the unsatisfiedReads javadoc still describes the old machine
    ("A read() can be satisfied ... in a channelReadComplete()"; a downstream completion fires when
    "an upstream channelReadComplete arrives"). Neither holds now.
  • FlowControlHandlerTest.java:806 — "FlowControlHandler must forward that channelReadComplete to
    satisfy the outstanding read" sits directly above assertEquals(0, readCompletes.get()) at :810.
  • FlowControlHandlerTest.java:1102 — "then reads further upstream twice: once for the transparent
    resume..." sits above assertEquals(0, upstream.reads.get()) at :1106.
  • EmbeddedChannel.doBeginRead() is a no-op, so a swallowed ctx.read() is invisible in these
    tests; several rewritten cases then hand-inject flushInbound() to unstick a channel a real
    transport would never have restarted. Both issues above are consequently untested.

Suggested direction

Both blocking issues come from the same trade: read() and channelReadComplete treat "satisfy
downstream" and "keep the upstream read pumped" as mutually exclusive, when they are independent
obligations. Two narrow changes should cover it:

  1. In read(), still forward ctx.read() upstream when auto-read is on, even after a successful
    dequeue.
  2. Do not gate autoReadComplete on unsatisfiedReads == 0; a delivered message should complete
    the auto-read cycle.

Neither weakens what the PR achieves for #17050. Please also restore testSwallowedReadComplete to
its original body and keep it green — that is the acceptance test for not regressing #16837.

One note on #17050 itself

Requirement 2 as written ("any sequence of N x read() MUST lead to exactly N x channelRead() + 1 x channelReadComplete()") isn't met by this PR or by the current branch, and I don't think it can
be: a read() satisfiable from the queue completes its own cycle before the next read() is
issued, so two sequential reads legitimately produce two completions. It would help to define what
counts as a "sequence" — I read the real requirement as the narrower and clearly correct one you
demonstrate above: a read() must never be answered with a completion instead of a message.


Recap

What I'd want resolved before approving: (1) forward ctx.read() upstream under auto-read after a
dequeue; (2) don't gate autoReadComplete on unsatisfiedReads == 0; (3) settle the
testSwallowedReadComplete question and get that test green again. Then: (4) tests for 1 and 2
using an upstream read counter, (5) refresh the stale javadoc and test comments.

The core fix is right and I'd like to see it land. Push those and I'll re-review and approve —
but the merge decision, and especially the design call in item 3, needs a maintainer.

All reactions

Sorry, something went wrong.

Uh oh!

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

@lhotari

lhotari commented Aug 27, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor
  • Don't swallow the auto-read resume. read() must still forward ctx.read() upstream when
    auto-read is on, even after a successful dequeue. Today the connection stalls permanently in the
    class javadoc's own use case. (Details and reproducer in "Blocking issue 1".)
  • Don't gate the auto-read completion on unsatisfiedReads == 0. A message that was actually
    delivered should complete the auto-read cycle; today it can be delivered with no
    channelReadComplete at all, so a downstream that flushes on completion never flushes.
    ("Blocking issue 2".)

regarding auto read behavior, there's a useful comment at #16837 (review).

It's not really clear to me how it should work, but my instinct is that with autoRead=true the FlowControlHandler should behave as if it isn't there.

In addition, the previous fix for #16945 should continue to apply so that when auto read gets disabled, it would switch to the mode where ctx.read() would need to be explicit or switching auto read on would need to be used for resuming reading (so that FlowControlHandler behaves as it isn't there).

All reactions

Sorry, something went wrong.

Uh oh!

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

@allthingssecurity allthingssecurity mentioned this pull request Sep 29, 2026
FlowControlHandler: preserve reads requested during a read cycle #17647
Open
@adwsingh

adwsingh commented Oct 24, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

This change in behavior also broke multiple services in production at Amazon/AWS.

cc: @normanmaurer

All reactions

Sorry, something went wrong.

Uh oh!

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

ursaj added 2 commits October 24, 2026 23:51
@ursaj
Fix review notes:
0a9ea46
* Blocking issue 1: re-enabling auto-read no longer re-arms the transport
* Blocking issue 2: a delivered message can arrive with no channelReadComplete
@ursaj
Updated tests for netty#17046 (comment)
0b8e07a
@ursaj

ursaj commented Oct 24, 2026

Copy link
Copy Markdown
Contributor Author

thanks @lhotari. updated flow controller + added your tests to fix:

  • Blocking issue 1: re-enabling auto-read no longer re-arms the transport
  • Blocking issue 2: a delivered message can arrive with no channelReadComplete
All reactions

Sorry, something went wrong.

Uh oh!

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

ursaj added 3 commits October 25, 2026 00:05
@ursaj
Updated checkstyle
870b6d6
@ursaj
Prevent duplicate read-requests sent to upstream - do NOT decode next…
9cf1987
… message before previous processed.
@ursaj
Update tests
a369331
@ursaj

ursaj commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

3. Restore testSwallowedReadComplete to its original body and make it pass. The PR currently
removes the three ctx.read() calls that make that test meaningful. It is the acceptance test
for not regressing #16837, and with those calls restored it fails: READER_IDLE never fires.
This one is really a design question rather than a straightforward fix, and it's the item most
worth a maintainer's opinion — see that section.

I've updated test exactly to cover scenarios of #16837:

Assume autoRead == false and FlowControlHandler has already queued two messages from upstream. If a downstream handler calls read(), FlowControlHandler serves that read with the first queued message. Since the queue is still not empty, FlowControlHandler does not fire channelReadComplete.

Because allowRead == false, no further messages are delivered downstream until the downstream handler calls read() again. A downstream handler that waits for channelReadComplete before issuing the next read() may therefore stall.

Three additional reads would result in x4 reads from FlowControlHandler, while scenario #16837 explicitly specifies one and only one, expecting read-complete event afterwards.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj
Updated docs/comments
f448d0d
@ursaj

ursaj commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

Smaller items

Updated.

EmbeddedChannel.doBeginRead() is a no-op, so a swallowed ctx.read() is invisible in these
tests; several rewritten cases then hand-inject flushInbound() to unstick a channel a real
transport would never have restarted. Both issues above are consequently untested.

embeddedChannel.flushInbound() triggers/emulates pipeline().fireChannelReadComplete()

swallowed ctx.read() is invisible in these tests

I've explicitly added events.add("#r") to check read events in full sequence of events. also in some tests, where this information was ignored / not tested.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj

ursaj commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@normanmaurer could you please take a look and merge this change?

All reactions

Sorry, something went wrong.

Uh oh!

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

@ursaj

ursaj commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@chrisvest hi, could you please take a look and merge this change?

All reactions

Sorry, something went wrong.

Uh oh!

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

@chrisvest
chrisvest self-requested a review November 7, 2026 03:08
chrisvest
chrisvest reviewed Nov 12, 2026
View reviewed changes

@chrisvest chrisvest 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.

Noticed some reentrancy problems. I think they're new, but it's hard to tell.

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
// Auto-read is off, and we have satisfied all reads.
// As such, we can complete the current read cycle. && !dequeueing makes sure we are completing the
// read cycle only once in the top-most read() call.
ctx.fireChannelReadComplete();

@chrisvest chrisvest Nov 11, 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.

We can miss read-completes if auto-read is off.

  1. Suppose we get a read() call. It sets unsatisfiedReads to 1 and asks upstream for data.
  2. Then we get a channelRead() and call dequeue(), which hands the message on and drops unsatisfiedReads to 0.
  3. In dequeue() we fireChannelRead() and in the next handlers channelRead it calls ctx.read(), so we get a read() and raise unsatisfiedReads back to 1. That calls an inner dequeue() which returns false straight away.
  4. The outer loop (outer dequeue()) polls again, finds the queue empty, and breaks. The read-complete it still owes (fireReadComplete == true) is thrown away.
  5. The upstream channelReadComplete then arrives with unsatisfiedReads > 0. The new code only calls ctx.read(); and only passes on read-completes when auto-read is on.

Sorry, something went wrong.

Uh oh!

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

All reactions

@ursaj ursaj Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

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.

this is exactly the problem this PR solves. statement (4) is wrong. when auto-read is off FCH must NOT deliver readComplete until all requested messages delivered. in this example during msg1 delivery downstream requested the next read. sending #rc before msg2 will break FCH contract.

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
ctx.fireChannelReadComplete();
}
unsatisfiedReads = isQueueEmpty() ? 0 : queue.size();
dequeue(ctx);

@chrisvest chrisvest Nov 12, 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.

There's a similar reentrancy problem to what I described below.

If we're in dequeue(), next handler's channelRead() which then removes this handler, the inner dequeue() returns immediately and we don't fire the read-compele, but we also go to destroy() and release all the messages that were queued up so the outer dequeue() don't get to send them.

Sorry, something went wrong.

Uh oh!

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

All reactions

@ursaj ursaj Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

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.

good point. added test, updated handlerRemoved.

Sorry, something went wrong.

Uh oh!

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

All reactions
ursaj added a commit to ursaj/netty that referenced this pull request Nov 13, 2026
@ursaj
FlowControlHandler must comply with its fundamental goal (ensured mes…
c8cbfa1
…sage for each read request) - behaviour broken in 4.2.15.Final (netty#17050) - netty#17046

* Added test for handler removal during read-delivery to downstream.
@ursaj
FlowControlHandler must comply with its fundamental goal (ensured mes…
9777382
…sage for each read request) - behaviour broken in 4.2.15.Final (netty#17050) - netty#17046

* Added test for handler removal during read-delivery to downstream.
@ursaj
ursaj force-pushed the flow-controller-handler branch from c8cbfa1 to 9777382 Compare November 13, 2026 01:14
@testlens-app

testlens-app Bot commented Nov 13, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 9777382
▶️ Tests: 147645 executed
⚪️ Checks: 26/26 completed


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 mentioned this pull request Nov 18, 2026
FlowControlHandler: don't drop outstanding reads on channelReadComplete #18472
Open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@chrisvest chrisvest chrisvest left review comments
+1 more reviewer
@lhotari lhotari lhotari 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.

FlowControlHandler must provide an ensured message for each read request

Uh oh!

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

5 participants

@ursaj @lhotari @normanmaurer @adwsingh @chrisvest
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.