Skip to content

http: fix body drop when StopAllIteration filter re-buffers until trailers - #49151

Merged
paul-r-gall merged 8 commits into
envoyproxy:mainfrom
paul-r-gall:encode-trailers-stop
Nov 18, 2026
Merged

paul-r-gall merged 8 commits into
envoyproxy:mainfrom
paul-r-gall:encode-trailers-stop

Conversation

@paul-r-gall

@paul-r-gall paul-r-gall commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Commit Message: http: fix body drop when StopAllIteration filter re-buffers until trailers

Additional Description:

#49241 landed the held-trailers forwarding fix while this PR was in review, so merging main narrows this PR to the remaining nested-continuation bug plus the extra unit/integration tests and addEncodedTrailers() doc note.

When a filter paused in decodeHeaders(false) or encodeHeaders(false) with StopAllIterationAndBuffer / StopAllIterationAndWatermark resumes (commonContinue()), iterate_from_current_filter_ stays true for the whole outer commonContinue() call. If that filter then re-buffers the body in decodeData(false) / encodeData(false) (StopIterationAndBuffer) and returns Continue from decodeTrailers() / encodeTrailers(), commonHandleAfterTrailersCallback() runs a nested commonContinue() after end_stream_ has been marked true on the filter; because iterate_from_current_filter_ is still true, the nested doData(false) starts at the current filter, hits if ((*entry)->end_stream_) return;, and drops the buffered body before forwarding the trailers. Clearing iterate_from_current_filter_ in commonHandleAfterTrailersCallback() (under envoy.reloadable_features.filter_manager_forward_held_trailers) starts the nested pass at the next filter as intended.

Risk Level: Low (runtime guarded behind envoy.reloadable_features.filter_manager_forward_held_trailers)
Testing: Unit tests in test/common/http/filter_manager_test.cc and integration tests in test/integration/filter_integration_test.cc
Docs Changes: addEncodedTrailers() doc comment in envoy/http/filter.h
Release Notes: Added
Runtime guard: envoy.reloadable_features.filter_manager_forward_held_trailers
AI Usage: Generated by Gemini; reviewed, improved by paul-r-gall.

…tops

If an encoder filter calls `addEncodedTrailers()` in `encodeData(end_stream=true)`
and a later encoder filter then stops iteration, `FilterManager::encodeData`
returned early and never dispatched the new trailers. Filters after the adder
never saw end of stream, so streaming responses hung until the client timed out.
`decodeData` already handles the request-side equivalent by breaking out of the
loop and dispatching `decodeTrailers`.

Fix: `encodeData` now breaks on stop and, if an earlier filter added trailers,
forwards them with `encodeTrailers` starting after the adder. Two supporting
changes keep delivery exactly-once: `doTrailers()` on a resuming filter defers to
that forwarding pass when it has not yet been handed the trailers, and
`encodeTrailers` takes a `FilterIterationStartState` so the adder never receives
its own trailers when it is itself resuming from `StopAllIteration`.

Guarded by `envoy.reloadable_features.filter_manager_encode_trailers_on_stop_iteration`.

Risk Level: Medium (core HTTP filter manager, runtime guarded)
Testing: New unit tests in test/common/http/filter_manager_test.cc and an integration test in test/integration/filter_integration_test.cc
Docs Changes: N/A
Release Notes: Added
Runtime guard: envoy.reloadable_features.filter_manager_encode_trailers_on_stop_iteration

Signed-off-by: Paul Ogilby <[email protected]>
@repokitteh-read-only

Copy link
Copy Markdown

As a reminder, PRs marked as draft will not be automatically assigned reviewers,
or be handled by maintainer-oncall triage.

Please mark your PR as ready when you want it to be reviewed!

🐱

Caused by: #49151 was opened by paul-r-gall.

see: more, trace.

