gateway: Codex's memories after a model switch wait for the new turn, as titles do

cybercaius (Discord) asked whether Codex's side calls (title, thread
description, composer prediction, memory consolidation, auto-review)
still go to the model the conversation was switched away from, and
whether the first of each after a switch follows it as the title does
since 81a73c1c0.

Titles, descriptions and predictions already followed: untied ones wait
in codexLeads.sideOf for the next turn when the last is stale, and tied
ones (a forked prediction) are asked on the thread's model. The
auto-review runs inside its turn, on that turn's model ("session") or on
codex-auto-review/the set model, so it follows at once.

Memories did not. Codex starts them with every turn that has the user's
input (codex-rs app-server start_memories_startup_task), concurrently
with that turn. Extraction is tied to the conversation's thread, so
codexSessionOf took that thread's last model at once: the one before the
switch. Consolidation, on its own thread, took the key's last model
without waiting. With magpie as Codex's provider, codexMemoryStandIn read
the last turn per agent and key, which the racing turn hadn't written.

Fix, at the two places a memory call is routed:
- codexLeads.sideOf takes beside: a call started with a turn waits for
  the next turn even when tied (codexMemorySession); codexFollowTo uses
  it for memories, and reads CodexSideSet first so a model set in
  Codex's config never waits.
- rememberCodexTurn also records the turn in codexLeads, and
  codexMemoryStandIn reads codexLeads.sideOf(beside) before its last-turn
  record.
docs/subsystems/gateway-routing.md says so.

Tests (fake upstreams, a session switched from one relay to another):
TestCodexSideCallsBeforeTheFirstTurnFollowTheSwitch (title, description,
prediction, memory extraction, memory consolidation, each sent before
the first turn after the switch), TestCodexMemoryOfASwitchedConversation
FollowsTheSwitch (an ongoing conversation switched), and
TestCodexMemoryStandInFollowsTheSwitch (magpie as Codex's provider).

Run: go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., gofmt -l clean, go test -timeout 45m
./internal/gateway/... ok (424.7s), at the pushed head
rebased on 94a70f1a0.

Broken by hand: with the old codex_follow.go, codex_memory.go and
gateway.go, both memory subtests, the switched-conversation test and the
stand-in test fail (the old relay got 2 requests); title, description
and prediction pass on the old code, as they already followed. With
beside forced false for memories, the switched-conversation test fails.
With saw() dropped from rememberCodexTurn, the stand-in test fails.

Not tried: a real Codex app or account. The app's ambient_suggestions
calls are not routed by magpie (they go to ChatGPT) and are left alone.
A tied call that isn't started with a turn (a prediction on a known
thread) asked after a switch but before the new turn still takes the
thread's last model, by design: waiting there would add latency to every
prediction.

