gateway: a Gemini OpenAI-compatible stream that lost its finish_reason is ended by usage, or cut

Linka (Discord #feedback): Gemini's OpenAI-compatible API sends a whole
function call (its thought signature, the usage) in one chunk and the
finish_reason in the next. When the upstream hung up between the two,
magpie relayed a stream that ended with neither, and Pi threw the
complete call away ("Stream ended without finish_reason") and asked the
whole 160k turn again. On a Chat upstream only a failed read was a cut,
so a clean EOF there went on as a stream with no end.

That API counts the usage only on the generation's last chunk(s): the
Vertex fixture (testdata/vertex_openai_thoughts.sse) has it only beside
finish_reason, Linka's frames have it on the call chunk and the finish
chunk, and Google's forum and third-party docs say the same; no Google
doc states it. So for a Chat upstream that is Gemini's (geminiCompat,
saysItsEnd) and ended without a finish_reason:
- its last chunk carried usage: the generation was done and only the
  finish_reason was lost. It is filled in (chatTail), "tool_calls" after
  a call and "stop" otherwise: relayed, as one chunk before [DONE]
  (written only if [DONE] hadn't gone); translated, as the reply's normal
  end (tool_use for Claude Code), streamed and unstreamed. Recorded ok.
- no usage at its end: the reply was cut, and the client gets "the reply
  ended before it was complete" (errEndedShort), as a Gemini stream's
  finishReason is told (#1643, #1644): the relay's error chunk, the
  translated stream's error, an unstreamed 502.
A failed read keeps its own "connection lost mid-reply". Other vendors'
Chat streams are unchanged.

Tests (gemini_compat_cut_test.go, Linka's frames): relayed, the call
with usage ends with finish_reason tool_calls then [DONE], text with
usage with stop, the call without usage with the error and no
finish_reason; a whole reply with or without [DONE] goes as it came
with one finish_reason; kimi-k3 with and without usage unchanged.
Translated: with usage one message_stop with stop_reason tool_use and
no error, streamed, and a 200 tool_use unstreamed; without usage one
error and no message_stop, and a 502 unstreamed.
Broken by hand, each red: the relay fill off (relay test: no
finish_reason), the streamed fill off (0 stops, 1 error), the
unstreamed fill off (502), usage ignored in chatTail.finish (every
no-usage case ended as whole, unstreamed 200).

Run: gofmt -l clean; GOOS=darwin/linux/windows go vet -tags nogui ./...
ok; go test -run 'TestGeminiCompat|EndedShort|TestStreamCut|
TestWellFormed|Sniff' ./internal/gateway ok.
Docs: gateway-routing.md says when the finish_reason is filled in.
Full suite: go test -tags nogui -timeout 45m ./... at base a61a6f954 + this, EXIT 1: 65 packages ok, internal/gateway red only in TestVisionWaitIsntTheDescribersTime (300ms describer limit under load, unrelated; passes -count=5 alone; filed #2444). Rebased onto 1a16fc0b5, internal/gateway whole: ok.
This commit is contained in:
yetone
2026-10-16 03:41:49 +08:00
parent db8b791797
commit a6f908ba58
5 changed files with 252 additions and 8 deletions
File diff suppressed because one or more lines are too long
+76 -1
View File
@@ -112,6 +112,73 @@ func geminiKin(actual provider.Protocol) bool {
return actual == provider.Gemini || actual == provider.CodeAssist
}
// saysItsEnd tells whether every whole reply of p in proto, serving model,
// says it ended, so a stream that stops short of that is a reply cut
// short: Anthropic's message_stop, Responses' response.completed, a
// Gemini candidate's finishReason (#1643, #1644), and a finish_reason from
// Gemini's OpenAI-compatible API (geminiCompat). That one sends a whole
// function call in one chunk and its finish_reason in the next; an
// upstream that hung up between the two ended the reply with no end, and
// a strict client (Pi: "Stream ended without finish_reason") threw the
// call away, while a lenient one took the turn as over (Linka on
// Discord). When the last chunk counted the reply's usage, which that API
// sends only once its generation is done, only the finish_reason was lost
// and it is filled in (chatTail); without it the cut is said as one.
// Other Chat APIs may end a whole reply with neither a finish_reason nor
// [DONE], so only a failed read is a cut there.
func saysItsEnd(p provider.Provider, proto provider.Protocol, model string) bool {
switch {
case proto == provider.Anthropic, proto == provider.Responses, geminiKin(proto):
return true
case proto == provider.Chat:
return geminiCompat(p.Host(), model)
}
return false
}
// chatTail follows a Chat stream's chunks for a Gemini OpenAI-compatible
// reply that ended without its finish_reason (saysItsEnd): whether its
// last chunk counted the usage and whether it made calls.
type chatTail struct{ usage, calls bool }
func (t *chatTail) see(data []byte) {
var v struct {
Choices []struct {
Delta struct {
ToolCalls []json.RawMessage `json:"tool_calls"`
} `json:"delta"`
} `json:"choices"`
Usage *cUsage `json:"usage"`
}
if json.Unmarshal(data, &v) != nil {
return // [DONE], or nothing to read
}
t.usage = v.Usage != nil && (v.Usage.PromptTokens > 0 || v.Usage.CompletionTokens > 0)
for _, c := range v.Choices {
t.calls = t.calls || len(c.Delta.ToolCalls) > 0
}
}
// finish is the finish_reason a reply that ended without one is given:
// Gemini's OpenAI-compatible API counts the usage only on the
// generation's last chunks, so a last chunk with it says the generation
// was done and only the chunk with its finish_reason was lost (Linka on
// Discord). Without it, "": the reply was cut.
func (t chatTail) finish() string {
switch {
case !t.usage:
return ""
case t.calls:
return "tool_calls"
}
return "stop"
}
// finishChunk is the Chat chunk that ends a reply with finish_reason fin.
func finishChunk(fin string) []byte {
return []byte(`{"choices":[{"delta":{},"finish_reason":"` + fin + `","index":0}],"object":"chat.completion.chunk"}`)
}
// groupTryKey marks a try of a routing group's member. A member whose
// stream breaks with an error mid-reply is failed as it used to be — the
// group answers the agent's retry with another of its members (#733) —
@@ -463,7 +530,9 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
attemptSee, held = t.event, t.release
}
ended := false // the upstream said its reply ended
var tail chatTail
serr = readSSEAlive(rd, func(_, data string) error {
tail.see([]byte(data))
st := upstreamStop([]byte(data))
u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st, Tier: upstreamTier([]byte(data))})
ended = ended || replyEnds(actual, data, st)
@@ -480,7 +549,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
serr = nil
}
if serr == nil && failed == "" && !ended && !relooped &&
(actual == provider.Anthropic || actual == provider.Responses || geminiKin(actual)) && r.Context().Err() == nil {
saysItsEnd(p, actual, model) && r.Context().Err() == nil {
// an Anthropic stream that just stopped — no
// stop_reason, no message_stop — or a Responses one
// with no response.completed is a reply cut short,
@@ -490,6 +559,12 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
// whole would say completed it never said. A Gemini
// one is told by its finishReason (geminiEnds, #1643)
serr = errEndedShort
if fin := tail.finish(); actual == provider.Chat && fin != "" {
// Gemini's OpenAI-compatible API lost only the
// finish_reason after its generation was done
u.add(Usage{Stop: fin})
serr = dec(string(finishChunk(fin)), attemptSee)
}
}
}
}
+28 -6
View File
@@ -4493,20 +4493,35 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
status, msg := gather.finish(client, p, sse, cut, sniff.failed)
return status, msg, true
}
if sse && r.Context().Err() == nil && !sniff.whole() {
// a Chat stream of Gemini's OpenAI-compatible API is whole only with
// its finish_reason, [DONE] or not (saysItsEnd)
unfinished := proto == provider.Chat && sniff.failed == "" && sniff.u.Stop == "" && saysItsEnd(p, proto, upstream)
if fin := sniff.tail.finish(); sse && unfinished && fin != "" && (rerr == nil || rerr == io.EOF) && r.Context().Err() == nil {
// only the finish_reason was lost, after the generation was done
// (chatTail): the client gets it, and the reply is whole
w.Write([]byte("data: " + string(finishChunk(fin)) + "\n\n"))
if !sniff.ended {
w.Write([]byte("data: [DONE]\n\n"))
}
if f != nil {
f.Flush()
}
sniff.u.Stop, unfinished = fin, false
}
if sse && r.Context().Err() == nil && (!sniff.whole() || unfinished) {
// the upstream died mid-reply, or ended it short of its last
// event: say so in the stream rather than end it as if whole,
// which a client reads as a reply cut off for no reason (#370:
// dsh's "stream ended before message_stop", not retried). A Chat
// stream may end without [DONE] and be whole, so only a read that
// failed counts there; a Gemini one ends on a candidate's
// finishReason (#1644).
// failed counts there, Gemini's own aside; a Gemini one ends on a
// candidate's finishReason (#1644).
var failed string
switch {
case rerr != nil && rerr != io.EOF:
failed = cutMidReply(p.Name, rerr)
case proto == provider.Anthropic || proto == provider.Responses || proto == provider.Gemini:
failed = p.Name + ": the reply ended before it was complete"
case proto == provider.Anthropic || proto == provider.Responses || proto == provider.Gemini || unfinished:
failed = p.Name + ": " + errEndedShort.Error()
}
if failed != "" {
w.Write(streamFailure(proto, failed))
@@ -5416,12 +5431,19 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
}
var col collector
ended := false // the upstream said its reply ended
var tail chatTail
see, held := written(zenSee(zen, col.add))
err = readSSE(rd, func(_, data string) error {
tail.see([]byte(data))
u.add(Usage{Upstream: upstreamOf([]byte(data)), Tier: upstreamTier([]byte(data))})
ended = ended || replyEnds(actual, data, upstreamStop([]byte(data)))
return dec(data, see)
})
if fin := tail.finish(); err == nil && !ended && actual == provider.Chat && fin != "" && saysItsEnd(p, actual, model) {
// Gemini's OpenAI-compatible API lost only the finish_reason
// after its generation was done (chatTail)
ended, err = true, dec(string(finishChunk(fin)), see)
}
held()
if err != nil {
// a partial answer is not an answer
@@ -5439,7 +5461,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
// the vendor failing
return writeVendorError(w, from, cmp.Or(col.errStatus, 502), p.Name+": "+said, col.errSaid), said
}
if col.err == "" && !ended && (actual == provider.Anthropic || actual == provider.Responses || geminiKin(actual)) && r.Context().Err() == nil {
if col.err == "" && !ended && saysItsEnd(p, actual, model) && r.Context().Err() == nil {
// an Anthropic stream that just stopped — no stop_reason, no
// message_stop — or a Responses one with no response.completed is
// a reply cut short, not a finished one, as a streaming client is
+144
View File
@@ -0,0 +1,144 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Gemini's OpenAI-compatible API, in Linka's frames (Discord): a whole
// function call, its thought signature and the usage in one chunk, then
// the finish_reason in the next.
const (
compatCall = `data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"extra_content":{"google":{"thought_signature":"c2ln"}},"function":{"arguments":"{\"code\":\"run()\"}","name":"codemode"},"id":"call_1","type":"function"}]},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}}` + "\n\n"
compatStop = `data: {"choices":[{"delta":{},"finish_reason":"stop","index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}}` + "\n\n"
compatDone = "data: [DONE]\n\n"
)
// compatServer serves reply as a Chat upstream on this machine, where a
// Gemini model's is taken to be Gemini's OpenAI-compatible API
// (geminiCompat), and asks it for model at path with body.
func compatServer(t *testing.T, model, reply, path, body string) (int, string) {
t.Helper()
fresh(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, reply)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{model}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
return post(t, path, strings.ReplaceAll(body, "MODEL", "up/"+model))
}
// compatBare is compatCall without the usage: the generation wasn't
// counted as done.
var compatBare = strings.Replace(compatCall, `,"usage":{"completion_tokens":1110,"prompt_tokens":2049,"total_tokens":165667}`, "", 1)
// The upstream hung up between the call and its finish_reason. Gemini's
// OpenAI-compatible API counts the usage only once the generation is
// done, so a call chunk carrying it lost only the finish_reason: the
// client relayed to gets it, "tool_calls", where Pi threw the call away
// as "Stream ended without finish_reason". Without the usage the reply
// was cut, and the client is told so, as a Gemini stream's is (#1644).
func TestGeminiCompatRelayEndedShort(t *testing.T) {
const ask = `{"model":"MODEL","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"hi"}]}`
const cut = `data: {"error":{"message":"UP: the reply ended before it was complete","type":"api_error"}}`
code, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/chat/completions", ask)
if code != 200 || !strings.Contains(body, `"codemode"`) || strings.Contains(body, "ended before") {
t.Fatalf("status %d: %s", code, body)
}
if !strings.Contains(body, `"finish_reason":"tool_calls"`) || !strings.HasSuffix(strings.TrimSpace(body), compatDone[:len(compatDone)-2]) {
t.Errorf("a done Gemini reply that lost its finish_reason didn't end with it: %s", body)
}
// text alone, done, ends with "stop"
text := `data: {"choices":[{"delta":{"role":"assistant","content":"hi"},"index":0}],"model":"models/gemini-4-argon","object":"chat.completion.chunk","usage":{"completion_tokens":1,"prompt_tokens":2049,"total_tokens":2050}}` + "\n\n"
if _, body := compatServer(t, "gemini-4-argon", text, "/v1/chat/completions", ask); !strings.Contains(body, `"finish_reason":"stop"`) || strings.Contains(body, "ended before") {
t.Errorf("done text: %s", body)
}
code, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/chat/completions", ask)
if code != 200 || !strings.Contains(body, `"codemode"`) {
t.Fatalf("status %d: %s", code, body)
}
if !strings.HasSuffix(strings.TrimSpace(body), cut) {
t.Errorf("a cut Gemini reply ended as if whole: %s", body)
}
if strings.Contains(body, `"finish_reason":"`) {
t.Errorf("a cut reply given a finish_reason: %s", body)
}
// whole, with [DONE] or without it, it goes as it came
for what, reply := range map[string]string{
"whole": compatCall + compatStop + compatDone,
"whole, no [DONE]": compatCall + compatStop,
} {
code, body := compatServer(t, "gemini-4-argon", reply, "/v1/chat/completions", ask)
if code != 200 || strings.Contains(body, "ended before") || strings.Count(body, `"finish_reason":"`) != 1 || !strings.Contains(body, `"finish_reason":"stop"`) {
t.Errorf("%s: %d %s", what, code, body)
}
}
// another vendor's Chat stream may end whole with neither: it goes as
// it came, as it did
for _, reply := range []string{compatCall, compatBare} {
other := strings.ReplaceAll(reply, "models/gemini-4-argon", "kimi-k3")
code, body = compatServer(t, "kimi-k3", other, "/v1/chat/completions", ask)
if code != 200 || strings.Contains(body, "ended before") || strings.Contains(body, `"finish_reason":"`) {
t.Errorf("another vendor's stream: %d %s", code, body)
}
}
}
// Translated, a call whose generation was done ends the turn with the
// call, for Claude Code to run; a cut one ends with the error, not with a
// turn that ended with the call never run.
func TestGeminiCompatTranslatedEndedShort(t *testing.T) {
const ask = `{"model":"MODEL","max_tokens":32000,"stream":true,"messages":[{"role":"user","content":"hi"}]}`
_, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/messages", ask)
if !strings.Contains(body, `"codemode"`) {
t.Fatalf("the call didn't reach the client: %s", body)
}
if _, stops, errs := messageStops(body); errs != 0 || stops != 1 || !strings.Contains(body, `"stop_reason":"tool_use"`) {
t.Errorf("a done Gemini call didn't end its turn as one (%d stops, %d errors): %s", stops, errs, body)
}
_, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/messages", ask)
if !strings.Contains(body, `"codemode"`) {
t.Fatalf("the call didn't reach the client: %s", body)
}
if _, stops, errs := messageStops(body); errs != 1 || stops != 0 {
t.Errorf("a cut Gemini reply ended as a turn (%d stops, %d errors): %s", stops, errs, body)
}
_, body = compatServer(t, "gemini-4-argon", compatCall+compatStop+compatDone, "/v1/messages", ask)
if _, stops, errs := messageStops(body); errs != 0 || stops != 1 {
t.Errorf("a whole Gemini reply (%d stops, %d errors): %s", stops, errs, body)
}
// another vendor's Chat stream ends as it did
other := strings.ReplaceAll(compatBare, "models/gemini-4-argon", "kimi-k3")
_, body = compatServer(t, "kimi-k3", other, "/v1/messages", ask)
if _, _, errs := messageStops(body); errs != 0 {
t.Errorf("another vendor's stream: %s", body)
}
// unstreamed: a done call is the answer, a cut reply a 502
unstreamed := strings.Replace(ask, `"stream":true`, `"stream":false`, 1)
code, body := compatServer(t, "gemini-4-argon", compatCall, "/v1/messages", unstreamed)
if code != 200 || !strings.Contains(body, `"tool_use"`) || !strings.Contains(body, `"stop_reason":"tool_use"`) {
t.Errorf("unstreamed done call: %d %s", code, body)
}
code, body = compatServer(t, "gemini-4-argon", compatBare, "/v1/messages", unstreamed)
if code != 502 || !strings.Contains(body, "ended before") {
t.Errorf("unstreamed cut: %d %s", code, body)
}
}
+3
View File
@@ -26,6 +26,8 @@ type usageSniffer struct {
// failed: what an explicit error event said; a terminal event can end
// the stream successfully or with a failure despite its HTTP 200.
failed string
// tail: what a Chat stream's chunks say of its end (chatTail)
tail chatTail
}
func newSniffer(proto provider.Protocol, contentType string) *usageSniffer {
@@ -161,6 +163,7 @@ func (s *usageSniffer) parse(b []byte) {
}
}
case provider.Chat:
s.tail.see(b)
var v struct {
ID string `json:"id"`
Error any `json:"error"`