Files
magpie/internal/gateway/codex_memory.go
T
yetone b7d5a97fec 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.
2026-10-27 08:37:47 +08:00

122 lines
4.7 KiB
Go

package gateway
import (
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// isMemoryKind: a call Codex makes to write or consolidate its memories,
// however it names one (usage.PurposeOf's memory_consolidation).
func isMemoryKind(kind string) bool {
return usage.PurposeOf(kind) == "kind:memory_consolidation"
}
// codexTurnKey is whose turns codexTurns holds: the agent recorded and the
// gateway key it came with, so a Codex on another computer (its own key,
// #742's Codex-BWG and Codex-R4S) is told apart from this one's.
func codexTurnKey(r *http.Request, who string) string {
return who + "\x00" + access.Caller(r.Context()).KeyID
}
// rememberCodexTurn keeps the model a turn of Codex's own conversation
// was asked on, one magpie serves, for its memory calls.
func (s *Server) rememberCodexTurn(r *http.Request, who, agent, kind, asked string) {
if agent != "codex" || kind != "" {
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
// it asks for on codex-auto-review, the reviewer model of OpenAI's, when
// its list has that or names it as a model's auto_review_model_override.
func isReviewCall(kind, asked string) bool {
return kind == "guardian" || asked == "codex-auto-review"
}
// freeOnChatGPT says whether a call on model by a ChatGPT account on plan
// is free, counted in none of its usage windows: Codex's reviewer model,
// codex-auto-review, since OpenAI made Auto-review free for ChatGPT
// sign-ins on 2026-10-06 (#1593, hywang1230), but not on a Free plan,
// where cybercaius on Discord measured it spending the allowance. A review
// run on another model, or through an API key, is counted as any call.
func freeOnChatGPT(model, plan string) bool {
return strings.EqualFold(strings.TrimSpace(model), "codex-auto-review") && !strings.EqualFold(strings.TrimSpace(plan), "free")
}
// codexMemoryStandIn is the model a Codex memory call goes to when magpie
// knows none by the name it came with (#742): Codex writes and
// consolidates its memories on models of its own (memories.extract_model
// and consolidation_model, gpt-5.6-luna and gpt-5.6-terra by default) by
// their bare names, whatever it is set to, so with magpie as its provider
// every one was turned away as an unknown model before it was routed. It
// goes to the model that Codex's own turns go to — the last one it had
// answered here, else the last in the ledger (a week back) from the same
// agent with the same key — so it is routed, and in the views, as the
// memory call it is. Its auto-review (isReviewCall) goes there too when
// Codex's config names no model magpie serves (StandIn): Codex reviews on
// the conversation's model when it has no reviewer, and a Codex whose
// config magpie doesn't read as its own — on magpie through another
// provider table or a profile, under a CODEX_HOME of its own, or on
// 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.
//
// 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 {
if _, _, ok := provider.Resolve(m); ok {
return m
}
}
}
keyID := access.Caller(r.Context()).KeyID
var last usage.Record
usage.Visit(time.Now().Add(-7*24*time.Hour), func(rec usage.Record) {
if rec.Agent != who || rec.CallerKeyID != keyID || rec.Kind != "" || rec.Rejected || rec.IsReported() || rec.Failed() || rec.Requested == "" {
return
}
if rec.Time.After(last.Time) {
last = rec
}
})
m := last.Requested
if id, ok := provider.GroupFor(m); ok {
m = id
}
if m == "" || m == asked {
return ""
}
if _, _, ok := provider.Resolve(m); !ok {
return ""
}
return m
}