Reported by cybercaius on Discord.
This commit is contained in:
yetone
2026-10-27 08:37:47 +08:00
parent 94a70f1a0d
commit b7d5a97fec
5 changed files with 222 additions and 23 deletions
File diff suppressed because one or more lines are too long
+41 -19
View File
@@ -20,7 +20,8 @@ import (
// account rather than where the user had routed Codex (cybercaius on
// Discord). With nothing set for them, a subagent and the memories follow
// the session: they go on the model the conversation's own turns go on,
// when that is one of magpie's (codexSessionOf), as the app's titles,
// when that is one of magpie's (codexSessionOf; a memory call, started
// with a turn, after that turn: codexMemorySession), as the app's titles,
// descriptions, summaries and composer predictions do (codexSideTo). The auto-review follows it when set to
// (settings.CodexAutoReviewSession, which codexcat writes into each of
// magpie's entries); left to Codex it stays on codex-auto-review, which a
@@ -121,19 +122,28 @@ var (
codexSideWait = 5 * time.Second
)
// sideOf is of for the Codex app's own side turns: a title, description,
// summary or prediction. Codex writes a new conversation's title on a
// temporary thread of its own, with no link to the conversation, started
// as the user's first message is sent, so it often reaches magpie before
// that conversation's first turn. Read then, the key's last turn is the
// previous conversation's, on the model the user switched away from
// (cybercaius on Discord: the first title after a switch came from the
// old model). When this key's last turn is older than codexSideFresh,
// such a call waits, up to codexSideWait or until it is cancelled, for
// the next turn of any conversation, and takes that one's model.
func (l *codexLeads) sideOf(r *http.Request, body []byte) string {
// sideOf is of for a side call started beside a turn: the Codex app's
// title, description, summary or prediction, and Codex's memories. Codex
// writes a new conversation's title on a temporary thread of its own, with
// no link to the conversation, started as the user's first message is
// sent, so it often reaches magpie before that conversation's first turn.
// Read then, the key's last turn is the previous conversation's, on the
// model the user switched away from (cybercaius on Discord: the first
// title after a switch came from the old model). When this key's last
// turn is older than codexSideFresh, such a call waits, up to
// codexSideWait or until it is cancelled, for the next turn of any
// conversation, and takes that one's model.
//
// beside is a call Codex starts with every turn of its conversation, tied
// to it: its memories, which Codex extracts and consolidates as each turn
// with the user's input starts (codex-rs app-server turn_processor,
// start_memories_startup_task), under that conversation's thread. Racing
// the turn, the conversation's last model is the one before a switch, so
// it waits too. A call tied to a conversation that isn't (a composer
// prediction, a known thread's title) takes its last model at once.
func (l *codexLeads) sideOf(r *http.Request, body []byte, beside bool) string {
model, tied, at := l.lookup(r, body)
if tied || model == "" || time.Since(at) < codexSideFresh {
if tied && !beside || model == "" || time.Since(at) < codexSideFresh {
return model
}
l.mu.Lock()
@@ -177,13 +187,19 @@ func (s *Server) codexFollowTo(r *http.Request, agent, kind, asked string, body
default:
return ""
}
to := s.codexSessionOf(r, body)
if to == "" || to == asked {
// the user's own pick in Codex's config is kept; read before the
// session, which a memory call may wait on
if CodexSideSet == nil || CodexSideSet(which) {
return ""
}
// the user's own pick in Codex's config is kept; read last, as it
// reads the config
if CodexSideSet == nil || CodexSideSet(which) {
var to string
if which == "memories" {
// started with a turn, maybe the first after a switch
to = s.codexMemorySession(r, body)
} else {
to = s.codexSessionOf(r, body)
}
if to == "" || to == asked {
return ""
}
return to
@@ -206,7 +222,13 @@ func (s *Server) codexSessionOf(r *http.Request, body []byte) string {
// codexSideSession is codexSessionOf for the Codex app's own side turns,
// read after the turn they were started beside (codexLeads.sideOf).
func (s *Server) codexSideSession(r *http.Request, body []byte) string {
return s.servedSession(r, s.codexLeads.sideOf(r, body))
return s.servedSession(r, s.codexLeads.sideOf(r, body, false))
}
// codexMemorySession is codexSessionOf for Codex's memory calls, read
// after the turn they were started with (codexLeads.sideOf, beside).
func (s *Server) codexMemorySession(r *http.Request, body []byte) string {
return s.servedSession(r, s.codexLeads.sideOf(r, body, true))
}
// servedSession is to, else the model in Codex's config, when magpie can
+147
View File
@@ -277,3 +277,150 @@ func TestCodexMemoriesBeforeAnyTurnFollowTheConfig(t *testing.T) {
t.Fatalf("the relay got %v", reqs)
}
}
// codexSideAsk is one of Codex's side calls on one of its own models, with
// the headers Codex sends for it.
func codexSideAsk(s *Server, model string, h map[string]string) {
body := `{"model":"` + model + `","stream":true,"input":[` + leadAsk + `]}`
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
req.Header.Set("User-Agent", "codex_cli_rs/0.159.0 (Mac OS 26.2.0; arm64)")
for k, v := range h {
req.Header.Set(k, v)
}
s.Handler().ServeHTTP(httptest.NewRecorder(), req)
}
// beforeTheTurn runs side, then turn once side is waiting for a turn or has
// been answered (on the old code a memory call never waits, and is
// answered first), and waits for side to finish.
func beforeTheTurn(t *testing.T, s *Server, side, turn func()) {
t.Helper()
done := make(chan struct{})
go func() {
defer close(done)
side()
}()
for waiting := false; !waiting; {
select {
case <-done:
waiting = true
default:
s.codexLeads.mu.Lock()
waiting = s.codexLeads.next != nil
s.codexLeads.mu.Unlock()
if !waiting {
time.Sleep(time.Millisecond)
}
}
}
turn()
<-done
}
// cybercaius on Discord: after switching Codex's model, does the first of
// each side call go on the new model, as the title does? Each kind, sent
// before the first turn on the new model reaches magpie: a new
// conversation's title and description (a temporary thread of the app's),
// its composer prediction (a fork of it), and its memories, which Codex
// starts with every turn of a conversation (phase 1 under the
// conversation's thread, phase 2 on a consolidation thread of its own).
// Each goes on the model switched to, none on the one before, none to
// ChatGPT.
func TestCodexSideCallsBeforeTheFirstTurnFollowTheSwitch(t *testing.T) {
for _, c := range []struct {
name string
h map[string]string
}{
{"title", map[string]string{"session_id": "title-thread", "x-codex-turn-metadata": `{"thread_source":"thread_title"}`}},
{"description", map[string]string{"session_id": "desc-thread", "x-codex-turn-metadata": `{"thread_source":"thread_description"}`}},
{"prediction", map[string]string{"session_id": "fork-of-lead-2", "x-codex-turn-metadata": `{"thread_source":"composer_predictions","forked_from_thread_id":"lead-2"}`}},
{"memory extraction", map[string]string{"session_id": "lead-2", "x-codex-turn-metadata": `{"thread_source":"memory_consolidation","request_kind":"memory"}`}},
{"memory consolidation", map[string]string{"session_id": "consolidation-thread", "x-openai-memgen-request": "true", "x-codex-turn-metadata": `{"thread_source":"memory_consolidation"}`}},
} {
t.Run(c.name, func(t *testing.T) {
up, old, s := codexFollowSetup(t, false)
switched := relayOn(t, "fourth")
wasModel, wasFresh, wasWait := CodexSideModel, codexSideFresh, codexSideWait
CodexSideModel = func() string { return "" }
codexSideFresh, codexSideWait = 0, time.Minute
t.Cleanup(func() { CodexSideModel, codexSideFresh, codexSideWait = wasModel, wasFresh, wasWait })
beforeTheTurn(t, s, func() { codexSideAsk(s, "gpt-5.6-luna", c.h) }, func() {
if rec := codexSubTurn(s, "fourth/gpt-6-astra", "lead-2", "", leadAsk); rec.Code != 200 {
t.Errorf("new conversation: %d %s", rec.Code, rec.Body.String())
}
})
if got := up.asked(); len(got) != 0 {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := old.requests(); len(reqs) != 1 {
t.Fatalf("the model switched from got %d requests, the %s among them", len(reqs), c.name)
}
if reqs := switched.requests(); len(reqs) != 2 {
t.Fatalf("the model switched to got %d requests, want the turn and the %s", len(reqs), c.name)
}
})
}
}
// The model switched in a conversation already under way: Codex starts its
// memories with the conversation's next turn, under that thread, and the
// memory call that beats the turn to magpie goes on the new model, not on
// the thread's last. A composer prediction of that thread asked after the
// turn is on the new model too.
func TestCodexMemoryOfASwitchedConversationFollowsTheSwitch(t *testing.T) {
up, old, s := codexFollowSetup(t, false)
switched := relayOn(t, "fourth")
wasModel, wasFresh, wasWait := CodexSideModel, codexSideFresh, codexSideWait
CodexSideModel = func() string { return "" }
codexSideFresh, codexSideWait = 0, time.Minute
t.Cleanup(func() { CodexSideModel, codexSideFresh, codexSideWait = wasModel, wasFresh, wasWait })
memory := map[string]string{"session_id": "lead-1", "x-codex-turn-metadata": `{"thread_source":"memory_consolidation","request_kind":"memory"}`}
beforeTheTurn(t, s, func() { codexSideAsk(s, "gpt-5.6-luna", memory) }, func() {
if rec := codexSubTurn(s, "fourth/gpt-6-astra", "lead-1", "", leadAsk); rec.Code != 200 {
t.Errorf("the switched turn: %d %s", rec.Code, rec.Body.String())
}
})
codexSideAsk(s, "gpt-6-luna", map[string]string{"session_id": "fork-of-lead-1", "x-codex-turn-metadata": `{"thread_source":"composer_predictions","forked_from_thread_id":"lead-1"}`})
if got := up.asked(); len(got) != 0 {
t.Fatalf("ChatGPT was asked for %v", got)
}
if reqs := old.requests(); len(reqs) != 1 {
t.Fatalf("the model switched from got %d requests", len(reqs))
}
if reqs := switched.requests(); len(reqs) != 3 {
t.Fatalf("the model switched to got %d requests, want the turn, the memory and the prediction", len(reqs))
}
}
// Codex with magpie as its provider asks for its memories on a model of
// its own by its bare name (codexMemoryStandIn): the one that beats the
// first turn after a switch goes on the model switched to, not on the
// last turn's.
func TestCodexMemoryStandInFollowsTheSwitch(t *testing.T) {
fresh(t)
old, switched := relayOn(t, "third"), relayOn(t, "fourth")
wasFresh, wasWait := codexSideFresh, codexSideWait
codexSideFresh, codexSideWait = 0, time.Minute
t.Cleanup(func() { codexSideFresh, codexSideWait = wasFresh, wasWait })
s := New()
if rec := codexCall(t, s, "third/gpt-6-astra", ""); rec.Code != 200 {
t.Fatalf("the old turn: %d %s", rec.Code, rec.Body.String())
}
beforeTheTurn(t, s, func() {
if rec := codexCall(t, s, "gpt-5.6-luna", "memory_consolidation"); rec.Code != 200 {
t.Errorf("memory: %d %s", rec.Code, rec.Body.String())
}
}, func() {
if rec := codexCall(t, s, "fourth/gpt-6-astra", ""); rec.Code != 200 {
t.Errorf("the switched turn: %d %s", rec.Code, rec.Body.String())
}
})
if reqs := old.requests(); len(reqs) != 1 {
t.Fatalf("the model switched from got %d requests", len(reqs))
}
if reqs := switched.requests(); len(reqs) != 2 {
t.Fatalf("the model switched to got %d requests, want the turn and the memory", len(reqs))
}
}
+17 -1
View File
@@ -30,6 +30,9 @@ func (s *Server) rememberCodexTurn(r *http.Request, who, agent, kind, asked stri
return
}
s.codexTurns.Store(codexTurnKey(r, who), asked)
// and by its conversation, for a memory call that raced it
// (codexMemoryStandIn)
s.codexLeads.saw(r, kind, asked)
}
// isReviewCall: Codex's auto-review of an approval (the guardian), which
@@ -66,13 +69,26 @@ func freeOnChatGPT(model, plan string) bool {
// another computer — was answered 404 "magpie knows no model
// \"codex-auto-review\"" (Adam on Discord). "" for any other call, a model
// magpie serves, or a Codex that has had no turn answered here.
func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked string) string {
//
// Codex starts its memories with each turn of a conversation, so a memory
// call can come before the turn it was started with, the first after the
// model was switched: it is read after that turn, as the app's titles are
// (codexLeads.sideOf, beside), not on the model switched away from
// (cybercaius on Discord).
func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked string, body []byte) string {
if agent != "codex" || !isMemoryKind(kind) && !isReviewCall(kind, asked) {
return ""
}
if _, _, ok := provider.Resolve(asked); ok {
return ""
}
if isMemoryKind(kind) {
if m := s.codexLeads.sideOf(r, body, true); m != "" && m != asked {
if _, _, ok := provider.Resolve(m); ok {
return m
}
}
}
key := codexTurnKey(r, who)
if m, ok := s.codexTurns.Load(key); ok {
if m, _ := m.(string); m != "" && m != asked {
+1 -1
View File
@@ -1816,7 +1816,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// that same name, went on unresolved, a 404 (Adam on Discord)
asked = grouped(at(m))
}
if m := s.codexMemoryStandIn(r, call.Agent, agent, call.Kind, asked); m != "" {
if m := s.codexMemoryStandIn(r, call.Agent, agent, call.Kind, asked, body); m != "" {
asked = m
}
// a Codex subagent on the model set for Codex's subagents, whatever