Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog/unreleased/command-stream-truncation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

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

### 中文

- 上游未见终态事件(`finish-step` / `finish` / `error`)就结束的 Command Code 流——无论是否已下发内容——不再冷却账号。该类中断以 `upstream_stream_truncated` 上报,账号保持可路由,单账号路由上的一次截断不会再演变成一串 `all accounts are cooling down` 失败。
- Command Code 的截断错误现在会带上实际观测到的流形态(事件数、字节数、最后一个事件类型、是否出现过真实内容),而不是固定文案,因此可以把「答到一半被切」和「上游什么都没产出就中断」区分开。提示词与生成内容不会写入该信息。
78 changes: 78 additions & 0 deletions internal/executor/classify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,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
Expand Down
16 changes: 16 additions & 0 deletions internal/executor/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,22 @@ func ClassifyError(err error) Classified {
classified.Failover = true
classified.Cooldown = 0
}
if providerErr.Code == providers.CodeStreamTruncated {
// 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 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
}
switch classified.Kind {
case accounts.KindRateLimit:
switch {
Expand Down
5 changes: 3 additions & 2 deletions internal/providers/command/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ type aggregate struct {
finishReason string
sawTerminalEvent bool
sawError error
stats streamStats
}

func newAggregate() *aggregate {
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}
Expand Down
68 changes: 68 additions & 0 deletions internal/providers/command/chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,74 @@ 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 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
// 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) {
Expand Down
25 changes: 25 additions & 0 deletions internal/providers/command/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,28 @@ 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`) — 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
// 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,
}
}
9 changes: 7 additions & 2 deletions internal/providers/command/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
81 changes: 77 additions & 4 deletions internal/providers/command/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package command
import (
"bufio"
"encoding/json"
"fmt"
"io"
"strings"
)
Expand Down Expand Up @@ -86,17 +87,89 @@ func (e generateEvent) usage() *eventUsage {
return e.TotalUsage
}

// 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 {
reader := bufio.NewReaderSize(r, 64*1024)
// 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, 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
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
}
}

// 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 {
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)
}

// 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 {
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 {
trimmed := strings.TrimSpace(string(line))
if trimmed != "" {
var event generateEvent
if json.Unmarshal([]byte(trimmed), &event) == nil && event.Type != "" {
if stats != nil {
stats.observe(event)
}
if cbErr := onEvent(event); cbErr != nil {
return cbErr
}
Expand Down
7 changes: 7 additions & 0 deletions internal/providers/tlserr.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,10 @@ 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 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"
Loading