Covers the legacy behavior: with
envoy.reloadable_features.filter_manager_encode_trailers_on_stop_iteration
disabled, trailers added by an earlier encoder filter are dropped and the
buffering filter is never resumed, so the downstream response stays open after
the upstream request has finished.

Signed-off-by: Paul Ogilby <[email protected]>
@paul-r-gall
paul-r-gall requested a review from wbpcode November 10, 2026 18:26
@paul-r-gall
paul-r-gall marked this pull request as ready for review November 10, 2026 18:26
@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: #49151 was ready_for_review by paul-r-gall.

see: more, trace.

@paul-r-gall

Copy link
Copy Markdown
Contributor Author

/assign @yanjunxiang-google

Picks up envoyproxy#49155 (bindgen builtin headers) which fixes the format precheck.

Signed-off-by: Paul Ogilby <[email protected]>
@paul-r-gall

Copy link
Copy Markdown
Contributor Author

/retest

@citrus7 citrus7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, thanks for the thorough fix and test coverage!

@yanjunxiang-google

Copy link
Copy Markdown
Contributor

Thanks for working on this issue! This filter_manager state transition is pretty subtle — it would be great to add a brief diagram/flow in the comment illustrating which filter added the trailers, which filter stopped iteration, and which filter called commonContinue() to make this easier to follow.

