Skip to content

http2: prevent gRPC streaming response truncation on premature local resets - #48857

Closed
bingqifan wants to merge 7 commits into
envoyproxy:mainfrom
bingqifan:fix/issue-48192-response-flush
Closed

bingqifan wants to merge 7 commits into
envoyproxy:mainfrom
bingqifan:fix/issue-48192-response-flush

Conversation

@bingqifan

@bingqifan bingqifan commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Commit Message:

When independent upstream half-close is disabled, normal completion of a response can reset an open downstream HTTP/2 request while response data remains buffered by flow control. This can truncate the response with an INTERNAL_ERROR reset.

This change retains the stream until the codec finishes encoding the response, then performs normal stream cleanup. The behavior is enabled by default and can be disabled through the envoy.reloadable_features.http2_defer_reset_until_response_complete runtime guard.

Additional Description:

If the downstream request remains open when response encoding completes, HCM schedules the normal reset for the next dispatcher iteration. This avoids recursively entering the HTTP/2 adapter's Send operation from its completion callback. If the request has already ended, HCM can complete cleanup without sending a reset.

The codec disables its stream flush timer before notifying HCM of response completion. While response data remains pending, the existing flush timeout limits the wait; a configured timeout of zero disables that timeout.

Explicit aborts, protocol errors, downstream resets, and connection closure retain their cancellation behavior. CONNECT requests, established tunnels, and independent upstream half-close retain their existing behavior.

Risk Level:

Medium. This change affects HTTP/2 stream lifetime and cleanup ordering. The runtime guard provides a rollback to the previous behavior.

Testing:

Focused HCM, HTTP/2 codec, and integration tests passed on Linux.

The tests cover response completion after WINDOW_UPDATE, flush timeout, request END_STREAM ordering, deferred reset cancellation, explicit aborts, connection draining, resource cleanup, and runtime-guard behavior.

The integration tests exercise large flow-controlled responses through Envoy, including DATA and trailers carrying END_STREAM and upstream closure variations.

Formatting and spelling checks passed.

Docs Changes:

This PR does not change user or API documentation.

Release Notes:

The release note describes response preservation, excluded request types, the runtime guard, and the existing flush timeout behavior.

Platform Specific Features:

This change introduces no platform-specific behavior.

Runtime guard:

envoy.reloadable_features.http2_defer_reset_until_response_complete defaults to true. Setting it to false restores the previous behavior.

Fixes #48192

Wait for codec response completion before resetting an open downstream
request. Schedule the reset outside the codec send callback to avoid
reentrant sends, while preserving explicit abort handling.

Disarm the server stream flush timer before notifying response completion.
Add codec, HCM, and integration coverage for draining and cleanup.

Guard the behavior with
envoy.reloadable_features.http2_defer_reset_until_response_complete.

Fixes envoyproxy#48192

Signed-off-by: Bingqi(Jonatahn)Fan <[email protected]>
@repokitteh-read-only

Copy link
Copy Markdown

CC @envoyproxy/runtime-guard-changes: FYI only for changes made to (source/common/runtime/runtime_features.cc).

🐱

Caused by: #48857 was opened by CapricornFBQ.

see: more, trace.

Update the deferred-reset test to expect flush timer cleanup before
the low-level reset once the response END_STREAM has been encoded.

Update local-reply byte-count expectations to account for response
headers being encoded before final access logging. Preserve the
legacy expectations when the response-draining runtime guard is disabled.

Replace the unqualified InvokeWithoutArgs action with a direct lambda
following the upstream removal of its using declaration.

Validation: related HCM, HTTP/2 codec and integration tests passed,
including local-reply tests with the runtime guard enabled and disabled.
Format and spelling checks passed.

Signed-off-by: Bingqi(Jonatahn)Fan <[email protected]>
Clean up open requests while their response decoders are still alive. Keep disconnect waits running across unrelated dispatcher exits without restarting their timeout, and exercise that exit in the delayed-close test.

Signed-off-by: Bingqi(Jonatahn)Fan <[email protected]>
@bingqifan

Copy link
Copy Markdown
Contributor Author

I investigated the CI failures caused by the changed reset timing in this PR.

In the original issue I reproduced, the complete response had been submitted to the codec, but the codec could not send the remaining response data until the client increased its flow-control window. With independent upstream half-close disabled, HCM’s normal local reset could discard that pending response data.

This patch keeps the stream alive until the codec completes encoding the response. If the downstream request is still open, HCM schedules the normal reset for the next dispatcher iteration because the completion callback runs inside the HTTP/2 adapter’s Send() call. Resetting there directly could recursively enter Send(). This separates response completion from the subsequent reset and stream cleanup.

