youyo.p on Discord (Windows, magpie 0.1.1609): Claude Code on
/v1/messages, translated to a custom provider's /v1/responses, was
canceled with 499 at ~357s and ~795s while the provider was still open.
Once the provider had begun its reply, a translated stream sent the
client something only when the provider did: the encoder's keepalive
went out on each upstream keepalive, and a provider silent mid-turn
(a long reasoning step sent whole at its end) sent nothing at all.
Now streamTranslated runs keepThroughSilence beside readSSEAlive: every
keepaliveEvery with the provider quiet, the client gets its own
protocol's keepalive through the encoder (Anthropic a ping, Responses
response.in_progress, Chat a comment, Gemini nothing), for up to
translatedQuietLongest (30 min: longer than upstreamHeaderWait's 10, long
enough for a reasoning turn sent whole), then nothing, so a provider
that never answers still ends. Writes from the reader and the ticker go
under one lock. Failover is unchanged: nothing is kept alive once a try
failed, was cut or relooped, and a held try's writes still go through
holdWriter.
Anthropic pings are spaced pingEvery (1 min) apart, comments in
between: Claude Code's 300s event watchdog takes at most 30 pings in a
row, and one ping per upstream keepalive spent them in minutes. Before
message_start the keepalive is a comment, as the SDKs' MessageStream
fails on any event before it.
Sibling: search.go's askTranslated, the other readSSEAlive caller, hands
on a KAlive from the same ticker under the same bound. The relays
(claude_subscription relay/relayEvents) keep keepaliveLongest (5 min)
and are unchanged, as is holdWriter's held comments.
Not changed: a provider that sends headers and then no byte at all is
waited out by notAnAPIReply's first-byte read under the held writer's
comments only, before any encoder exists; that path stays as it was.
A translated try held for failover (holdWriter) has two keepers: the
held writer's own comments, bounded by keepaliveLongest (5 min), and the
encoder's. Its comments bypass the encoder's writer, so for the first 5
minutes such a client can get two keepalives per keepaliveEvery. That is
harmless (comments and spaced pings) and left as is;
TestQuietKeptAliveOnlySoLong now sets both bounds and allows both
keepers' count.
Tests: TestTranslatedSilenceStillTimesOut is replaced by
TestTranslatedSilenceKeptAliveForABound (anthropic from responses,
responses from chat, chat from responses: the provider begins, then is
silent; it waits for 10 keepalives, not a duration, and checks they stop
after the bound, with room both ways). TestTranslatedStreamKeepsClientAlive
bounds pings by pingEvery; TestAnthropicKeepaliveBeforeStartIsAComment;
TestRelayKeepsClientAlive counts comments too; TestSearchQueueKeepsCodexAlive
sets the bound; TestQuietKeptAliveOnlySoLong sets both bounds
(red with the quiet bound removed). Prompts and headers sent upstream are unchanged.
Run at this head (rebased on origin/main 6ce0f14b9):
- go test ./internal/gateway -count=1 -timeout 45m: started before the push, its result is in the follow-up
(owner rule: ship a verified fix at once). Targeted at this head:
go test -race -run 'TestQuiet|Keepalive|KeepAlive|KeptAlive|TestTranslatedSilence|TestSearchQueue|TestRelay': ok
- go test -race on the keepalive tests: ok
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: ok
Broken by hand:
- the ticker never calling keep: the bound test red in all 3 (0, 1, 3 of 10)
- no quiet bound: red, 125/199/220 more after the first 10
- a ping on every keepalive: TestTranslatedStreamKeepsClientAlive red
(75 pings in 1.5s, want at most 20) and the encoder test red
- a ping before message_start: TestAnthropicKeepaliveBeforeStartIsAComment red
Not tried: a real Claude Code against a real silent provider, or
youyo.p's provider; Windows.
151 lines
5.9 KiB
Go
151 lines
5.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// #2316 (clxsh, their test as filed): Codex includes web_search even when
|
|
// it asks for no search. That selects searchReply: queue progress must survive translation before any content,
|
|
// including the fallback writer's initial hold. Release the fake queue only
|
|
// after the client receives progress, so content cannot hide a lost heartbeat.
|
|
func TestSearchQueueKeepsCodexAlive(t *testing.T) {
|
|
keepFast(t, 10*time.Millisecond, 20*time.Millisecond, 100*time.Millisecond)
|
|
held, quiet, watch, silent := keepHeldAfter, agentQuietMost, watchEvery, translatedQuietLongest
|
|
keepHeldAfter, agentQuietMost, watchEvery, translatedQuietLongest = 10*time.Millisecond, 50*time.Millisecond, 5*time.Millisecond, 40*time.Millisecond
|
|
t.Cleanup(func() { keepHeldAfter, agentQuietMost, watchEvery, translatedQuietLongest = held, quiet, watch, silent })
|
|
for _, mode := range []string{"comments", "progress", "cancel", "silent"} {
|
|
t.Run(mode, func(t *testing.T) {
|
|
fresh(t)
|
|
release, stopped := make(chan struct{}), make(chan struct{})
|
|
var once sync.Once
|
|
finish := func() { once.Do(func() { close(release) }) }
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
defer close(stopped)
|
|
var q struct{ Tools []struct{ Type, Name string } }
|
|
if err := json.NewDecoder(r.Body).Decode(&q); err != nil {
|
|
t.Error(err)
|
|
return
|
|
}
|
|
search, client := false, false
|
|
for _, tool := range q.Tools {
|
|
search = search || tool.Type == "function" && tool.Name == "web_search"
|
|
client = client || tool.Type == "function" && tool.Name == "get_value"
|
|
}
|
|
if !search || !client {
|
|
t.Error("search translation lost the search or client tool")
|
|
http.Error(w, "missing tools", 400)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, "data: "+`{"type":"response.created","response":{"id":"queued","model":"m1","status":"in_progress"}}`+"\n\n")
|
|
w.(http.Flusher).Flush()
|
|
tick := time.NewTicker(20 * time.Millisecond)
|
|
defer tick.Stop()
|
|
pings := 0
|
|
for {
|
|
select {
|
|
case <-r.Context().Done():
|
|
return
|
|
case <-tick.C:
|
|
if mode == "silent" && pings > 0 {
|
|
continue
|
|
}
|
|
pings++
|
|
if mode == "comments" {
|
|
io.WriteString(w, ": keepalive\n\n")
|
|
} else {
|
|
io.WriteString(w, "data: "+`{"type":"response.in_progress","response":{"id":"queued","status":"in_progress"}}`+"\n\n")
|
|
}
|
|
w.(http.Flusher).Flush()
|
|
case <-release:
|
|
io.WriteString(w, "data: "+`{"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_value","arguments":""}}`+"\n\n")
|
|
io.WriteString(w, "data: "+`{"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":"{}"}`+"\n\n")
|
|
io.WriteString(w, "data: "+`{"type":"response.completed","response":{"id":"queued","status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_value","arguments":"{}"}],"usage":{"input_tokens":10,"output_tokens":2}}}`+"\n\n")
|
|
w.(http.Flusher).Flush()
|
|
return
|
|
}
|
|
}
|
|
}))
|
|
defer up.Close()
|
|
defer finish()
|
|
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "fixture", Models: []string{"m1"}, Responses: up.URL + "/v1"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "searxng", URL: up.URL + "/unused-search"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
server := httptest.NewServer(New().Handler())
|
|
defer server.Close()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
req, _ := http.NewRequestWithContext(ctx, "POST", server.URL+CodexPath+"/responses", strings.NewReader(`{"model":"fake/m1","stream":true,"input":"Use get_value","tools":[{"type":"web_search"},{"type":"function","name":"get_value","parameters":{"type":"object","properties":{}}}]}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer magpie")
|
|
// The idle deadline is much longer than the simulated queue tick;
|
|
// comments cannot reset it. A hard cap also catches runaway pings.
|
|
hard := time.AfterFunc(5*time.Second, cancel)
|
|
defer hard.Stop()
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer res.Body.Close()
|
|
idle := time.AfterFunc(300*time.Millisecond, cancel)
|
|
defer idle.Stop()
|
|
var body strings.Builder
|
|
pings, completed := 0, false
|
|
sc := bufio.NewScanner(res.Body)
|
|
for sc.Scan() {
|
|
line := sc.Text()
|
|
body.WriteString(line + "\n")
|
|
if strings.HasPrefix(line, "data:") {
|
|
idle.Reset(300 * time.Millisecond)
|
|
}
|
|
if strings.Contains(line, `"type":"response.in_progress"`) {
|
|
pings++
|
|
if pings >= 3 {
|
|
if mode == "cancel" {
|
|
cancel()
|
|
}
|
|
if mode == "comments" || mode == "progress" {
|
|
finish()
|
|
}
|
|
}
|
|
}
|
|
if strings.Contains(line, `"type":"response.completed"`) {
|
|
completed = true
|
|
break
|
|
}
|
|
}
|
|
cancel()
|
|
select {
|
|
case <-stopped:
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("client cancellation did not close upstream")
|
|
}
|
|
if mode == "silent" {
|
|
if completed || pings == 0 || pings > 12 {
|
|
t.Fatalf("silent upstream covered indefinitely: pings=%d complete=%v", pings, completed)
|
|
}
|
|
} else if mode == "cancel" {
|
|
if pings < 3 || completed {
|
|
t.Fatalf("queue cancellation: pings=%d complete=%v", pings, completed)
|
|
}
|
|
} else if pings < 3 || !completed || !strings.Contains(body.String(), `"name":"get_value"`) || !strings.Contains(body.String(), `"call_id":"call_1"`) {
|
|
t.Fatalf("queue progress or native tool call lost: pings=%d complete=%v\n%s", pings, completed, body.String())
|
|
}
|
|
})
|
|
}
|
|
}
|