Skip to content

Fix: Abort the client connection when an upstream stream breaks mid-body - #1588

Merged
huang195 merged 4 commits into
mainfrom
fix/truncated-stream-1543
Oct 29, 2026
Merged

huang195 merged 4 commits into
mainfrom
fix/truncated-stream-1543

Conversation

@huang195

@huang195 huang195 commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Fixes #1543 and its CI-test companion #1552. The bug was reproduced first as failing tests across every relay arm, which now pin the fixed behavior.

The bug

When the upstream broke a streamed response partway, every relay arm of the forward proxy stopped copying and returned normally — so net/http wrote the terminating chunk (h1) or END_STREAM (h2), and the agent read a complete 200 off a cut-off stream. A truncated answer treated as finished. Invisible in the session view too: the row said 200 with no error, so agentop hid the failure. The same happened on the proxy's own 5-minute streamReadIdleTimeout cutoff (the issue's log analysis: 103 such lines over 17 hours, 68 of them the idle cutoff killing MCP's standing GET). The reverse proxy already aborted (httputil.ReverseProxy semantics); only the forward proxy lied — the exact listener divergence core/listener/parity exists to catch.

The fix

On a mid-body upstream read error, the three relay arms — SSE relay (streaming responder), SSE passthrough, and the unbuffered io.Copy including the skip-hosts copy — now:

  1. Classify and record: pipeline.ExchangeFailure builds the row's error (upstream_error, the already-sent status as error.code), exactly as the buffered path has recorded mid-body breaks since Bug: A timed-out or refused upstream request is not flagged as an error on any abctl screen #1045. The session view and /v1/usage stop showing these as clean 200s.
  2. panic(http.ErrAbortHandler) — the standard library's own abort signal: deferred finalization and recording still run, net/http does not log it as a panic, and the client's connection is reset (h1) or gets RST_STREAM (h2) instead of a clean end. The unbuffered arm flushes its buffered bytes first, so the headers and partial body reach the client before the reset.

The one exception is a client that hung up first (context canceled): nobody is left to abort for — plain return, Debug log (the WARN there violated the client-cancel logging rule), and the row carries client_canceled like the buffered path.

Shared classifier: classifyBrokenStream. Nothing in the handler chain recovers panics except dispatchFinish's OnFinish isolation, so ErrAbortHandler reaches net/http intact.

