#3734: with ~20 Codex app-servers starting together, Codex logged "failed to refresh available models: request timed out" 1,906 times a day, fell back to its default metadata for magpie's groups (no supports_search_tool), and inlined ~1,075 Apps tools: ~500K input tokens a turn. Each /backend-api/codex/models asked the ChatGPT backend on its own, and gave its ask up at codexModelsWait (3 s). Measured with a minimal gateway (gateway.New().Handler() alone, sandbox HOME, no providers), 20 lists at once with a real ChatGPT sign-in's headers, as app-servers ask: -4a33cf0a9: mean 2.24 s, max 3.01 s; the one at 3.01 s was handed an empty list (16 bytes), the backend asked 20 times. Again right after: mean 1.04 s, max 1.72 s, 20 asks again. - this change: mean 1.72 s, max 1.74 s, all 20 the full list (568,401 bytes) from one ask; again right after: max 0.01 s. Now the backend's list is kept for each sign-in (account id, the backend, Codex's version): within codexListFor (a minute) it is handed out again; past it, handed out at once while one ask goes; with none, the callers wait on the one ask for up to codexModelsWait as before, and the ask goes on, up to 30 s, for the callers after, where a backend slower than the wait had never got a list through. A 401 or 403 is still Codex's to see, and no list from before is handed out in its place. Each caller reads its own copy, since the windows, picks, V1 stamp and auto-review are written into the entries. What changes for users: the account's own models (not magpie's, whose part is built per call) are up to a minute behind the backend. Not changed: Codex's own 300 s cache and the build of magpie's part under provider.Hold (#746); no model_catalog_json floor is written. Tests (codex_models_shared_test.go): - 20 lists at once, the backend held: each answered with magpie's models and Codex's last list, the backend asked once; let go, its list reaches the next caller; fresh, five more ask it no more. On4a33cf0a9: asked 20 times, then 5 times more. - a backend always 600 ms against a 200 ms wait gets its list through: red on4a33cf0a9(none in 10 s), green here. - stale: three answers at once while the backend holds its second ask. - a refused sign-in after a list: the 401 is passed on. TestCodexModelListOnlyPicked and TestCodexNativeModelsTakeSetWindows change the backend's list between calls, so they forget the kept one there (forgetCodexLists, which also waits for every ask a test began). Run at this head (cm3734 worktree, base834935149): - go test -race -count=10 on the five list tests (the four new, BackendSlow): ok. - GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway/: ok; gofmt -l clean. - go test -timeout 45m ./internal/gateway/: ok (429s), run before TestCodexModelListBackendAlwaysSlow was added; that test then run alone and in the -race run above: ok. - Rebased onto80857a66c(13cca8109touched codexcat and Codex's models since): go test -run 'Codex|Fast' ./internal/gateway/: ok (42s).
236 lines
7.5 KiB
Go
236 lines
7.5 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// forgetCodexLists starts the test with no backend list kept, and ends it
|
|
// with every ask of the backend it started done.
|
|
func forgetCodexLists(t *testing.T) {
|
|
t.Helper()
|
|
reset := func() {
|
|
codexLists.asking.Wait()
|
|
codexLists.Lock()
|
|
codexLists.at = map[string]*codexListed{}
|
|
codexLists.Unlock()
|
|
}
|
|
reset()
|
|
t.Cleanup(reset)
|
|
}
|
|
|
|
// codexListAsk is one /models request as a Codex app-server sends it.
|
|
func codexListAsk(h http.Handler) (int, map[string]bool) {
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest("GET", CodexPath+"/models?client_version=0.164.0", nil)
|
|
req.Header.Set("Authorization", "Bearer chatgpt-token")
|
|
req.Header.Set("chatgpt-account-id", "acct-1")
|
|
h.ServeHTTP(rec, req)
|
|
var list struct {
|
|
Models []map[string]any `json:"models"`
|
|
}
|
|
json.Unmarshal(rec.Body.Bytes(), &list)
|
|
has := map[string]bool{}
|
|
for _, m := range list.Models {
|
|
s, _ := m["slug"].(string)
|
|
has[s] = true
|
|
}
|
|
return rec.Code, has
|
|
}
|
|
|
|
// Twenty Codex app-servers asking for the model list at once, with a
|
|
// ChatGPT backend slower than magpie waits for it (#3734): the backend is
|
|
// asked once for all of them, and its list, though it came after they
|
|
// were answered, is what the next ones get, at once, with magpie's
|
|
// models. Before, each asked on its own and gave up at codexModelsWait,
|
|
// so a slow backend's list never came through.
|
|
func TestCodexModelListSharedWhenSlow(t *testing.T) {
|
|
setup(t, provider.Chat, &fake{t: t})
|
|
var asks atomic.Int32
|
|
hold := make(chan struct{})
|
|
var holdOnce sync.Once
|
|
letGo := func() { holdOnce.Do(func() { close(hold) }) }
|
|
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
|
asks.Add(1)
|
|
select {
|
|
case <-hold:
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
w.Write([]byte(`{"models":[{"slug":"gpt-live","priority":1}]}`))
|
|
})
|
|
t.Cleanup(letGo)
|
|
home, _ := os.UserHomeDir()
|
|
os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
|
|
os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),
|
|
[]byte(`{"etag":"\"v1\"","models":[{"slug":"gpt-cached","priority":1,"base_instructions":"x"}]}`), 0o644)
|
|
was := codexModelsWait
|
|
codexModelsWait = 200 * time.Millisecond
|
|
t.Cleanup(func() { codexModelsWait = was })
|
|
h := New().Handler()
|
|
|
|
// the backend held: every one answered from Codex's last list, the
|
|
// backend asked once
|
|
var wg sync.WaitGroup
|
|
var bad atomic.Int32
|
|
for range 20 {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
if code, has := codexListAsk(h); code != 200 || !has["fake/m1"] || !has["gpt-cached"] {
|
|
bad.Add(1)
|
|
}
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
if bad.Load() != 0 {
|
|
t.Fatalf("%d of 20 answers without magpie's models or Codex's last list", bad.Load())
|
|
}
|
|
if n := asks.Load(); n != 1 {
|
|
t.Fatalf("the backend was asked %d times for 20 lists at once, want 1", n)
|
|
}
|
|
|
|
// it answers late; the ask was not given up with the first answers
|
|
letGo()
|
|
deadline := time.Now().Add(10 * time.Second)
|
|
for {
|
|
_, has := codexListAsk(h)
|
|
if has["gpt-live"] {
|
|
if !has["fake/m1"] || has["gpt-cached"] {
|
|
t.Fatalf("the backend's list without magpie's models, or beside the cached one: %v", has)
|
|
}
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the backend's list, answered after magpie stopped waiting, never reached a caller")
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
|
|
// fresh, it is handed out again without asking
|
|
n := asks.Load()
|
|
for range 5 {
|
|
if _, has := codexListAsk(h); !has["gpt-live"] || !has["fake/m1"] {
|
|
t.Fatalf("a fresh list not handed out again: %v", has)
|
|
}
|
|
}
|
|
if got := asks.Load() - n; got != 0 {
|
|
t.Fatalf("the backend was asked %d times more within codexListFor", got)
|
|
}
|
|
}
|
|
|
|
// Past codexListFor the last list is handed out at once while the backend
|
|
// is asked again, so a slow backend holds no answer once it has answered
|
|
// one; what it says then is what the callers after get.
|
|
func TestCodexModelListStaleAnsweredAtOnce(t *testing.T) {
|
|
setup(t, provider.Chat, &fake{t: t})
|
|
var asks atomic.Int32
|
|
slow := make(chan struct{})
|
|
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
|
if asks.Add(1) == 1 {
|
|
w.Write([]byte(`{"models":[{"slug":"gpt-old","priority":1}]}`))
|
|
return
|
|
}
|
|
select {
|
|
case <-slow:
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
w.Write([]byte(`{"models":[{"slug":"gpt-new","priority":1}]}`))
|
|
})
|
|
t.Cleanup(func() { close(slow) })
|
|
was, wasFor := codexModelsWait, codexListFor
|
|
codexModelsWait, codexListFor = 3*time.Second, time.Nanosecond
|
|
t.Cleanup(func() { codexModelsWait, codexListFor = was, wasFor })
|
|
h := New().Handler()
|
|
if _, has := codexListAsk(h); !has["gpt-old"] {
|
|
t.Fatalf("first list %v", has)
|
|
}
|
|
// stale at once; the backend now holds its answer. Each answer comes
|
|
// from the list it has, well inside the 3 s it would have waited
|
|
start := time.Now()
|
|
for range 3 {
|
|
if _, has := codexListAsk(h); !has["gpt-old"] || !has["fake/m1"] {
|
|
t.Fatalf("a stale list not handed out: %v", has)
|
|
}
|
|
}
|
|
if d := time.Since(start); d >= codexModelsWait {
|
|
t.Fatalf("three answers took %v with a list in hand: they waited on the backend", d)
|
|
}
|
|
// the ask they started reaches the backend, once
|
|
for deadline := time.Now().Add(10 * time.Second); asks.Load() < 2 && time.Now().Before(deadline); {
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
if n := asks.Load(); n != 2 {
|
|
t.Fatalf("the backend was asked %d times, want 2: once, then once again for the stale list", n)
|
|
}
|
|
}
|
|
|
|
// A sign-in the backend refuses is Codex's to see, and no list from
|
|
// before it is handed out in its place.
|
|
func TestCodexModelListRefusedSignInPassed(t *testing.T) {
|
|
setup(t, provider.Chat, &fake{t: t})
|
|
var asks atomic.Int32
|
|
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
|
if asks.Add(1) == 1 {
|
|
w.Write([]byte(`{"models":[{"slug":"gpt-old","priority":1}]}`))
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(401)
|
|
w.Write([]byte(`{"detail":"token expired"}`))
|
|
})
|
|
was := codexListFor
|
|
codexListFor = time.Nanosecond
|
|
t.Cleanup(func() { codexListFor = was })
|
|
h := New().Handler()
|
|
if code, has := codexListAsk(h); code != 200 || !has["gpt-old"] {
|
|
t.Fatalf("first list %d %v", code, has)
|
|
}
|
|
// stale: handed out while the backend is asked again, which refuses
|
|
codexListAsk(h)
|
|
codexLists.asking.Wait()
|
|
if code, _ := codexListAsk(h); code != 401 {
|
|
t.Fatalf("after the backend refused the sign-in: %d, want its 401", code)
|
|
}
|
|
}
|
|
|
|
// A backend that always answers after magpie stops waiting still gets its
|
|
// list to Codex: the ask goes on, and the next caller has it. Before,
|
|
// every ask was given up at codexModelsWait, so such a backend's list,
|
|
// and the version and tools its entries say, never came through (#3734).
|
|
func TestCodexModelListBackendAlwaysSlow(t *testing.T) {
|
|
setup(t, provider.Chat, &fake{t: t})
|
|
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
|
// three times what magpie waits, well inside codexListFetch
|
|
select {
|
|
case <-time.After(600 * time.Millisecond):
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
w.Write([]byte(`{"models":[{"slug":"gpt-live","priority":1}]}`))
|
|
})
|
|
was := codexModelsWait
|
|
codexModelsWait = 200 * time.Millisecond
|
|
t.Cleanup(func() { codexModelsWait = was })
|
|
h := New().Handler()
|
|
for deadline := time.Now().Add(10 * time.Second); ; {
|
|
if _, has := codexListAsk(h); has["gpt-live"] && has["fake/m1"] {
|
|
return
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("a backend slower than magpie waits never got its list through")
|
|
}
|
|
time.Sleep(50 * time.Millisecond)
|
|
}
|
|
}
|