Comment thread source/common/http/filter_manager.cc Outdated
// iteration) delivers them from the filter that added them; encoding from here would skip
// intermediate filters or encode the trailers twice. When resuming from StopAllIteration
// (iterate_from_current_filter_) no outer pass exists, so encode from here.
if (!end_stream_ && !iterate_from_current_filter_ &&

@yanjunxiang-google yanjunxiang-google Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If I understand the change correctly, this check prevents this filter from calling encodeTrailers() when an upstream filter hasn't finished encodeData()/encodeTrailers() yet. However, what if this filter is also an async filter that paused during encodeHeaders() by returning StopAllIterationAndBuffer (so commonContinue() sets iterate_from_current_filter_ = true)?

Specifically, in a chain Filter A -> Filter B -> Filter C (this) on the encode path:
1. Filter C pauses in encodeHeaders() with StopAllIterationAndBuffer.
2. Filter A calls addEncodedTrailers() in encodeData(..., true) and continues.
3. Filter B stops iteration in encodeData() (e.g., StopIterationNoBuffer) and encodeTrailers()
(StopIteration), so neither body nor trailers have reached Filter C yet.
4. Filter C finishes its async header processing work first and calls continueEncoding() -> commonContinue().

Since hasTrailers() is already true (due to above 2). commonContinue() will call doTrailers()

. And as iterate_from_current_filter_ is true on Filter C, it bypass this guard, and prematurely send the trailers (and endStream) to the downstream client before Filter B finishes encodeData()/encodeTrailers(). Would that happen here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks @yanjunxiang-google -- this is a pre-existing issue that I can also fix in this PR. new commit incoming presently.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, that trace is correct: with iterate_from_current_filter_ set, C's doTrailers() sent the trailers and ended the stream while B still held the body. It is the same at HEAD (guard off, or with codec-originated trailers when B stops on data), so it is pre-existing rather than introduced here, but it is the same ownership question so I fixed it under the same guard: doTrailers() now also defers when an earlier encoder filter is still stopped (earlierFilterStopped()), and B's later continueEncoding() delivers body then trailers through C. Added EncodeDataAddedTrailersDeferredWhenStopAllFilterResumesFirst for exactly your chain.

Comment thread source/common/http/filter_manager.cc Outdated
if (trailers_added_entry != encoder_filters_.end()) {
encodeTrailers(trailers_added_entry->get(), *filter_manager_callbacks_.responseTrailers());
encodeTrailers(trailers_added_entry->get(), *filter_manager_callbacks_.responseTrailers(),
FilterIterationStartState::AlwaysStartFromNext);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should this FilterIterationStartState::AlwaysStartFromNext be runtime guarded, like only set it to be AlwaysStartFromNext if runtime guard is true. Otherwise stay as default CanStartFromCurrent?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. That site now uses AlwaysStartFromNext only when the guard is on, so guard-off matches HEAD exactly; the other forwarding call is already inside the guarded block.

- Runtime-guard the AlwaysStartFromNext at the post-codec trailer forwarding
  site so guard-off behavior matches the previous code exactly.
- doTrailers() also defers when a filter resuming from StopAllIteration has an
  earlier encoder filter that is still stopped; that filter's continueEncoding()
  delivers body then trailers through this one. Previously the resuming filter
  could encode the trailers (and end the stream) before the earlier filter
  released the body.
- Add a flow diagram to the encodeData() forwarding comment and a unit test for
  the StopAll-resume-first case.

Signed-off-by: Paul Ogilby <[email protected]>
@paul-r-gall

Copy link
Copy Markdown
Contributor Author

Added a flow in the comment above the forwarding block in encodeData() showing which filter adds the trailers, which one stops, and which one ends up calling commonContinue(), with a pointer from doTrailers(). Also addressed the two inline comments (guarded AlwaysStartFromNext, and the StopAll-resume-first case) in f64e37b.

Replace the linear scan in doTrailers() with state_.encoder_iteration_stopped_at_,
the encoder filter at which the most recent encodeData()/encodeTrailers() pass
stopped. It is cleared only when a pass started by that filter (or by the
codec) reaches the codec, so a filter resuming from StopAllIteration encodes
pending trailers from itself only if it owns the stop point. Also covers
several concurrently stopped filters resuming in any order; add a test for a
chain where three filters each hold a frame and the paused filter resumes first.

Signed-off-by: Paul Ogilby <[email protected]>
@yanjunxiang-google

Copy link
Copy Markdown
Contributor

/assign @wbpcode

Comment thread source/common/http/filter_manager.cc Outdated
// return so trailers added by an earlier filter can still be forwarded below.
if (handleDataIfStopAll(**entry, data, state_.encoder_filters_streaming_)) {
return;
state_.encoder_iteration_stopped_at_ = entry->get();

@yanjunxiang-google yanjunxiang-google Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This seems having a behavior change. Better guarded by the runtime flag.

@yanjunxiang-google yanjunxiang-google Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

emm, another observation is the filter manager has only one state_. And a single pointer state_.encoder_iteration_stopped_at_ only tracks the filter where the most recent encodeData()/encodeTrailers() pass stopped, not whether any
earlier filter is still stopped. When multiple filters are stopped concurrently, a middle filter resuming into a downstream StopAllIteration filter overwrites
encoder_iteration_stopped_at_ with the downstream filter, erasing the fact that an earlier filter still holds a body frame.

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

thanks Paul for the fix, and just have one thought.

Comment thread source/common/http/filter_manager.cc Outdated
// return so trailers added by an earlier filter can still be forwarded below.
if (handleDataIfStopAll(**entry, data, state_.encoder_filters_streaming_)) {
return;
state_.encoder_iteration_stopped_at_ = entry->get();

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.

encoder_iteration_stopped_at_ records the last stop point, not where the trailers are. Those differ when a StopAll filter resumes after the codec trailers are already waiting at it: its own resume pass can stop at a later filter, which overwrites the pointer, and then it defers trailers that nobody else will deliver.

B (StopAllIterationAndBuffer on encodeHeaders) -> C -> codec
codec: data(false), trailers          // both wait at B, stopped_at = B
B.continueEncoding()
  doHeaders(): C StopIteration
  doData():    C StopIterationAndBuffer, stopped_at = C
  doTrailers(): !end_stream_ && stopped_at != this -> defer

C never gets encodeTrailers(). With the guard on (the default):

If C buffers until end of stream (ext_proc BUFFERED, encoder-decoder-buffer-filter), the downstream response hangs. As an upstream filter it ends in a 504 at the route timeout.

If C holds the body and resumes on its own, its doTrailers() defers too, so the trailers never reach the codec.

If C also stops all, B’s encodeTrailers() is skipped.

The trailers are a single frame that only moves forward, so can we track where they wait instead of the last stop point? For example, encoder_trailers_waiting_at_, set only where encodeTrailers() returns at a stoppedAll() filter, and then:

if (!end_stream_ && parent_.state_.encoder_trailers_waiting_at_ != this && <guard>) {
  return;
}

That drops started_by_owner and the writes in encodeData(). here is a proposed change: botengyao@b6f13a3 and tests: botengyao@b2714e6

WDYT?

… filter

Drop `encoder_iteration_stopped_at_` in favor of reading whether trailers have
reached a resuming `StopAllIteration` filter off its immediate predecessor
(`trailersReachedThisFilter()`: `predecessor->end_stream_ &&
predecessor->canIterate()`). Because the trailers pass is sequential, this
handles concurrent multi-filter stops, multi-chunk streaming into a `StopAll`
filter, and `StopAll` resuming into a downstream buffering filter with zero
`FilterManager` state.

Also guard the `handleDataIfStopAll` `break`, stop `encodeTrailers` at a filter
whose `end_stream_` is already set, and clear `iterate_from_current_filter_`
before nested `commonContinue()` in `commonHandleAfterTrailersCallback()` so a
`StopAll` filter that re-buffers the body until trailers does not drop the body
or deliver duplicate trailers.

Signed-off-by: Paul Ogilby <[email protected]>
@paul-r-gall

Copy link
Copy Markdown
Contributor Author

@botengyao and @yanjunxiang-google i have refactored. "should process trailers" is determined by whether or not the previous filter

  1. has encoded end stream.
  2. has then continued iteration.

Rename `upstream_filter` / `downstream_filter` in `EncoderTrailerChain` to
`first_filter` / `last_filter` and `upstream` / `mid_upstream` /
`mid_downstream` / `downstream` in the 4-filter tests to `filter_1`..`filter_4`
so filter roles in the encoder chain do not collide with `upstream_http_filters`
terminology.

Signed-off-by: Paul Ogilby <[email protected]>
@botengyao

Copy link
Copy Markdown
Member

@paul-r-gall could you merge main?

@paul-r-gall paul-r-gall changed the title http: propagate added response trailers when encoder data iteration stops http: fix body drop when StopAllIteration filter re-buffers until trailers Nov 17, 2026
@paul-r-gall

Copy link
Copy Markdown
Contributor Author

@paul-r-gall could you merge main?

merged. @wbpcode 's changes made this PR much simpler.

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

LGTM. Thanks.

@paul-r-gall
paul-r-gall merged commit 9042726 into envoyproxy:main Nov 18, 2026
26 checks passed
botengyao added a commit that referenced this pull request Nov 18, 2026
)

Commit Message: http: test a StopAll filter that buffers the body until
trailers
Additional Description:
Test-only follow-up to #49151, which fixed the body dropped by a filter
that resumes from StopAllIteration, buffers the replayed body and
continues from its trailers callback. It closes two gaps in the tests
for that fix.

- `StopAllDecoderFilterRebuffersBodyUntilRequestTrailers`: It runs with
async host resolution, so the router stops all iteration on headers too
and replays the shared request buffer itself when it resumes, which
delivers the body the filter failed to forward. The test now runs in
both modes. Without async host resolution the upstream gets an empty
body without the fix and the full body with it. The async case is kept
as `...AsyncLb` and covers the path where the router is stopped as well.
- `FilterManagerTrailersInvariantTest` has no stop kind for this case.
`StopAllThenBufferData` adds 24 cases (both directions, every add phase
and stopper position).

Risk Level: Low (test only)
Docs Changes: N/A
Release Notes: N/A
Platform Specific Features: N/A
AI Usage: AI helped write and run these tests; I reviewed the change.

---------

Signed-off-by: Boteng Yao <[email protected]>
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.

5 participants