Tests (the #1552 table)

All failed on main, pass on this branch:

  • forwardproxy truncated_stream_test.go — the three arms (client read errors + row carries upstream_error/200), a clean-stream control (no abort on healthy streams, no row error), and skip_hosts (aborts the connection, records nothing — the bypass promise is about recording, not about lying).
  • forwardproxy truncated_stream_bridge_test.go — the same truncation through the TLS bridge, the laptop's own shape: the abort propagates across the decrypt → relay → re-originate loop to the agent's TLS connection (h1).
  • reverseproxy truncated_stream_test.go — the parity control: the reverse proxy already aborted (the issue measured this); pinned so the two listeners cannot drift on this behavior in either direction.

Existing sse_relay, mcp_sse_*, bytescount and buffered-failure suites all pass unchanged.

Verification

  • go test ./... in core — 75 packages, all pass; go vet, gofmt, go mod tidy -diff clean
  • CLAUDE.md's event-schema section documents the streamed-truncation behavior (no 502 to synthesize — row keeps the sent status + error, connection aborted)

Out of scope, per the issue: whether 5 minutes is the right idle cutoff for a stream that is idle by design (MCP's standing GET). With this fix the cut is at least visible to the client, which can reconnect.

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • Bug Fixes
    • Streaming responses that fail partway through now end with a connection error instead of appearing to complete normally. This applies to forward and reverse proxy traffic, including server-sent events.
    • Failures retain the upstream response status and count as usage errors. Proxy-caused interruptions, such as idle timeouts or oversized SSE frames, are distinguished from upstream failures.
    • Streams skipped by host rules still abort on failure without creating a response record.
  • Documentation
    • Clarified how streamed failures are reflected in response records and client connections.

…ody (#1543, #1552)

When the upstream broke a streamed response partway, every relay arm of
the forward proxy stopped copying and RETURNED NORMALLY, so net/http
wrote the terminating chunk (h1) or END_STREAM (h2) and the agent read a
COMPLETE 200 off a cut-off stream — a truncated answer treated as
finished, invisible in the session view too (the row said 200, no
error). The same happened on the proxy's own 5-minute idle cutoff. The
reverse proxy already aborted (httputil.ReverseProxy semantics); only
the forward proxy lied.

On a mid-body upstream read error, the three relay arms (SSE relay with
a streaming responder, SSE passthrough, unbuffered io.Copy — including
the skip_hosts copy) now:

- classify via pipeline.ExchangeFailure and put the failure on the
  response row (error.kind upstream_error, the sent status as
  error.code), so the session view and /v1/usage stop showing these as
  clean 200s;
- panic(http.ErrAbortHandler) — the standard library's own abort
  signal: deferred finalization and recording still run, net/http does
  not log it, and the client's connection is reset instead of cleanly
  ended. A client that hung up first (context canceled) is the one
  case with nobody left to abort for: plain return, Debug log, row
  carries client_canceled. The WARN on that path is gone per the
  client-cancel logging rule.

Reproduced first as failing tests across all arms, now the pinning
tests: forwardproxy truncated_stream_test.go (three arms + clean
control + skip_hosts aborts-but-records-nothing + error kind/code on
the row), truncated_stream_bridge_test.go (through the TLS bridge,
h1), and reverseproxy truncated_stream_test.go (the parity control the
issue's measurement said already passed — pinned so the two listeners
cannot drift on this again, #1552's table).

Fixes #1543
Fixes #1552

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 requested a review from a team as a code owner October 29, 2026 21:45
@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Walkthrough

Forward-proxy streaming paths now classify read failures, record them on response events, and abort responses when the client remains connected. Usage accounting counts explicit response errors. Tests cover truncated streams across forward-proxy, TLS-bridge, and reverse-proxy paths.

Changes: Stream failure handling

Layer / File(s) Summary
Classify and abort failed streams
core/listener/forwardproxy/server.go, CLAUDE.md
Forward-proxy relay paths classify stream failures and attach them to response events. Idle cutoffs and oversized SSE frames use proxy_error; other read failures use upstream_error. When the client has not canceled, the proxy aborts the response. The documentation describes these outcomes.
Count explicit response errors
core/cost/usage/usage.go, core/cost/usage/upstreamfailure_test.go
Usage accounting counts events with an explicit error as errors, including events that retain a 200 status. The test checks that the response remains in the 200 status series.
Verify truncated-stream outcomes
core/listener/forwardproxy/truncated_stream_test.go, core/listener/forwardproxy/truncated_stream_bridge_test.go, core/listener/reverseproxy/truncated_stream_test.go
Tests check client-visible read errors for truncated streams across forward-proxy, TLS-bridge, and reverse-proxy paths. They also cover clean streams, skipped hosts, failure classification, client cancellation, and idle cutoffs.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Upstream
  participant ForwardProxy
  participant ResponseEvent
  participant Client
  Upstream->>ForwardProxy: Stream response body
  ForwardProxy->>ResponseEvent: Record classified failure and upstream status
  ForwardProxy-->>Client: Abort response after read failure
Loading

Possibly related issues

Suggested labels: ready-for-ai-review

Suggested reviewers: mrsabath, esnible, alan-cha

Merge Risk: Low · up to f9300

When the durable ledger is configured, usage error totals can disagree across time windows. This is a bounded reporting issue to resolve or explicitly accept before merging.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Linked Issues check Inconclusive Issue #1543 requires three things. A truncated upstream stream must not reach the client as a clean 200. The response row must carry an error. Passthrough, SSE-relay, and bridged TLS paths must be cov… Make the incremental diff of core/listener/forwardproxy/server.go and core/listener/forwardproxy/truncated_stream_test.go (previousReviewedHead 9d0f4bf to head f9300ad) readable, by making the changed blobs available in the checkout. With t…
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the primary change: aborting the client connection when an upstream stream breaks mid-body.
Out of Scope Changes check Passed Changes are connected to #1543 or to the stated PR objectives.
- core/cost/usage/usage.go (verified in the incremental diff): countsAsError counts explicit row errors. The PR states that /v1/usage mus…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Out of Scope Changes check

Explanation

Changes are connected to #1543 or to the stated PR objectives.

  • core/cost/usage/usage.go (verified in the incremental diff): countsAsError counts explicit row errors. The PR states that /v1/usage must stop showing these rows as clean 200s. The change is required for that statement. The existing exclusions for declined upgrades and private-destination refusals are kept.
  • core/listener/forwardproxy/server.go (incremental diff not readable; the summary describes it): proxy_error classification for proxy-caused cuts (idle cut and oversized SSE frame) and the errIdleCut sentinel. The objectives list both proxy_error classification and the errIdleCut-style distinction as reported changes. The SSE frame-cap classification is not named in issue #1543. It sits in the same error-recording path and is named in the PR objectives, so it is not an unrelated change.
  • Tests (truncated_stream*_test.go, reverseproxy truncated_stream_test.go, usage upstreamfailure_test.go): cover the same behaviors.
  • CLAUDE.md: documentation of the same streamed-truncation behavior.

No change alters the 5-minute streamReadIdleTimeout value. The PR excludes that policy, and no evidence shows the value changed.

Limit: the server.go and truncated_stream_test.go incremental diffs were not readable. This PASS relies on the whole-PR summary and the verified usage.go diff.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 12 functions across 6 files. (1 skipped: 1 unsupported.)

Full details: Linked Issues check

Explanation

Issue #1543 requires three things. A truncated upstream stream must not reach the client as a clean 200. The response row must carry an error. Passthrough, SSE-relay, and bridged TLS paths must be covered.

Prior conclusion at reviewed head 9d0f4bf: PASS. The SSE relay, SSE passthrough, and unbuffered io.Copy arms called classifyBrokenStream, then panicked with http.ErrAbortHandler. The row carried upstream_error with code 200. Tests covered the three arms, the TLS bridge, and a clean-stream control.

Changes since 9d0f4bf (head f9300ad):

  • core/cost/usage/usage.go: verified. countsAsError now also returns true when e.Error is non-nil. This supports the PR claim that /v1/usage no longer counts these rows as clean.
  • core/listener/forwardproxy/server.go: not verified. The incremental diff could not be read because the changed blobs are missing from the checkout. The reported changes include proxy_error classification for idle cuts and SSE frame-cap breaches, errIdleCut on idleReadCloser, and a StatusCode reset. These sit on the core abort path that satisfies #1543.
  • Forward-proxy truncated_stream_test.go: incremental diff also unreadable for the same reason.

The prior PASS depended on server.go code that has since changed. I cannot confirm that the current code still aborts on every mid-body break, or that the row still carries the error, in every arm. The 9d0f4bf conclusion is not sufficient for head f9300ad.

Resolution

Make the incremental diff of core/listener/forwardproxy/server.go and core/listener/forwardproxy/truncated_stream_test.go (previousReviewedHead 9d0f4bf to head f9300ad) readable, by making the changed blobs available in the checkout. With that evidence, confirm the following at head. Each mid-body read error in the three relay arms reaches http.ErrAbortHandler, except client cancel. The row carries an Error with the sent status. The new proxy_error and errIdleCut paths keep that behavior. Then re-run the review.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

_, fail = pipeline.ExchangeFailure(r.Context(), err)
fail.Code = strconv.Itoa(resp.StatusCode)
if r.Context().Err() != nil {
slog.Debug("forward-proxy: streaming response ended by client hangup", "host", r.Host, "error", err)
return fail, false
}
slog.Warn("forward-proxy: streaming response read error — aborting the client connection",
"host", r.Host, "kind", fail.Kind, "error", fail.Message)
Review round on #1588:

- countsAsError now counts a row's explicit error, so a truncated stream's
  row — which keeps its delivered 200 because the status is already on the
  wire — raises the /v1/usage error rate instead of folding in as healthy.
- The idle read cutoff and an SSE frame over the frame cap now record
  proxy_error instead of upstream_error: both are the proxy's cuts, not the
  upstream's, and on the issue's own log the idle cutoff was the majority of
  truncated streams. idleReadCloser surfaces errIdleCut when its timer, not
  the upstream, closed the body; classifyBrokenStream keys on it and on
  sseframe.ErrFrameTooLarge.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
classifyBrokenStream now resets pctx.StatusCode to zero, matching the
buffered path's contract: the deferred RunFinish derives the outcome
from it, and a 200 there reported OutcomeAllow for an exchange the
client saw reset — lineage labelling "ok" a failed one. The response
row is unaffected; it records resp.StatusCode, the status already on
the wire.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

The fix is correct. panic(http.ErrAbortHandler) on a mid-body read error is the right way to stop net/http writing the terminating chunk or END_STREAM. The deferred finalize and record still run on the panic path in both SSE arms, and the plain arm records before it panics. The only recover() in the tree is dispatchFinish, so the abort reaches net/http intact. Resetting pctx.StatusCode to 0 matches the buffered path, and errIdleCut / ErrFrameTooLarge -> proxy_error is a good split.

I built the branch and ran the new tests on go1.27.3. TestForwardProxy_TruncatedStream_ReachesClientAsError, TruncatedSkippedStream, CleanStream, ClassifyBrokenStream_*, IdleReader_CutSurfacesSentinel and the reverse-proxy parity test passed 200/200 each. I also reverted server.go and usage.go to main and checked that a stream the client closes recorded 200/no error before this PR, so the change in row semantics noted below is real. Nothing blocks the merge. The inline comments cover a flaky new test, the ledger's error count not matching the ring's, and a question about client hangups on long-lived streams.

Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (forwardproxy relay arms, idleReadCloser, usage aggregator), tests, CLAUDE.md docs
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits, all signed-off: yes
CI status: passing (all required checks green)

// which that test's comment explains).
func TestForwardProxy_TruncatedStream_BridgedReachesClientAsError(t *testing.T) {
// TLS origin: one flushed SSE event, then a TCP reset.
origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion — This test is flaky. It failed 3/100 locally with -count=100, and failed every time when I made the origin wait a little before the reset.

Cause: bridgeServe sends its upstream-verify HEAD through TLSBridge.Upstream before it forges, and this handler answers the HEAD as well. It hijacks and RSTs that keep-alive connection. The bridged GET can then reuse the dead pooled connection, get EOF, and the proxy answers a clean 502 (WARN forward-proxy: upstream request failed ... error=EOF). io.ReadAll reads that body without error, so the test reports "clean end of body" even though the truncation path never ran.

Fix: skip the HEAD in the handler:

origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodHead {
		return
	}
	...

With that change it passed 300/300. Also asserting resp.StatusCode == 200 before the body read would make any future regression of this kind fail with a clear message instead of a misleading one.

Comment thread core/cost/usage/usage.go
return false
}
return e.StatusCode >= 400 || e.Phase == pipeline.SessionDenied
return e.Error != nil || e.StatusCode >= 400 || e.Phase == pipeline.SessionDenied

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion — The ring now counts a row's explicit Error, but the durable ledger still decides Errors from status alone (core/cost/ledger/writer.go:514: if e.StatusCode >= 400 || e.Phase == pipeline.SessionDenied { r.Errors = 1 }). ledger.Fold sums r.Counts into the totals, so a truncated inference stream (the main case #1543 is about) raises the error count for window=1h (ring) but not for window=today (ledger). Those two surfaces are meant to agree. I'd suggest moving the predicate into one shared helper, or giving the writer the same e.Error != nil clause plus the upgrade_declined / destination_private exemptions, with a ring-vs-ledger agreement test like the existing TestLedgerAndRingAgree* ones.

}
fail.Code = strconv.Itoa(resp.StatusCode)
pctx.StatusCode = 0
if r.Context().Err() != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion — A question about intent. The client-hangup branch now puts client_canceled (code 200) on the row, and with the countsAsError change that row counts as an error in /v1/usage and the timeline. I verified on this branch that a client which simply closes an open SSE stream (passthrough and relay arms) now records status=200 error={client_canceled 200 "context canceled"}. On main the same exchange recorded 200/no error. For buffered requests a 499 counted as an error is long-standing. For open-ended streams, though, the client closing is often the normal end: an MCP standing GET closed when the session ends, or the user interrupting an agent mid-reply. Every such close would now add to the error rate. If that is intended, a sentence in the CLAUDE.md paragraph would help. If not, countsAsError could exempt client_canceled when the status is below 400.

dst = flushWriter{w: w, f: f}
}
var streamFail *pipeline.EventError
if _, err := io.Copy(dst, resp.Body); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit — On this arm, io.Copy's error can come from either side. A downstream write failure (broken pipe) that wins the race against r.Context() cancellation is classified by TransportError as upstream_error and blamed on the upstream. The SSE arms avoid this because they handle write errors separately (Debug log plus break/return). In practice the context is almost always canceled first (40/40 hangups in my run came out client_canceled), so this is low priority. Telling the two apart would mean wrapping resp.Body to capture the read-side error.

Fixes review: the origin handler hijacked+RST the bridge's upstream-verify
HEAD, poisoning the pooled conn the GET could reuse — the proxy then answered
a clean 502 and the test flaked (3/100) with a misleading "clean end of body"
message. Answer the HEAD with a normal 200 in the handler and fail fast on a
non-200 status so a regression of this kind reports its actual cause.

Files: core/listener/forwardproxy/truncated_stream_bridge_test.go

Signed-off-by: Hai Huang <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
@huang195
huang195 merged commit f4ff461 into main Oct 29, 2026
41 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 29, 2026
@huang195
huang195 deleted the fix/truncated-stream-1543 branch October 29, 2026 23:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

bug: Forward proxy ends a broken upstream stream as a clean, complete 200

3 participants