The CI failures exposed two test issues:

  • Some tests returned after receiving the response’s END_STREAM and destroyed their local response decoder while the client request was still active. Later connection cleanup reset the remaining stream and invoked a callback through the destroyed decoder.
  • In TestDelayedConnectionTeardownTimeoutTrigger, a later reset callback exited the client dispatcher during waitForDisconnect(). The decoder’s earlier waiting_for_end_stream_ flag was still set, and the connection-wait helper treated the dispatcher returning as completion even though the connection was still open.

Even with the previous implementation, RST_STREAM could still arrive later at the client because of network delays, even if Envoy sent END_STREAM and RST_STREAM together. These tests did not account for that possibility.

I made minimal changes to the affected test cases. The response tests now call cleanupUpstreamAndDownstream() after their existing assertions, while their decoders are still alive. The connection-wait helper now continues waiting until the connection closes or its original timeout expires. The existing connection-close test also posts a dispatcher exit before waiting, so it exercises an intermediate exit without relying on network timing.

The response assertions, RemoteClose expectation, and delayed-close counter check remain unchanged. The added intermediate-exit scenario failed with the old wait helper even with the runtime guard disabled, and passed with the updated helper. The focused tests passed locally with the runtime guard both enabled and disabled.

The patch already accounts for explicit aborts, which remain immediate, and excludes CONNECT requests and established tunnels.

I would appreciate feedback on the HCM lifecycle change and any additional lifecycle guarantees that this implementation needs to preserve.

@bingqifan bingqifan changed the title http2: preserve responses before normal local resets of open requests http2: prevent gRPC streaming response truncation on premature local resets Oct 31, 2026
@RyanTheOptimist

Copy link
Copy Markdown
Contributor

/assign @mattklein123

@ggreenway

Copy link
Copy Markdown
Member

I'm concerned that this makes significant changes to HCM behavior, and is quite risky. And I think this can be better fixed by pushing more of the code into the h2 codec; the h3 codec already handles this case in that codec. The fix I'm suggesting is hard to describe, so I'm just going to post another PR with that approach, and we can compare tradeoffs between them.

@agrawroh agrawroh left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🚫 Suggested Fixes. The merge with main breaks the build, and the layer for this hold is worth settling with #49126 before more work here.

  • ⚠️ Main removed allow_upstream_half_close_ in #48648, so the new gate merges without a conflict and then fails to build, and the integration fixture's override of the removed guard aborts a debug run.
  • ❓ The HTTP/2 codec already defers a server reset to the end of the same send so END_STREAM can go out, then resets anyway when flow control blocks it.
  • 💡 Request DATA that arrives while a filter has reads disabled never reaches the HCM, so the codec keeps it and its connection window until the hold ends, which can stall other uploads on the connection.
  • 💡 The hold disarms every stream timer, while the codec arms no flush timer on some trailer paths, such as empty trailers behind a blocked body, so those holds have no deadline.
  • 💡 An abort during the hold sends the caller's reason as is, so a module's refused-stream reset becomes REFUSED_STREAM after a processed response, which invites a retry.
  • 💡 The codec's new flush-timer disarm runs whatever the guard says, and after the merge it also stops that timer from resetting a half-closed CONNECT tunnel once END_STREAM is out.
  • 💡 The release note repeats the area and the indent the generator adds and describes the half-close mode main removed.
  • 💡 The new shard count on the upstream test looks unrelated to the fix and conflicts with main.

