Files
magpie/internal/gateway/search_queue_test.go
T
yetone 6f6b7d4077 gateway: a Codex request with web_search stays alive while its provider is queued, not cut at Codex's idle timeout (#2316, clxsh)
A request that offers web_search to a model that can't run it goes through
searchReply, which reads the provider's reply in rounds. That reader used
readSSE, so the provider's keepalives (": keepalive", response.in_progress)
were dropped, and relay waited for the first event past KStart before it
made the client's encoder. A provider queued for minutes sent the client
nothing but the holdWriter's comments, which Codex's idle timeout doesn't
count: it hung up at ~315s and asked again, losing its place in the queue.
The plain translated path has kept the client alive since #436.

Now askTranslated reads with readSSEAlive and, after keepaliveGap with
nothing else sent, hands its reader a KAlive event (nothing of the reply).
searchRounds passes it on without collecting it, the collector ignores it
(no reasoning block boundary moves), and relay takes it as the provider
being heard from: it begins the client's stream and sends the protocol's
own keepalive (response.in_progress, Anthropic's ping) when the client has
been quiet keepaliveGap. A provider that goes silent sends no KAlive, so
relayEvents' keepaliveLongest still ends the keepalives; an error before
any keepalive is still a status for the next account.

Test: clxsh's TestSearchQueueKeepsCodexAlive as filed (comments, progress,
cancel, silent). On the old code all four fail (pings=0 complete=false,
only comments reach the client); with the fix they pass, -count=3.

Run: go test -tags nogui ./internal/gateway -run
'Search|Keep|Alive|Relay|Zen|Draw|Probe|Held|Hold|Queue|Codex.*Stream|Translated'
ok (75s); gofmt -l clean; go vet -tags nogui ./internal/gateway on
darwin, linux, windows clean. Not tried against a real queued provider.

Full suite: SUITE_LINE
2026-10-15 23:08:01 +08:00

151 lines
5.8 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 := keepHeldAfter, agentQuietMost, watchEvery
keepHeldAfter, agentQuietMost, watchEvery = 10*time.Millisecond, 50*time.Millisecond, 5*time.Millisecond
t.Cleanup(func() { keepHeldAfter, agentQuietMost, watchEvery = held, quiet, watch })
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())
}
})
}
}