codex: each end of the Codex app's app-server says why, and list flaps are guarded (#4550)

70d50254c (v0.1.2387) took the model list out of the route the Codex
app's app-server is ended on. The effort the app saves on each pick
went into the catalog, the next sync rewrote it, and the route's hash
of the catalog changed, so the app-server was ended every few minutes
and the ChatGPT app read that as a crash (goto_nozomi on Discord,
ggbdpq on #4550). This adds two things on top of that.

- codexAppStep logs each end with what made the app-server stale:
  "codex: ended the Codex app's app-server [pid] for the app to start
  another: <why>". The reason is the ChatGPT account switched, the
  route changed, or the used-up takeover. Before this a successful end
  logged nothing, so a reported crash couldn't be put down to magpie or
  to the app (ggbdpq asked for it on #4550).
- TestCodexAppRouteKeepsThroughListFlaps runs in a sandbox HOME
  through SyncCatalog. A relay's list drops a model and has it back,
  the catalog is re-ranked in another order with other descriptions,
  and the catalog is caught half-written. Each must leave the route as
  it was. 70d50254c's tests cover an effort pick and a rename.

Product call, as 70d50254c made it: a list change alone never restarts
the app-server, not even once Codex has been idle for a while. The
restart is what crashes ChatGPT when an MCP server is slow, and idle
time doesn't make it safe. The new list is read at the app's next
launch, or on the Agents row's Restart (StaleCopies). Where requests
go (model_provider, openai_base_url, the magpie table's base_url,
requires_openai_auth, the used-up takeover) still restarts it, as
TestCodexAppRouteFollowsConnectAndDisconnect and
TestCodexAppRouteFollowsOpenAIAuth hold.

Run (mote):
- go vet, GOOS=linux go vet and GOOS=windows go vet of ./internal/agent
  and ./internal/provider: clean.
- go test -count=1 -timeout 45m ./internal/agent ./internal/provider on
  e484b1e93: ok. Rebased onto 5cc2eea2f (dsh in internal/agent), then
  go vet and go test -count=1 -timeout 45m ./internal/agent again, and
  -run CodexApp ./internal/provider: ok.
- gofmt -l on both packages: nothing.

Broken by hand:
- TestCodexAppRouteKeepsThroughListFlaps at 70d50254c^ (the route
  still hashed the catalog) is red three ways: a model dropped (:119),
  another order (:141) and a half-written catalog (:147) each changed
  the route.
- With the used-up reason taken out of codexAppStep,
  TestCodexAppEndSaysWhy is red ("... start another: where Codex's
  config sends it changed", want "used up").

Not tried:
- The real ChatGPT/Codex app. Nothing here changes when the app-server
  is ended, only what is logged.
- The whole ./... suite and the GUI suite. Neither package touches the
  GUI.
- Whether goto_nozomi's crashes stop on v0.1.2387. #4550 stays open
  for them to say, with the new log line asked for if any crash is
  left.
This commit is contained in:
yetone
2026-10-31 19:55:12 +08:00
parent 1dc22a37c5
commit d6e1116380
4 changed files with 145 additions and 2 deletions
File diff suppressed because one or more lines are too long
+77
View File
@@ -1,10 +1,14 @@
package agent
import (
"encoding/json"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// The route the Codex app's app-server is restarted on (codex_app_server.go)
@@ -70,3 +74,76 @@ func TestCodexAppRouteFollowsOpenAIAuth(t *testing.T) {
t.Fatalf("requires_openai_auth taken out left the route as it was:\n%s", read())
}
}
// #4550: the Codex app's app-server was restarted three times in 20
// minutes with the user doing nothing, and a slow MCP server took
// ChatGPT down with each. What magpie writes to Codex's catalog changes
// with no change of the user's: a list that fails to fetch drops its
// models and has them back at the next fetch, the order is re-ranked by
// the models Codex used last, descriptions and windows follow the
// vendor's list. None of that is where Codex sends, so none of it is the
// route, which restarts the app-server at once; and a catalog that can't
// be read now is no change either.
func TestCodexAppRouteKeepsThroughListFlaps(t *testing.T) {
home := syncHome(t)
codexCat := filepath.Join(home, ".codex", "magpie-models.json")
writeFile(t, filepath.Join(home, ".codex", "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n")
writeFile(t, codexCat, `{"models":[]}`)
save := func(models ...string) {
t.Helper()
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: models}); err != nil {
t.Fatal(err)
}
SyncCatalog()
}
route := func() string {
t.Helper()
r, _, known := codexAppRoute()
if !known {
t.Fatal("route not known")
}
return r
}
save("glm-4.6", "glm-4.5")
full := readFile(codexCat)
if !strings.Contains(full, "glm-4.5") {
t.Fatalf("catalog:\n%s", full)
}
before := route()
// the list fetched while the vendor failed: one model left
save("glm-4.6")
if strings.Contains(readFile(codexCat), "glm-4.5") {
t.Fatalf("catalog still lists the dropped model:\n%s", readFile(codexCat))
}
if r := route(); r != before {
t.Errorf("a model dropped from the list changed the route:\n%s\nto\n%s", before, r)
}
// and back at the next fetch
save("glm-4.6", "glm-4.5")
if r := route(); r != before {
t.Errorf("the model back in the list changed the route:\n%s\nto\n%s", before, r)
}
// the same models in another order, as usage re-ranks them, with
// other descriptions
var cat map[string][]map[string]any
if err := json.Unmarshal([]byte(readFile(codexCat)), &cat); err != nil {
t.Fatal(err)
}
ms := cat["models"]
slices.Reverse(ms)
for i, m := range ms {
m["priority"] = i + 1
m["description"] = "fetched again"
}
b, _ := json.Marshal(cat)
writeFile(t, codexCat, string(b))
if r := route(); r != before {
t.Errorf("the list in another order changed the route:\n%s\nto\n%s", before, r)
}
// half a file, as another writer's would be mid-write: not known,
// never a change
writeFile(t, codexCat, `{"models":[{"slug":"glm`)
if r := route(); r != before {
t.Errorf("a catalog that can't be read changed the route:\n%s\nto\n%s", before, r)
}
}
+15
View File
@@ -270,6 +270,10 @@ var codexApp struct {
// one has to start (codexAppBackWait after the last end)
ended map[int]bool
backBy time.Time
// why: what made the app-servers in stale stale, said in the log line
// when they are ended, so a crash a user reports can be put down to
// an account switch, a route change or a used-up account (#4550)
why string
}
// CodexAppStuck is whether a Codex app is left on the provider it started
@@ -377,6 +381,14 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
return nil
}
c.Lock()
switch {
case c.switched:
c.why = "Codex's ChatGPT account was switched"
case !c.seen:
c.why = "Codex's account is used up, so magpie serves it"
default:
c.why = "where Codex's config sends it changed"
}
c.seen, c.route, c.switched = true, route, false
c.stale, c.stuck = map[int]int{}, false
for _, p := range pids {
@@ -483,6 +495,9 @@ func codexAppStep(ctx context.Context, now time.Time, busy func() (int, time.Tim
}
c.ended[p], c.backBy = true, now.Add(codexAppBackWait)
}
if len(ended) > 0 {
log.Printf("codex: ended the Codex app's app-server %v for the app to start another: %s", ended, c.why)
}
return ended
}
+52 -1
View File
@@ -2,13 +2,16 @@ package provider
import (
"bufio"
"bytes"
"context"
"errors"
"log"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"testing"
"time"
@@ -43,7 +46,7 @@ func stubCodexApp(t *testing.T) *codexAppStub {
reset := func() {
codexApp.Lock()
codexApp.seen, codexApp.route, codexApp.stale, codexApp.stuck, codexApp.switched = false, "", nil, false, false
codexApp.ended, codexApp.backBy, codexApp.spent = nil, time.Time{}, false
codexApp.ended, codexApp.backBy, codexApp.spent, codexApp.why = nil, time.Time{}, false, ""
codexApp.Unlock()
}
t.Cleanup(func() {
@@ -176,6 +179,54 @@ func TestCodexAppServerRestartedOnDisconnect(t *testing.T) {
}
}
// Each end of the Codex app's app-server is logged with what made it
// stale. The ChatGPT app can read the end as a crash (#4550), and the log
// is what tells a used-up takeover, a route change and an account switch
// apart in a user's report.
func TestCodexAppEndSaysWhy(t *testing.T) {
signIn(t)
var buf bytes.Buffer
log.SetOutput(&buf)
t.Cleanup(func() { log.SetOutput(os.Stderr) })
now := time.Now()
idle := func() (int, time.Time) { return 0, now.Add(-time.Minute) }
step := func() []int { return codexAppStep(context.Background(), now, idle) }
said := func(want string) {
t.Helper()
got := buf.String()
buf.Reset()
if !strings.Contains(got, "ended the Codex app's app-server") || !strings.Contains(got, want) {
t.Fatalf("the log says %q, want the end and %q", got, want)
}
}
s := stubCodexApp(t)
s.running, s.on = []int{60}, true
if got := step(); !slices.Equal(got, []int{60}) {
t.Fatalf("first look on magpie: ended %v", got)
}
said("used up")
s.on = false
s.route = "openai_base_url="
if got := step(); !slices.Equal(got, []int{100}) {
t.Fatalf("the route changed: ended %v", got)
}
said("where Codex's config sends it changed")
codexApp.Lock()
codexApp.switched = true
codexApp.Unlock()
if got := step(); !slices.Equal(got, []int{101}) {
t.Fatalf("the account switched: ended %v", got)
}
said("account was switched")
if got := step(); got != nil {
t.Fatalf("nothing changed: ended %v", got)
}
if strings.Contains(buf.String(), "ended the Codex app's app-server") {
t.Fatalf("a look that ended nothing logged an end: %q", buf.String())
}
}
// A magpie started while it is Codex's provider for a used-up account
// restarts the app-servers it finds: they may have started before.
// Started with Codex on its account, it leaves them be.