void ConnectionManagerImpl::ActiveStream::endStream() {
ASSERT(!state_.codec_saw_local_complete_);
state_.codec_saw_local_complete_ = true;
if (!connection_manager_.allow_upstream_half_close_ &&

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

⚠️ Main removed allow_upstream_half_close_ in #48648, so the new gate merges without a conflict and then fails to build, and the integration fixture's override of the removed guard aborts a debug run. Could we merge main, key the gate on isHalfCloseEnabled(), drop the removed overrides and have the half-close test call enableHalfClose() before it responds?


// Normal completion must preserve a response that
// HTTP/2 flow control still holds in the codec. Explicit aborts retain reset semantics.
void ConnectionManagerImpl::ActiveStream::endStream() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

❓ The HTTP/2 codec already defers a server reset to the end of the same send so END_STREAM can go out, then resets anyway when flow control blocks it. Should the codec hold that reset, as HTTP/3 does, leaving this PR's HCM retention as the hybrid #49126 asks about, rather than adding request handling, scheduling and reset mapping here?

@agrawroh agrawroh Nov 20, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Greg answered this for the codec hold in #49126, which I agree with, so this question is settled.

ENVOY_EXECUTION_SCOPE(trackedStream(), active_span_.get());
maybeRecordLastByteReceived(end_stream);
filter_manager_.streamInfo().addBytesReceived(data.length());
if (handleRequestDuringResponseFlush()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 Request DATA that arrives while a filter has reads disabled never reaches the HCM, so the codec keeps it and its connection window until the hold ends, which can stall other uploads on the connection. Wherever the hold lands, could it return that window without dropping the request's end, as #49126 does in the codec?

state_.is_zombie_stream_ = true;
filter_manager_.setLocalComplete();
// Keep only the codec flush timer. Do not charge stream destruction until the final exit.
disarmStreamTimers();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 The hold disarms every stream timer, while the codec arms no flush timer on some trailer paths, such as empty trailers behind a blocked body, so those holds have no deadline. Could every held stream keep a flush deadline when the flush timeout is set?

// then perform the same post-reset drain check as doEndStream, even outside dispatch.
auto& connection_manager = connection_manager_;
const bool skip_delay = shouldSkipDeferredCloseDelay();
response_encoder_->getStream().resetStream(reason);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 An abort during the hold sends the caller's reason as is, so a module's refused-stream reset becomes REFUSED_STREAM after a processed response, which invites a retry. If the hold stays here, could that reason go out as a plain local reset during the hold?

const bool end_stream_sent = flags & FLAG_END_STREAM;
stream->local_end_stream_sent_ = end_stream_sent;
if (end_stream_sent) {
if (adapter_->IsServerSession()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 The codec's new flush-timer disarm runs whatever the guard says, and after the merge it also stops that timer from resetting a half-closed CONNECT tunnel once END_STREAM is out. Could the release note say so, since it says tunnels keep their behavior and the guard restores the old one?

@@ -0,0 +1,8 @@
http2: preserve fully submitted responses before normal local resets of open downstream requests

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 The release note repeats the area and the indent the generator adds and describes the half-close mode main removed. Neither it nor the lifecycle docs say these streams now record request time, and log and trace after delivery, or that local replies sent during dispatch reset a loop later. Could we update both for the merged behavior?

srcs = ["upstream_impl_test.cc"],
data = ["//test/common/tls/test_data:certs"],
rbe_pool = "linux_x64_small",
shard_count = 2,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 The new shard count on the upstream test looks unrelated to the fix and conflicts with main. Could we drop it here?

@bingqifan

Copy link
Copy Markdown
Contributor Author

🚫 Suggested Fixes. The merge with main breaks the build, and the layer for this hold is worth settling with #49126 before more work here.

  • ⚠️ Main removed allow_upstream_half_close_ in router: remove allow_multiplexed_upstream_half_close, keep half close for TCP upstreams #48648, so the new gate merges without a conflict and then fails to build, and the integration fixture's override of the removed guard aborts a debug run.
  • ❓ The HTTP/2 codec already defers a server reset to the end of the same send so END_STREAM can go out, then resets anyway when flow control blocks it.
  • 💡 Request DATA that arrives while a filter has reads disabled never reaches the HCM, so the codec keeps it and its connection window until the hold ends, which can stall other uploads on the connection.
  • 💡 The hold disarms every stream timer, while the codec arms no flush timer on some trailer paths, such as empty trailers behind a blocked body, so those holds have no deadline.
  • 💡 An abort during the hold sends the caller's reason as is, so a module's refused-stream reset becomes REFUSED_STREAM after a processed response, which invites a retry.
  • 💡 The codec's new flush-timer disarm runs whatever the guard says, and after the merge it also stops that timer from resetting a half-closed CONNECT tunnel once END_STREAM is out.
  • 💡 The release note repeats the area and the indent the generator adds and describes the half-close mode main removed.
  • 💡 The new shard count on the upstream test looks unrelated to the fix and conflicts with main.

Thanks for the detailed review. I’ve read your comments carefully. I’ll wait until we agree on which layer should defer the reset until the full response has been sent, then update this PR if needed.

@ggreenway ggreenway left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@agrawroh I don't think we should go this route. I opened #49126 which I think is a better way to fix this. Let me know if you disagree.

@bingqifan

bingqifan commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@agrawroh I don't think we should go this route. I opened #49126 which I think is a better way to fix this. Let me know if you disagree.

Thank you for reviewing my PR and putting together a codec-based alternative. :)

@agrawroh

Copy link
Copy Markdown
Member

@ggreenway No disagreement, since the codec is the better layer and #49126 already returns the held stream's window and keeps its flush deadline, as two of my comments here asked.

@CapricornFBQ Thanks for waiting, and could you weigh in on the hybrid question in #49126, since this PR already keeps the stream until delivery the way that hybrid would?

@mattklein123

Copy link
Copy Markdown
Member

I think we are going with an alternate solution on this one.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HTTP/2 RST_STREAM(NO_ERROR) after a complete gRPC response drops pending downstream encode

6 participants