From 03554f20b9c73bcc9b31166aa187ab0aeca277f5 Mon Sep 17 00:00:00 2001 From: BrianBoy Date: Thu, 3 Dec 2026 12:56:47 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(command):=20=E6=B5=81=E6=88=AA=E6=96=AD?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E5=86=B7=E5=8D=B4=E8=B4=A6=E5=8F=B7=20/=20ke?= =?UTF-8?q?ep=20accounts=20routable=20on=20a=20truncated=20stream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Command Code stream that the upstream cut after delivering content was classified as a generic `unavailable` error, which applies a 15s cooldown that `nextBackoffCooldown` lifts to the 30s floor on repeat failures. On a single-account route that turns one truncated answer into a burst of "all accounts are cooling down" failures, and the client reads them as rate limiting rather than as a retryable upstream cut. Report the cut with a distinct `upstream_stream_truncated` code and, following the `upstream_empty` precedent, keep the account routable (failover, cooldown 0, retry-after 0). Also carry the observed stream shape in the message so a cut answer can be told apart from an upstream that aborted before producing anything; no prompt or completion text is included. Gated behind: - go test ./... / -race on command+executor / go vet ./... / gofmt - scripts/release-notes.py validate --- .../unreleased/command-stream-truncation.md | 9 +++ internal/executor/classify_test.go | 80 ++++++++++++++++++- internal/executor/error.go | 14 ++++ internal/providers/command/chat.go | 5 +- internal/providers/command/chat_test.go | 62 ++++++++++++++ internal/providers/command/errors.go | 24 ++++++ internal/providers/command/rewrite.go | 9 ++- internal/providers/command/wire.go | 56 +++++++++++++ internal/providers/tlserr.go | 6 ++ 9 files changed, 259 insertions(+), 6 deletions(-) create mode 100644 changelog/unreleased/command-stream-truncation.md diff --git a/changelog/unreleased/command-stream-truncation.md b/changelog/unreleased/command-stream-truncation.md new file mode 100644 index 000000000..1a4fefefc --- /dev/null +++ b/changelog/unreleased/command-stream-truncation.md @@ -0,0 +1,9 @@ +### English + +- A Command Code stream that the upstream cuts after delivering content no longer cools the account down. The cut is reported as `upstream_stream_truncated` and the account stays routable, so one truncated answer no longer turns into a burst of `all accounts are cooling down` failures on a single-account route. +- The Command Code truncation error now reports the shape of the stream it saw (event count, bytes, last event type, whether real content arrived) instead of a constant string, so a cut answer can be told apart from an upstream that aborted before producing anything. Prompt and completion text are never included. + +### 中文 + +- 上游已下发内容后被切断的 Command Code 流不再冷却账号。该类中断以 `upstream_stream_truncated` 上报,账号保持可路由,单账号路由上的一次截断不会再演变成一串 `all accounts are cooling down` 失败。 +- Command Code 的截断错误现在会带上实际观测到的流形态(事件数、字节数、最后一个事件类型、是否出现过真实内容),而不是固定文案,因此可以把「答到一半被切」和「上游什么都没产出就中断」区分开。提示词与生成内容不会写入该信息。 diff --git a/internal/executor/classify_test.go b/internal/executor/classify_test.go index 1654c4495..233688496 100644 --- a/internal/executor/classify_test.go +++ b/internal/executor/classify_test.go @@ -352,8 +352,6 @@ func TestObserveStreamFailureIgnoresCancellation(test *testing.T) { } func TestClassifyErrorUpstreamEmptyNoCooldown(t *testing.T) { - // A heartbeat-only empty upstream stream says nothing about the account's - // health: fail over, but never cool the account down. err := ClassifyError(&providers.Error{ Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, @@ -387,6 +385,84 @@ func TestClassifyErrorUpstreamEmptyNoCooldown(t *testing.T) { } } +// TestClassifyErrorStreamTruncatedNoCooldown pins the Command Code fix: a stream +// the upstream cut after delivering content is not an account fault. Cooldown +// must be exactly zero, because any positive value is lifted to the 30s backoff +// floor (nextBackoffCooldown) and one cut stream then freezes a single-account +// route behind "all accounts are cooling down". +func TestClassifyErrorStreamTruncatedNoCooldown(t *testing.T) { + err := ClassifyError(&providers.Error{ + Kind: accounts.KindUnavailable, + Status: http.StatusBadGateway, + Code: providers.CodeStreamTruncated, + Message: "command code stream ended before a terminal event (532 events, 122605 bytes, last type \"message\", content=true)", + }) + if err.Kind != accounts.KindUnavailable { + t.Errorf("kind = %q, want %q", err.Kind, accounts.KindUnavailable) + } + if err.Code != providers.CodeStreamTruncated { + t.Errorf("code = %q, want %q", err.Code, providers.CodeStreamTruncated) + } + if !err.Failover { + t.Error("expected Failover=true so another account can serve the turn") + } + if err.Cooldown != 0 { + t.Errorf("cooldown = %v, want 0 (any positive value is lifted to the 30s floor)", err.Cooldown) + } + if err.RetryAfter != 0 { + t.Errorf("retry-after = %v, want 0", err.RetryAfter) + } +} + +// TestStreamReadErrorPreservesTruncatedCode guards the streaming path: the +// gateway wraps the pipe error with StreamReadError, which unwraps provider +// errors today. If that changed, the code would be lost and the account would be +// cooled down again. +func TestStreamReadErrorPreservesTruncatedCode(t *testing.T) { + wrapped := StreamReadError(&providers.Error{ + Kind: accounts.KindUnavailable, + Status: http.StatusBadGateway, + Code: providers.CodeStreamTruncated, + Message: "command code stream ended before a terminal event", + }) + classified := ClassifyError(wrapped) + if classified.Code != providers.CodeStreamTruncated { + t.Fatalf("code = %q, want %q", classified.Code, providers.CodeStreamTruncated) + } + if classified.Cooldown != 0 { + t.Errorf("cooldown = %v, want 0 after wrapping", classified.Cooldown) + } +} + +// TestStreamTruncationDoesNotCoolPool is the end-to-end assertion the fix exists +// for: observing a truncation on the only account must leave it routable, so the +// very next pick succeeds instead of returning "all accounts are cooling down". +func TestStreamTruncationDoesNotCoolPool(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "only", Provider: "command", Region: "global", Models: []string{"deepseek/deepseek-v4.1-flash"}}) + ex := NewChatExecutor(pool, "") + ex.ObserveStreamFailure("only", &providers.Error{ + Kind: accounts.KindUnavailable, + Status: http.StatusBadGateway, + Code: providers.CodeStreamTruncated, + Message: "command code stream ended before a terminal event", + }, "deepseek/deepseek-v4.1-flash") + + item, ok := pool.ByID("only") + if !ok { + t.Fatal("account vanished from the pool") + } + if !item.DownUntil.IsZero() { + t.Fatalf("account cooled down until %v", item.DownUntil) + } + if len(item.ModelDownUntil) != 0 { + t.Fatalf("model cooled down: %v", item.ModelDownUntil) + } + if retryAfter := pool.RetryAfter(item, "deepseek/deepseek-v4.1-flash", nil); retryAfter > 0 { + t.Fatalf("pool still reports retry-after %v for the truncated account", retryAfter) + } +} + // A streaming first-byte timeout is an upstream hang: the client request is // still alive, the upstream just never sent a response head. It must classify // as upstream_unavailable with failover so the next eligible account serves diff --git a/internal/executor/error.go b/internal/executor/error.go index d9d3247cc..e55a20362 100644 --- a/internal/executor/error.go +++ b/internal/executor/error.go @@ -180,6 +180,20 @@ func ClassifyError(err error) Classified { classified.Failover = true classified.Cooldown = 0 } + if providerErr.Code == providers.CodeStreamTruncated { + // The upstream answered 200, delivered content, and then ended the + // stream without a protocol terminal event. Same reasoning as + // upstream_empty: the cut is on the upstream or transport side, not a + // credential, quota, or rate-limit problem, so the account stays + // routable. Cooldown must be exactly 0: any positive value is lifted to + // the 30s backoff floor (see nextBackoffCooldown), which turns a single + // cut stream into a frozen pool. The abort is logged as a failure by the + // gateway, so the operator still sees it — no cooldown is needed to make + // it visible. + classified.Failover = true + classified.Cooldown = 0 + classified.RetryAfter = 0 + } switch classified.Kind { case accounts.KindRateLimit: switch { diff --git a/internal/providers/command/chat.go b/internal/providers/command/chat.go index 8cddc53a6..0bc611b91 100644 --- a/internal/providers/command/chat.go +++ b/internal/providers/command/chat.go @@ -140,6 +140,7 @@ type aggregate struct { finishReason string sawTerminalEvent bool sawError error + stats streamStats } func newAggregate() *aggregate { @@ -227,7 +228,7 @@ func (a *aggregate) toolCalls() []map[string]any { func aggregateResponse(body io.Reader, model string) (providers.ChatOutcome, error) { agg := newAggregate() - if err := streamEvents(body, func(event generateEvent) error { + if err := streamEventsObserved(body, &agg.stats, func(event generateEvent) error { agg.apply(event) return nil }); err != nil { @@ -237,7 +238,7 @@ func aggregateResponse(body io.Reader, model string) (providers.ChatOutcome, err return providers.ChatOutcome{}, agg.sawError } if !agg.sawTerminalEvent { - return providers.ChatOutcome{}, newProviderError(502, "command code stream ended before a terminal event") + return providers.ChatOutcome{}, newStreamTruncatedError(agg.stats.describe()) } return outcomeFromAggregate(agg, model), nil } diff --git a/internal/providers/command/chat_test.go b/internal/providers/command/chat_test.go index a0cba89d6..a814acef9 100644 --- a/internal/providers/command/chat_test.go +++ b/internal/providers/command/chat_test.go @@ -139,6 +139,68 @@ func TestChatNonStreamNoTerminalEvent(t *testing.T) { if !asProviderError(err, &providerErr) || providerErr.Kind != accounts.KindUnavailable { t.Fatalf("truncated stream must classify as unavailable, got %v", err) } + // The distinct code is what keeps the executor from cooling the account + // down for a cut the account had nothing to do with. + if providerErr.Code != providers.CodeStreamTruncated { + t.Errorf("code = %q, want %q", providerErr.Code, providers.CodeStreamTruncated) + } +} + +// TestChatNonStreamTruncationReportsObservedShape covers the operator-facing +// half of the fix: the error says what the stream looked like, so a cut answer +// can be told apart from an upstream that aborted before producing anything. +func TestChatNonStreamTruncationReportsObservedShape(t *testing.T) { + body := ndjson( + `{"type":"start"}`, + `{"type":"text-delta","id":"t0","text":"Hel"}`, + ) + srv, _, _ := generateServer(t, 0, body) + client, _ := newTestClient(t, srv) + _, err := client.ChatNonStream(t.Context(), "acc-1", chatReq()) + if err == nil { + t.Fatal("truncated stream must error") + } + message := err.Error() + for _, want := range []string{"2 events", "content=true", `last type "text-delta"`} { + if !strings.Contains(message, want) { + t.Errorf("truncation detail missing %q in %q", want, message) + } + } + // The account is healthy; the report must not carry the prompt wording. + if strings.Contains(message, "partial") { + t.Errorf("error must not echo streamed content: %q", message) + } +} + +// TestChatStreamTruncationSurfacesCode covers the streaming path: the gateway +// relay reads the pipe error, and StreamReadError must preserve the code so the +// executor keeps the account routable. +func TestChatStreamTruncationSurfacesCode(t *testing.T) { + body := ndjson( + `{"type":"text-delta","id":"t0","text":"Hel"}`, + `{"type":"text-delta","id":"t0","text":"lo"}`, + ) + srv, _, _ := generateServer(t, 0, body) + client, _ := newTestClient(t, srv) + resp, _, err := client.ChatStream(t.Context(), "acc-1", chatReq()) + if err != nil { + t.Fatalf("ChatStream: %v", err) + } + defer resp.Body.Close() + + raw, readErr := io.ReadAll(resp.Body) + if readErr == nil { + t.Fatal("truncated stream must surface a read error") + } + // The partial answer was already on the wire before the cut; that is the + // case this fix is about (a pre-content failure can still fail over). + if !strings.Contains(string(raw), `"content":"Hel"`) { + t.Errorf("partial content must still reach the client: %q", raw) + } + var providerErr *providers.Error + if !asProviderError(readErr, &providerErr) || providerErr.Code != providers.CodeStreamTruncated { + t.Fatalf("stream truncation must carry %q, got %v", providers.CodeStreamTruncated, readErr) + } } func TestChatNonStreamErrorEvent(t *testing.T) { diff --git a/internal/providers/command/errors.go b/internal/providers/command/errors.go index c3abe9c02..0e25d1a03 100644 --- a/internal/providers/command/errors.go +++ b/internal/providers/command/errors.go @@ -152,3 +152,27 @@ func newProviderError(status int, body string) error { Message: classified.Message, } } + +// newStreamTruncatedError reports an upstream stream that ended without any +// terminal event (`finish-step` / `finish` / `error`). The account is healthy: +// the upstream answered, delivered events, and then closed. The distinct code +// lets the executor keep the account routable instead of cooling it down, which +// otherwise turns a single cut stream into a frozen pool (see +// executor.ClassifyError). +// +// detail carries the observed stream shape (event count, bytes, last event type, +// whether real content arrived). It never carries prompt or completion text, so +// it is safe to surface in the request log. +func newStreamTruncatedError(detail string) error { + message := "command code stream ended before a terminal event" + if strings.TrimSpace(detail) != "" { + message += " (" + redactSecrets(strings.TrimSpace(detail)) + ")" + } + return &providers.Error{ + Kind: accounts.KindUnavailable, + Status: 502, + Code: providers.CodeStreamTruncated, + Type: "api_error", + Message: message, + } +} diff --git a/internal/providers/command/rewrite.go b/internal/providers/command/rewrite.go index d25b9146b..0e4e895da 100644 --- a/internal/providers/command/rewrite.go +++ b/internal/providers/command/rewrite.go @@ -26,7 +26,7 @@ func rewriteStream(upstream *http.Response, model string) *http.Response { toolIndex: map[string]int{}, deltasSeen: map[string]bool{}, } - err := streamEvents(upstream.Body, writer.handle) + err := streamEventsObserved(upstream.Body, &writer.stats, writer.handle) if err != nil { _ = pw.CloseWithError(err) return @@ -60,6 +60,7 @@ type sseWriter struct { toolIndex map[string]int deltasSeen map[string]bool usage map[string]any + stats streamStats } func (w *sseWriter) handle(event generateEvent) error { @@ -207,7 +208,11 @@ func (w *sseWriter) writeChunk(delta map[string]any, finish string, usage any) e func (w *sseWriter) finish() error { if !w.sawTerminalEvent { - return newProviderError(502, "command code stream ended before a terminal event") + // Nothing else on this stream says the answer completed, and the bytes + // already relayed cannot be recalled. Report the cut instead of + // synthesizing a normal stop, which strict clients would read as a + // finished answer. + return newStreamTruncatedError(w.stats.describe()) } if !w.roleSent { w.roleSent = true diff --git a/internal/providers/command/wire.go b/internal/providers/command/wire.go index b28f80f2c..d6ed5b21f 100644 --- a/internal/providers/command/wire.go +++ b/internal/providers/command/wire.go @@ -3,6 +3,7 @@ package command import ( "bufio" "encoding/json" + "fmt" "io" "strings" ) @@ -86,9 +87,57 @@ func (e generateEvent) usage() *eventUsage { return e.TotalUsage } +// streamStats is what the reader saw on the wire. A stream that ends without a +// terminal event is otherwise indistinguishable from a clean close, and the only +// trace an operator gets is a constant error string; recording the shape lets a +// later report say whether the upstream cut the answer mid-sentence or aborted +// before producing anything. +type streamStats struct { + events int + lastType string + contentSeen bool + bytesRead int +} + +// contentEventTypes are the event types that carry real output. `start` and +// `start-step` are excluded on purpose: an upstream that emits only the envelope +// and then closes produced nothing the caller can use. +var contentEventTypes = map[string]bool{ + "reasoning-delta": true, + "text-delta": true, + "tool-input-start": true, + "tool-input-delta": true, + "tool-input-end": true, + "tool-call": true, +} + +func (s *streamStats) observe(event generateEvent) { + s.events++ + s.lastType = event.Type + if contentEventTypes[event.Type] { + s.contentSeen = true + } +} + +// describe renders the observed shape for the truncation error. It never +// includes prompt or completion content, only counters and event type names. +func (s *streamStats) describe() string { + last := s.lastType + if last == "" { + last = "none" + } + return fmt.Sprintf("%d events, %d bytes, last type %q, content=%t", + s.events, s.bytesRead, last, s.contentSeen) +} + // streamEvents parses the NDJSON body line by line. Blank lines are skipped; // malformed lines are tolerated (a stray keep-alive must not kill the stream). func streamEvents(r io.Reader, onEvent func(generateEvent) error) error { + return streamEventsObserved(r, nil, onEvent) +} + +// streamEventsObserved is streamEvents with wire accounting for streamStats. +func streamEventsObserved(r io.Reader, stats *streamStats, onEvent func(generateEvent) error) error { reader := bufio.NewReaderSize(r, 64*1024) for { line, err := readLine(reader) @@ -97,6 +146,13 @@ func streamEvents(r io.Reader, onEvent func(generateEvent) error) error { if trimmed != "" { var event generateEvent if json.Unmarshal([]byte(trimmed), &event) == nil && event.Type != "" { + if stats != nil { + stats.events++ + stats.lastType = event.Type + if contentEventTypes[event.Type] { + stats.contentSeen = true + } + } if cbErr := onEvent(event); cbErr != nil { return cbErr } diff --git a/internal/providers/tlserr.go b/internal/providers/tlserr.go index 0e2544e65..7758dc597 100644 --- a/internal/providers/tlserr.go +++ b/internal/providers/tlserr.go @@ -58,3 +58,9 @@ const CodeClientVersionTooLow = "client_version_too_low" // CodeUpstreamImageConversionTimeout marks a provider image-conversion TTL // (Qoder hub v1.8.0). Same-account bounded retry only; no account rotation. const CodeUpstreamImageConversionTimeout = "upstream_image_conversion_timeout" + +// CodeStreamTruncated marks an upstream stream that delivered content and then +// ended without any protocol terminal event. The account is healthy — the +// upstream or the transport cut the connection — so the executor never cools it +// down; cooling it turns one cut stream into a frozen account pool. +const CodeStreamTruncated = "upstream_stream_truncated" From e2ea1ae908a4cffda747193a33e1bd90ebdc068e Mon Sep 17 00:00:00 2001 From: BrianBoy Date: Sat, 5 Dec 2026 10:49:55 +0800 Subject: [PATCH 2/2] fix(command): address stream-truncation review feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wire.go: count raw bytes via a counting reader so streamStats.bytesRead is actually accumulated (was always 0); call stats.observe() instead of the duplicated inline logic; drop the unused streamEvents wrapper. - chat_test.go: make the no-content-echo assertion real (check for the actual streamed fragment) and assert bytesRead is non-zero. - classify_test.go: restore the two comment lines above TestClassifyErrorUpstreamEmptyNoCooldown that were unrelated to this change. - Align the code's actual scope (any stream without a terminal event, content or not) across tlserr.go, errors.go, and the changelog. - executor/error.go: correct the cooldown-floor comment — nextBackoffCooldown's 30s floor applies from the third consecutive same-kind failure, not to any positive cooldown. --- .../unreleased/command-stream-truncation.md | 4 +- internal/executor/classify_test.go | 2 + internal/executor/error.go | 16 ++++--- internal/providers/command/chat_test.go | 10 +++- internal/providers/command/errors.go | 11 +++-- internal/providers/command/wire.go | 47 +++++++++++++------ internal/providers/tlserr.go | 9 ++-- 7 files changed, 64 insertions(+), 35 deletions(-) diff --git a/changelog/unreleased/command-stream-truncation.md b/changelog/unreleased/command-stream-truncation.md index 1a4fefefc..09b898853 100644 --- a/changelog/unreleased/command-stream-truncation.md +++ b/changelog/unreleased/command-stream-truncation.md @@ -1,9 +1,9 @@ ### English -- A Command Code stream that the upstream cuts after delivering content no longer cools the account down. The cut is reported as `upstream_stream_truncated` and the account stays routable, so one truncated answer no longer turns into a burst of `all accounts are cooling down` failures on a single-account route. +- A Command Code stream that the upstream ends without a terminal event (`finish-step` / `finish` / `error`) — whether content was already delivered or not — no longer cools the account down. The cut is reported as `upstream_stream_truncated` and the account stays routable, so one truncated answer no longer turns into a burst of `all accounts are cooling down` failures on a single-account route. - The Command Code truncation error now reports the shape of the stream it saw (event count, bytes, last event type, whether real content arrived) instead of a constant string, so a cut answer can be told apart from an upstream that aborted before producing anything. Prompt and completion text are never included. ### 中文 -- 上游已下发内容后被切断的 Command Code 流不再冷却账号。该类中断以 `upstream_stream_truncated` 上报,账号保持可路由,单账号路由上的一次截断不会再演变成一串 `all accounts are cooling down` 失败。 +- 上游未见终态事件(`finish-step` / `finish` / `error`)就结束的 Command Code 流——无论是否已下发内容——不再冷却账号。该类中断以 `upstream_stream_truncated` 上报,账号保持可路由,单账号路由上的一次截断不会再演变成一串 `all accounts are cooling down` 失败。 - Command Code 的截断错误现在会带上实际观测到的流形态(事件数、字节数、最后一个事件类型、是否出现过真实内容),而不是固定文案,因此可以把「答到一半被切」和「上游什么都没产出就中断」区分开。提示词与生成内容不会写入该信息。 diff --git a/internal/executor/classify_test.go b/internal/executor/classify_test.go index 233688496..8528b6e20 100644 --- a/internal/executor/classify_test.go +++ b/internal/executor/classify_test.go @@ -352,6 +352,8 @@ func TestObserveStreamFailureIgnoresCancellation(test *testing.T) { } func TestClassifyErrorUpstreamEmptyNoCooldown(t *testing.T) { + // A heartbeat-only empty upstream stream says nothing about the account's + // health: fail over, but never cool the account down. err := ClassifyError(&providers.Error{ Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, diff --git a/internal/executor/error.go b/internal/executor/error.go index e55a20362..ce2e704f9 100644 --- a/internal/executor/error.go +++ b/internal/executor/error.go @@ -181,15 +181,17 @@ func ClassifyError(err error) Classified { classified.Cooldown = 0 } if providerErr.Code == providers.CodeStreamTruncated { - // The upstream answered 200, delivered content, and then ended the - // stream without a protocol terminal event. Same reasoning as + // The upstream answered 200 and then ended the stream without a + // protocol terminal event (content delivered or not). Same reasoning as // upstream_empty: the cut is on the upstream or transport side, not a // credential, quota, or rate-limit problem, so the account stays - // routable. Cooldown must be exactly 0: any positive value is lifted to - // the 30s backoff floor (see nextBackoffCooldown), which turns a single - // cut stream into a frozen pool. The abort is logged as a failure by the - // gateway, so the operator still sees it — no cooldown is needed to make - // it visible. + // routable. Cooldown must be exactly 0 here: repeated unavailable + // failures of the same kind climb nextBackoffCooldown's exponential + // ladder, whose 30s floor kicks in from the third consecutive failure — + // which is exactly how one cut stream turned into a burst of "all + // accounts are cooling down" on a single-account route. The abort is + // logged as a failure by the gateway, so the operator still sees it — + // no cooldown is needed to make it visible. classified.Failover = true classified.Cooldown = 0 classified.RetryAfter = 0 diff --git a/internal/providers/command/chat_test.go b/internal/providers/command/chat_test.go index a814acef9..33ff54b0d 100644 --- a/internal/providers/command/chat_test.go +++ b/internal/providers/command/chat_test.go @@ -166,10 +166,16 @@ func TestChatNonStreamTruncationReportsObservedShape(t *testing.T) { t.Errorf("truncation detail missing %q in %q", want, message) } } - // The account is healthy; the report must not carry the prompt wording. - if strings.Contains(message, "partial") { + // The streamed text must never be echoed back in the error, even as a + // fragment: the message carries counters and event type names only. + if strings.Contains(message, "Hel") { t.Errorf("error must not echo streamed content: %q", message) } + // Byte accounting must reflect what the reader consumed on the wire; a + // zero here means the counting reader was never wired in. + if !strings.Contains(message, " bytes, ") || strings.Contains(message, "0 bytes") { + t.Errorf("bytesRead must be non-zero after reading events: %q", message) + } } // TestChatStreamTruncationSurfacesCode covers the streaming path: the gateway diff --git a/internal/providers/command/errors.go b/internal/providers/command/errors.go index 0e25d1a03..d8c25dd8b 100644 --- a/internal/providers/command/errors.go +++ b/internal/providers/command/errors.go @@ -154,11 +154,12 @@ func newProviderError(status int, body string) error { } // newStreamTruncatedError reports an upstream stream that ended without any -// terminal event (`finish-step` / `finish` / `error`). The account is healthy: -// the upstream answered, delivered events, and then closed. The distinct code -// lets the executor keep the account routable instead of cooling it down, which -// otherwise turns a single cut stream into a frozen pool (see -// executor.ClassifyError). +// terminal event (`finish-step` / `finish` / `error`) — whether it had already +// delivered content or closed after only envelope events. The account is +// healthy either way: the upstream answered 200 and then closed the stream on +// its side. The distinct code lets the executor keep the account routable +// instead of cooling it down, which otherwise turns a single cut stream into a +// frozen pool (see executor.ClassifyError). // // detail carries the observed stream shape (event count, bytes, last event type, // whether real content arrived). It never carries prompt or completion text, so diff --git a/internal/providers/command/wire.go b/internal/providers/command/wire.go index d6ed5b21f..dfa1d746c 100644 --- a/internal/providers/command/wire.go +++ b/internal/providers/command/wire.go @@ -90,8 +90,9 @@ func (e generateEvent) usage() *eventUsage { // streamStats is what the reader saw on the wire. A stream that ends without a // terminal event is otherwise indistinguishable from a clean close, and the only // trace an operator gets is a constant error string; recording the shape lets a -// later report say whether the upstream cut the answer mid-sentence or aborted -// before producing anything. +// later report say whether the upstream cut the answer mid-sentence, aborted +// before producing anything, or never sent a single event. It applies to every +// stream that closes without a terminal event, content or not. type streamStats struct { events int lastType string @@ -119,6 +120,25 @@ func (s *streamStats) observe(event generateEvent) { } } +// countingReader counts raw bytes the stream reader consumed, so describe() +// can report how much the upstream actually sent before it cut the stream. +type countingReader struct { + r io.Reader + n int64 + onBytes func(int64) +} + +func (c *countingReader) Read(p []byte) (int, error) { + n, err := c.r.Read(p) + if n > 0 { + c.n += int64(n) + if c.onBytes != nil { + c.onBytes(c.n) + } + } + return n, err +} + // describe renders the observed shape for the truncation error. It never // includes prompt or completion content, only counters and event type names. func (s *streamStats) describe() string { @@ -130,15 +150,16 @@ func (s *streamStats) describe() string { s.events, s.bytesRead, last, s.contentSeen) } -// streamEvents parses the NDJSON body line by line. Blank lines are skipped; -// malformed lines are tolerated (a stray keep-alive must not kill the stream). -func streamEvents(r io.Reader, onEvent func(generateEvent) error) error { - return streamEventsObserved(r, nil, onEvent) -} - -// streamEventsObserved is streamEvents with wire accounting for streamStats. +// streamEventsObserved parses the NDJSON body line by line. Blank lines are +// skipped; malformed lines are tolerated (a stray keep-alive must not kill the +// stream). Every well-formed event is recorded in stats so a later truncation +// error can describe the observed stream shape. func streamEventsObserved(r io.Reader, stats *streamStats, onEvent func(generateEvent) error) error { - reader := bufio.NewReaderSize(r, 64*1024) + source := r + if stats != nil { + source = &countingReader{r: r, onBytes: func(n int64) { stats.bytesRead = int(n) }} + } + reader := bufio.NewReaderSize(source, 64*1024) for { line, err := readLine(reader) if len(line) > 0 { @@ -147,11 +168,7 @@ func streamEventsObserved(r io.Reader, stats *streamStats, onEvent func(generate var event generateEvent if json.Unmarshal([]byte(trimmed), &event) == nil && event.Type != "" { if stats != nil { - stats.events++ - stats.lastType = event.Type - if contentEventTypes[event.Type] { - stats.contentSeen = true - } + stats.observe(event) } if cbErr := onEvent(event); cbErr != nil { return cbErr diff --git a/internal/providers/tlserr.go b/internal/providers/tlserr.go index 7758dc597..f8b0df6de 100644 --- a/internal/providers/tlserr.go +++ b/internal/providers/tlserr.go @@ -59,8 +59,9 @@ const CodeClientVersionTooLow = "client_version_too_low" // (Qoder hub v1.8.0). Same-account bounded retry only; no account rotation. const CodeUpstreamImageConversionTimeout = "upstream_image_conversion_timeout" -// CodeStreamTruncated marks an upstream stream that delivered content and then -// ended without any protocol terminal event. The account is healthy — the -// upstream or the transport cut the connection — so the executor never cools it -// down; cooling it turns one cut stream into a frozen account pool. +// CodeStreamTruncated marks an upstream stream that ended without any protocol +// terminal event (`finish-step` / `finish` / `error`) — content delivered or +// not. The account is healthy: the upstream or the transport closed the +// connection on its side, so the executor never cools it down; cooling it turns +// one cut stream into a frozen account pool. const CodeStreamTruncated = "upstream_stream_truncated"