codex: a chat the Codex app had open as magpie became its provider moves once the app lets it go (crypto0xfish on Discord)
crypto0xfish on Discord, the Codex app: "Model provider mismatch. This chat uses OpenAI, but your current provider is magpie. Switch to OpenAI to continue." magpie makes itself Codex's provider (model_provider = "magpie") when Codex has no ChatGPT sign-in, is signed in with an API key, the user picks magpie API, or the ChatGPT account is used up (the takeover). bringOver then moves OpenAI's threads to magpie, a paginated one by its row (RetagPagedCodexThreads), skipping any a Codex holds open (its writer lock) or wrote to in the last minute, "for the next sync". The Codex app holds the lock of every thread it has loaded, the chat on screen among them, however long ago it was written (tried below), and nothing asked for that next sync: Sync runs on catalog changes, which can be hours away. So the chat open at the switch stayed on OpenAI; the app refuses it while loaded (app-server check_thread_model_provider_for_input compares the loaded thread's provider with config.toml at each turn), and after the app let it go it was refused again on resume by its row, until something else synced.681a472cafixed the same gap for bringBack by time alone and named the held-lock case as not tried. - sessions.CodexThreadsBusyOn also counts a thread on the provider whose writer lock a Codex holds (codexLockedIDs: the lock files in thread-writer-locks, each tried and let go under Codex's coordination lock, none made or removed). - codexThreadsLater(dir, p) now looks every 15s, for up to 12h, and asks for the Sync once nothing on p is busy or held; one wait per home and provider. bringBack keeps calling it for magpie; bringOver calls it for the provider it moved from, and lendOwn for openai (the same skip, OpenAI's threads onto a provider of the user's). - Tests: TestCodexOpenThreadFollowsMagpieOnceLetGo (new: a paginated OpenAI thread held open stays at the takeover, no Sync is asked while held, one is once let go, and that Sync moves it to magpie); TestCodexTakeoverThreadComesBackOnceQuiet now expects the Sync only after the thread is quiet. TestMain turns the wait off so no goroutine outlives a test; the two tests end theirs in Cleanup. - docs/subsystems/agent-wiring.md says so. The chat loaded at the moment of the switch can't be helped from outside: the app goes on with it once it reloads it (quit and reopen). Codex's identity line, base_instructions and every value of the user's are untouched. Run on mote at this tree (basecff530079): - gofmt -l: clean; go build ./...: ok; - go vet ./internal/agent ./internal/sessions for darwin, linux -tags nogui and windows: clean; - the two tests with -race -count=3: ok; - go test ./internal/agent ./internal/sessions: ok. On Windows (win-run): the two tests and TestCodexPagedThreadsFollowByRow: ok. Broken by hand: bringOver's call turned off (`if false &&`), the new test fails "no later Sync asked for"; the lock check in CodexThreadsBusyOn turned off, it fails the same way. Restored, both pass. Real Codex: codex-cli 0.165.0's app-server in a sandbox CODEX_HOME, a thread started and a turn sent (to a dead fake provider). With the thread loaded and its rollout quiet 73s, its lock was held, a probe built from this tree said CodexThreadsBusyOn true and RetagPagedCodexThreads moved nothing; after the app-server exited and a quiet minute, busy was false and the retag moved the row. Not tried: the real Codex desktop app (whether leaving a chat for another lets its lock go within a minute, or only quitting does), and a live switch with a real used-up or API-key account. The reporter's own setup (why Codex was on magpie for them) is not known. Reported-by: crypto0xfish
This commit is contained in:
File diff suppressed because one or more lines are too long
+66
-15
@@ -804,7 +804,7 @@ func codexIn(at place) *Agent {
|
||||
// each time and its model reads unavailable (nb5p on Discord).
|
||||
// Another Sync comes once the thread is quiet.
|
||||
if sessions.CodexThreadsBusyOn(dir, magpieID) {
|
||||
codexThreadsLater()
|
||||
codexThreadsLater(dir, magpieID)
|
||||
}
|
||||
}
|
||||
// bringOver is bringBack the other way: while magpie is Codex's
|
||||
@@ -903,6 +903,12 @@ func codexIn(at place) *Agent {
|
||||
if err != nil {
|
||||
log.Printf("codex: moving %s's threads to magpie: %v", from, err)
|
||||
}
|
||||
// one the Codex app has open (the chat on screen as magpie became
|
||||
// the provider) or wrote to this minute stayed on from: it moves
|
||||
// once it is let go (crypto0xfish on Discord)
|
||||
if sessions.CodexThreadsBusyOn(dir, from) {
|
||||
codexThreadsLater(dir, from)
|
||||
}
|
||||
}
|
||||
// mirrorsTaken are the mirrors takeMirrors pointed at magpie (#1796)
|
||||
mirrorsTaken := func() []string {
|
||||
@@ -1423,6 +1429,9 @@ func codexIn(at place) *Agent {
|
||||
if err != nil {
|
||||
log.Printf("codex: moving OpenAI's threads to %s: %v", to, err)
|
||||
}
|
||||
if sessions.CodexThreadsBusyOn(dir, "openai") {
|
||||
codexThreadsLater(dir, "openai")
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -2797,24 +2806,66 @@ var codexThreadsAgain func()
|
||||
|
||||
func init() { codexThreadsAgain = SyncCatalogSoon }
|
||||
|
||||
// codexThreadsWait is how long codexThreadsLater waits: past the window
|
||||
// in which a thread counts as being written to.
|
||||
var codexThreadsWait = sessions.ActiveWindow + 5*time.Second
|
||||
// codexThreadsWait is how often codexThreadsLater looks again: within
|
||||
// it of a thread going quiet, or of the Codex app letting it go, the
|
||||
// Sync is asked for.
|
||||
var codexThreadsWait = 15 * time.Second
|
||||
|
||||
var codexThreadsPending satomic.Bool
|
||||
// codexThreadsFor is how long codexThreadsLater keeps looking, in
|
||||
// nanoseconds: a thread the Codex app keeps open all day waits for the
|
||||
// next Sync after it. Read at each look, so a test ends a wait by
|
||||
// setting it to 0.
|
||||
var codexThreadsFor satomic.Int64
|
||||
|
||||
// codexThreadsLater runs codexThreadsAgain once codexThreadsWait has
|
||||
// passed, for the threads bringBack left on magpie as they were being
|
||||
// written to. One wait at a time: another call while one is pending
|
||||
// adds none.
|
||||
func codexThreadsLater() {
|
||||
if !codexThreadsPending.CompareAndSwap(false, true) {
|
||||
func init() { codexThreadsFor.Store(int64(12 * time.Hour)) }
|
||||
|
||||
var (
|
||||
codexThreadsMu sync.Mutex
|
||||
codexThreadsPending = map[string]bool{}
|
||||
)
|
||||
|
||||
// codexThreadsLater runs codexThreadsAgain once no thread of the Codex
|
||||
// home dir on the provider p is being written to or held open
|
||||
// (sessions.CodexThreadsBusyOn), for the threads a move off p left there:
|
||||
// bringBack's on magpie as they were being written to (nb5p on Discord),
|
||||
// and bringOver's and lendOwn's on OpenAI that the Codex app had open as
|
||||
// magpie became Codex's provider. Those the app refuses to go on with
|
||||
// ("This chat uses OpenAI, but your current provider is magpie",
|
||||
// crypto0xfish on Discord) while it keeps them loaded, and once it lets
|
||||
// them go (the chat closed, the app quit) it resumes them on the provider
|
||||
// their row names, so they have to move by then; nothing else may Sync
|
||||
// for hours. It looks every codexThreadsWait, which is a database read
|
||||
// and a try of the locks Codex holds, for up to codexThreadsFor. One wait
|
||||
// at a time for each home and provider: another call while one is
|
||||
// pending adds none.
|
||||
func codexThreadsLater(dir, p string) {
|
||||
key := dir + "\x00" + p
|
||||
codexThreadsMu.Lock()
|
||||
if codexThreadsPending[key] {
|
||||
codexThreadsMu.Unlock()
|
||||
return
|
||||
}
|
||||
time.AfterFunc(codexThreadsWait, func() {
|
||||
codexThreadsPending.Store(false)
|
||||
codexThreadsAgain()
|
||||
})
|
||||
codexThreadsPending[key] = true
|
||||
codexThreadsMu.Unlock()
|
||||
done := func() {
|
||||
codexThreadsMu.Lock()
|
||||
delete(codexThreadsPending, key)
|
||||
codexThreadsMu.Unlock()
|
||||
}
|
||||
wait := codexThreadsWait
|
||||
go func() {
|
||||
for start := time.Now(); time.Since(start) < time.Duration(codexThreadsFor.Load()); {
|
||||
time.Sleep(wait)
|
||||
if !sessions.CodexThreadsBusyOn(dir, p) {
|
||||
// let go first: the Sync it asks for may find another
|
||||
// thread busy and ask again
|
||||
done()
|
||||
codexThreadsAgain()
|
||||
return
|
||||
}
|
||||
}
|
||||
done()
|
||||
}()
|
||||
}
|
||||
|
||||
// codexUsedUp reports whether the ChatGPT account Codex is signed in to
|
||||
|
||||
@@ -1,13 +1,45 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
)
|
||||
|
||||
// watchCodexThreads stands in for codexThreadsLater's Sync, looking every
|
||||
// 10ms, and ends every wait it started when the test ends.
|
||||
func watchCodexThreads(t *testing.T) <-chan struct{} {
|
||||
t.Helper()
|
||||
asked := make(chan struct{}, 4)
|
||||
oldAgain, oldWait := codexThreadsAgain, codexThreadsWait
|
||||
codexThreadsAgain = func() { asked <- struct{}{} }
|
||||
codexThreadsWait = 10 * time.Millisecond
|
||||
codexThreadsFor.Store(int64(time.Minute))
|
||||
t.Cleanup(func() {
|
||||
codexThreadsFor.Store(0)
|
||||
for end := time.Now().Add(5 * time.Second); ; {
|
||||
codexThreadsMu.Lock()
|
||||
n := len(codexThreadsPending)
|
||||
codexThreadsMu.Unlock()
|
||||
if n == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(end) {
|
||||
t.Error("a wait for Codex's threads outlived its test")
|
||||
break
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
codexThreadsAgain, codexThreadsWait = oldAgain, oldWait
|
||||
})
|
||||
return asked
|
||||
}
|
||||
|
||||
// nb5p on Discord: with the ChatGPT account Codex is signed in to used
|
||||
// up, magpie became Codex's provider (the takeover), and the turn the
|
||||
// user sent then started a thread on magpie. When the account came back
|
||||
@@ -24,14 +56,8 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) {
|
||||
if err := cx.Fields[0].Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
asked := make(chan struct{}, 4)
|
||||
oldAgain, oldWait := codexThreadsAgain, codexThreadsWait
|
||||
codexThreadsAgain = func() { asked <- struct{}{} }
|
||||
codexThreadsWait = 10 * time.Millisecond
|
||||
t.Cleanup(func() {
|
||||
codexThreadsAgain, codexThreadsWait = oldAgain, oldWait
|
||||
codexUsedUp = func() bool { return false }
|
||||
})
|
||||
asked := watchCodexThreads(t)
|
||||
t.Cleanup(func() { codexUsedUp = func() bool { return false } })
|
||||
|
||||
codexUsedUp = func() bool { return true }
|
||||
if err := cx.Sync(); err != nil {
|
||||
@@ -56,13 +82,18 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) {
|
||||
t.Fatalf("a thread being written to was moved: %q", p)
|
||||
}
|
||||
select {
|
||||
case <-asked:
|
||||
t.Fatal("a Sync asked for while the thread is still written to")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
// quiet now
|
||||
old := now.Add(-2 * time.Minute)
|
||||
os.Chtimes(path, old, old)
|
||||
select {
|
||||
case <-asked:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the thread left on magpie as it was written to: no later Sync asked for")
|
||||
}
|
||||
// that Sync, the thread quiet by then
|
||||
old := now.Add(-2 * time.Minute)
|
||||
os.Chtimes(path, old, old)
|
||||
if err := cx.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -75,3 +106,89 @@ func TestCodexTakeoverThreadComesBackOnceQuiet(t *testing.T) {
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
// crypto0xfish on Discord, the Codex app: "Model provider mismatch. This
|
||||
// chat uses OpenAI, but your current provider is magpie. Switch to OpenAI
|
||||
// to continue." The app holds the writer lock of every thread it has
|
||||
// loaded, the chat on screen among them, and a thread's row moves to
|
||||
// magpie (bringOver) only when no Codex holds it, so the chat open as
|
||||
// magpie became Codex's provider stayed on OpenAI. Nothing asked for
|
||||
// another Sync, so it stayed there after the app let it go, and the app
|
||||
// refused it on every reopen until something else synced, which can be
|
||||
// hours. bringOver now asks for that Sync once the thread is let go, and
|
||||
// it moves the thread to magpie, where the app resumes it.
|
||||
func TestCodexOpenThreadFollowsMagpieOnceLetGo(t *testing.T) {
|
||||
const id = "019a0000-0000-7000-8000-0000000000b2"
|
||||
home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "")
|
||||
dir := filepath.Join(home, ".codex")
|
||||
// a paginated thread of OpenAI's, quiet for a day and packed by
|
||||
// Codex, that the Codex app has open (codex-rs rollout writer_lock.rs)
|
||||
packThread(t, codexThreadOn(t, dir, id, "openai"))
|
||||
db, err := sql.Open("sqlite", filepath.Join(dir, "state_5.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Exec(`ALTER TABLE threads ADD COLUMN history_mode TEXT NOT NULL DEFAULT 'legacy'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`UPDATE threads SET history_mode = 'paginated' WHERE id = ?`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
locks := filepath.Join(dir, "thread-writer-locks")
|
||||
os.MkdirAll(locks, 0o755)
|
||||
lf, err := os.OpenFile(filepath.Join(locks, id+".lock"), os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := filelock.TryLock(lf); !got {
|
||||
t.Fatal("lock:", err)
|
||||
}
|
||||
letGo := func() { filelock.Unlock(lf); lf.Close() }
|
||||
defer func() {
|
||||
if lf != nil {
|
||||
letGo()
|
||||
}
|
||||
}()
|
||||
|
||||
cx := codex(home)
|
||||
if err := cx.Fields[0].Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
asked := watchCodexThreads(t)
|
||||
t.Cleanup(func() { codexUsedUp = func() bool { return false } })
|
||||
codexUsedUp = func() bool { return true }
|
||||
if err := cx.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) {
|
||||
t.Fatalf("used up, magpie not Codex's provider:\n%s", cfg)
|
||||
}
|
||||
if p := codexRowOn(t, dir, id); p != "openai" {
|
||||
t.Fatalf("a thread a Codex holds open was moved: %q", p)
|
||||
}
|
||||
select {
|
||||
case <-asked:
|
||||
t.Fatal("a Sync asked for while the app still holds the thread")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
// the app lets it go: the chat closed, or the app quit
|
||||
letGo()
|
||||
lf = nil
|
||||
select {
|
||||
case <-asked:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the thread the app had open stayed on OpenAI: no later Sync asked for")
|
||||
}
|
||||
if err := cx.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := codexRowOn(t, dir, id); p != "magpie" {
|
||||
t.Fatalf("thread on %q after the later Sync, want magpie, where the app resumes it", p)
|
||||
}
|
||||
select {
|
||||
case <-asked:
|
||||
t.Fatal("another Sync asked for with nothing left on OpenAI")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,11 @@ func TestMain(m *testing.M) {
|
||||
// whether Codex's ChatGPT account is out of its allowance is asked of
|
||||
// OpenAI; never from here
|
||||
codexUsedUp = func() bool { return false }
|
||||
// a thread a Codex holds open is looked at again later, on its own
|
||||
// goroutine, which would outlive its test; the tests about it set
|
||||
// their own wait
|
||||
codexThreadsAgain = func() {}
|
||||
codexThreadsFor.Store(0)
|
||||
// Sandboxed config writes must never write into the real OS keychain.
|
||||
zedCredential = func(string) error { return nil }
|
||||
// Pi's and omp's model registries are read from their installs; never
|
||||
|
||||
@@ -535,11 +535,16 @@ func codexThreadsOn(home, p string) []string {
|
||||
|
||||
// CodexThreadsBusyOn says whether a thread a Codex folder's state
|
||||
// databases keep on the provider p was written to in the last
|
||||
// ActiveWindow, which a move of p's threads leaves where it is: such a
|
||||
// move has more to do once the thread is quiet. A database that can't be
|
||||
// read, and a rollout that can't be found, say nothing.
|
||||
// ActiveWindow, or is held open by a Codex (its writer lock), which a
|
||||
// move of p's threads leaves where it is: such a move has more to do once
|
||||
// the thread is quiet and let go. The Codex app holds the lock of every
|
||||
// thread it has loaded, the chat on screen among them, for as long as it
|
||||
// keeps it (codex-rs rollout recorder, writer_lock.rs), however long ago
|
||||
// it was written to. A database that can't be read, and a rollout that
|
||||
// can't be found, say nothing.
|
||||
func CodexThreadsBusyOn(home, p string) bool {
|
||||
now := time.Now()
|
||||
locked := codexLockedIDs(home)
|
||||
for _, path := range codexStateDBs(home) {
|
||||
u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), RawQuery: "mode=ro&_pragma=busy_timeout(2000)"}
|
||||
if len(u.Path) >= 2 && u.Path[1] == ':' {
|
||||
@@ -550,11 +555,18 @@ func CodexThreadsBusyOn(home, p string) bool {
|
||||
continue
|
||||
}
|
||||
var paths []string
|
||||
rows, err := db.Query(`SELECT rollout_path FROM threads WHERE model_provider = ?`, p)
|
||||
var held bool
|
||||
rows, err := db.Query(`SELECT id, rollout_path FROM threads WHERE model_provider = ?`, p)
|
||||
if err == nil {
|
||||
for rows.Next() {
|
||||
var r string
|
||||
if rows.Scan(&r) == nil && r != "" {
|
||||
var id, r string
|
||||
if rows.Scan(&id, &r) != nil {
|
||||
continue
|
||||
}
|
||||
if locked[strings.ToLower(id)] {
|
||||
held = true
|
||||
}
|
||||
if r != "" {
|
||||
paths = append(paths, r)
|
||||
}
|
||||
}
|
||||
@@ -566,10 +578,60 @@ func CodexThreadsBusyOn(home, p string) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if held {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// codexLockedIDs are the threads of a Codex home a Codex holds open now:
|
||||
// those whose lock file in thread-writer-locks is locked, as
|
||||
// holdCodexThread finds them, by lower-case id. Each lock is tried under
|
||||
// the home's coordination lock and let go at once, so a Codex taking one
|
||||
// meanwhile waits on the coordination lock rather than being turned away;
|
||||
// no lock file is made or taken away. A home without thread-writer-locks,
|
||||
// or with none held, has none.
|
||||
func codexLockedIDs(home string) map[string]bool {
|
||||
if home == "" {
|
||||
return nil
|
||||
}
|
||||
locks := filepath.Join(home, "thread-writer-locks")
|
||||
ents, err := os.ReadDir(locks)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var ids []string
|
||||
for _, e := range ents {
|
||||
if id, ok := strings.CutSuffix(e.Name(), ".lock"); ok && !e.IsDir() && safeID.MatchString(id) {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
unlock, ok := filelock.Lock(filepath.Join(locks, ".coordination.lock"), filelock.Wait)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
defer unlock()
|
||||
out := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
f, err := os.OpenFile(filepath.Join(locks, id+".lock"), os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
got, err := filelock.TryLock(f)
|
||||
if got {
|
||||
filelock.Unlock(f)
|
||||
} else if err == nil {
|
||||
out[strings.ToLower(id)] = true
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MoveCodexThreads moves every thread of a Codex folder its state database
|
||||
// keeps on the provider from to the provider to, each as MoveCodexProvider
|
||||
// moves one: its files' session_meta and its row, a copy of the files kept
|
||||
|
||||
Reference in New Issue
Block a user