#3751's second half;67b12956fixed the half about lengths. A Codex thread moved to another provider, by the Sessions page's Move (MoveCodexProvider, #887) or as Codex steps off magpie (bringBack's MoveCodexThreads), has each of its rollouts written whole into a temp file that then takes its place. The move took no Codex lock and left alone only a thread written to in the last minute. A Codex that resumed the thread (the app-server, as run below; a resumed TUI too, by Codex's source) keeps its rollout open to append to for as long as it has the thread, so what it wrote after a move went into the file the rename had put aside: a turn the upstream answered was in neither the rollout nor what Codex sent after its next resume. moveCodexPaths now holds the thread as Codex holds one it writes to, archives or deletes (rollout/src/writer_lock.rs, acquire; thread-store holds it through a whole archive, unarchive or delete): under thread-writer-locks/.coordination.lock it makes and locks thread-writer-locks/<thread>.lock, then lets the coordination lock go and keeps the thread's lock from before a file is copied to the trash until the thread's row in the state database has moved. Letting go takes the lock file away under the coordination lock, as Codex's guard does. A Codex that resumes the thread meanwhile is turned away by Codex itself ("already has an active writer"), so the files and the row move together and a rollback is written under no Codex. A thread a Codex has open is left as it was: its files, their time and its row, with no copy kept. Its error, "a Codex has the session open", is ErrActive too, so it goes where a thread written to in the last minute goes: MoveCodexThreads leaves it for its next call, and the Sessions page's reply marks it active, so the page says "{title} is still being written to; close it in Codex and try again in a minute" ("{n} sessions ..." for several), in en, zh, zh-TW, ja and de. No new words and no GUI file changed: app.js grows 0 bytes. There is no CLI for the move. The minute is the page's own: codex exec lets the thread go as it exits (the interactive TUI wasn't tried), but Codex 0.164.0's app-server keeps a thread loaded, and held, until 30 minutes after it went idle with nothing showing it (thread_unload_delay_secs, 1800 by default), or until it ends. So a thread the Codex app has shown can be refused for up to half an hour after it is closed there, or until the app quits. Those words are left as they are (#3986). A Codex home without thread-writer-locks (a Codex from before them) has no lock to take, and its threads move as before, with the last-minute check alone. None is made there: PortCodexRollouts reads a home with one as one whose Codex holds its threads, and would then rewrite rollouts under a Codex that doesn't. A lock folder that can't be read, or a lock file that can't be opened, refuses the move with its error. The coordination lock is waited for at most 10s (filelock.Wait), under storeMu and mu as the row's 5s busy_timeout already is; not had by then, the thread counts as held, as in editRollout. editRollout, the port's writer, isn't used: it publishes one file under the coordination lock alone, while a thread's files (a revert's, a packed twin) and its row move together, and its edit can't refuse a longer id in a paginated rollout as 67b12956's rewriteCodexProvider does. rewriteCodexProvider is unchanged, so the padding and that refusal stay as they were. A thread bringBack leaves keeps its row on magpie, so the next bringBack picks it again (codexThreadsOn) and moves it once its Codex has let go: it isn't left for good. bringBack runs at Disconnect and in Codex's Sync, which SyncCatalog runs: at the GUI's start, after a provider, plugin or model list is saved or fetched, and when the catalog is fetched again (catalog.KeepFresh, at least daily in the GUI and in magpie serve). Until then the thread stays on magpie, as one written to in the last minute does now, so for up to about a day while magpie runs. At a Disconnect magpie also restarts the Codex app's app-server (KeepCodexAppOnItsProvider, every 3s), which lets the thread go; when that comes after bringBack's move, the thread waits for the next Sync. When Codex goes back to openai, or another id of magpie's length, RelabelCodexThreads first writes a plain rollout's provider in place, held or not; MoveCodexThreads meets a held thread there only for what that skips, a packed rollout mostly. For an id of another length it moves them all. RelabelCodexThreads takes no lock either. It writes the id over in the first line, in place, so a Codex appending to the file loses nothing: tried below, the turn after it was kept and the row stayed as it wrote it. It is left as it is. The port's paragraph in docs/subsystems/gateway-routing.md, where67b12956put the move's lengths, says so, and so do the comments of MoveCodexProvider, MoveCodexThreads and bringBack. What was run (tree d652ce94, on origin/main74dcf40a, go1.26.8, linux/amd64, Linux 5.15), outside graftcp, umask 077: - TestMoveCodexProviderLeavesAnOpenThread (new): a thread's writer lock held as a resumed Codex holds it. The Move is refused with ErrActive; the file, its time and the row are as they were, nothing is kept in the trash and no temp file is left. With the lock let go (its file left behind, as a Codex that ended leaves it), the Move goes through and the lock file is gone. - TestMoveCodexProviderHoldsTheThread (new): looked at from a trigger on the row's update, as the Move writes the row, the thread's lock is held and the file names the new provider already; the lock file is gone after. - TestMoveCodexThreadsLeavesAnOpenThread (new): two threads on magpie, one held. The other moves; the held one keeps its file and row, with no copy and no error, and the next call moves it once let go. A home without thread-writer-locks moves its thread as before, and gets none. - The three with 74dcf40a's codex_provider.go: red, "err <nil>, want ErrActive", "as the row was written: no lock file", and both threads moved. - -race -count=10, the three and every move and port test of internal/sessions (TestCodexProviderIn, TestMoveCodexProvider, TestMoveCodexProviderPacked, TestMoveCodexProviderKeepsBytePlaces, TestMoveCodexThreads, TestMoveCodexThreadsNone, TestPortCodexRollouts and its KeepsBytePlaces, LeavesAnOpenThread, LongerLine and RepairsForks, TestPortLineDropsClaudeBlocks, TestPortLineLeavesOthers): 16 tests, 10 runs each, ok. -race -count=3: internal/agent's TestCodexThreadsComeBackOffMagpie and TestCodexThreadsFollowMagpieIn (bringBack, bringOver) and internal/gateway's TestPortedCompactionReadsTheSame, ok. - Broken by hand, each alone in a scratch worktree at this tree, the eight move tests run, each red: - no lock taken: all three new tests, as at74dcf40a. - the row written for a thread left: both LeavesAnOpenThread tests ("its row moved to ..., its files didn't"), and MoveCodexThreads never finds the thread again ("after its Codex let go: [] <nil>"). - the lock taken after the copy to the trash: both LeavesAnOpenThread tests ("a copy kept of a thread left as it was"). - the lock let go after the files, before the row: TestMoveCodexProviderHoldsTheThread. - the error not ErrActive: TestMoveCodexProviderLeavesAnOpenThread ("err a Codex has the session open, want ErrActive") and TestMoveCodexThreadsLeavesAnOpenThread (the held thread's error returned, "thread ...: a Codex has the session open"). - the lock file left when the move lets go: both TestMoveCodexProvider tests. - thread-writer-locks made in a home without one: TestMoveCodexThreadsLeavesAnOpenThread. The other move tests stayed green under each. - Codex CLI 0.164.0, real, with gw-c's #3616 move-open harness: a sandbox HOME and CODEX_HOME, loopback only, a fake Responses upstream, and MoveCodexThreads from fake-provider to fake through a test binary built from each tree. Two turns on a thread T; a codex app-server resumes T (T's lock file appears in thread-writer-locks), waits 80s and has a turn; at 70s, the move. -74dcf40a: the move moved T, file and row. The turn completed and the upstream got it, but the rollout has it 0 times, and Codex resuming T on fake sent turns 1 and 2 without it. - here: the move moved nothing, file and row on fake-provider. The turn is in the rollout (2 lines). With the app-server gone (its lock file gone) and the rollout a minute old, the move moved T (files 1, db 1), and thread-writer-locks had only .coordination.lock after it. Codex resuming T on fake sent turns 1 and 2 and the turn the app-server had. Each tree ran twice: in the first runs the move after the app-server came within the minute after its turn, which left T here; the script now waits the minute out. - Codex CLI 0.164.0, the same sandbox: with T's lock file made and flocked under the coordination lock by another process, as holdCodexThread does, codex exec resume T exits 1 with "thread/resume failed: thread ... already has an active writer" and sends nothing; once it is let go and the file taken away, the resume runs. - Codex CLI 0.164.0, the move-open run with RelabelCodexThreads from fake to fak2 (one length) at 70s: T relabelled at once, the turn in the rollout (2 lines), the row still fak2 after it, and Codex resuming T on fak2 sent the turn. - gofmt -l clean. tools/vetset.sh: go vet -tags nogui for linux, windows and darwin, go vet for windows, go build -tags nogui for linux and darwin, and go build for windows, exit 0 each; untagged linux vet and build exit 1 (no GTK or WebKitGTK dev packages on this box). - go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun 1.4.2: 68 packages ok and 8 red, sessions ok; each red on the list of reds already filed: agent (#3141, #3398, #3641, and TestWSLColdPlaceOpensNothing, #3924), davsync TestSync (#3420), edit and testenv (umask 077, #3640), gateway TestPluginToldWhereTheAgentWorks (#3675), gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie (#3649), provider TestCodexAppServersOnHome (#3906), then "close of synctest channel from outside bubble" (#3632), tui TestTUIFetchesSubscriptionModels/agent (#3919) - On origin/main1a804859with this commit cherry-picked (a scratch worktree, not this tree): go test ./internal/sessions ok; go test -run Codex ./internal/agent, only TestCodexDriftReached red (#3398) Not run: the GUI tests, i18n-keys among them; no GUI file changed. Not tried: Windows, where magpie's lock is LockFileEx on one byte and Codex's on the whole file (as for the port), and macOS; the Codex app itself, whose app-server was driven over stdio here as the app drives one; a thread of a Codex in a WSL distro moved from Windows, where the lock taken may not be the distro's; a file system without locks, where the move is refused as held. Review (yetone, at this commit on origin/mainbb5e68cea, go1.26.8): - Checked against Codex's codex-rs/rollout/src/writer_lock.rs: acquire takes thread-writer-locks/.coordination.lock, creates and try-locks <thread_id>.lock and lets coordination go; its guard's drop takes coordination again, closes the file, removes it and lets go. The move does the same, and leaves a home without the folder alone. - On main, the three new tests red on macOS (mote): "err <nil>, want ErrActive", "as the row was written: no lock file", both threads moved. With this change, ok. - Broken by hand, each red: letGo called at once (HoldsTheThread); os.Remove dropped ("lock file is left", both MoveCodexProvider tests); threadOpen's Is false (LeavesAnOpenThread x2); the lock folder always made (MoveCodexThreads, "thread-writer-locks made where Codex keeps none"). - macOS (mote): go test -tags nogui ./internal/sessions ./internal/filelock ./internal/agent ok; -race -count=10 -run 'TestMoveCodex|TestPortCodex' ./internal/sessions ok (atd0a61b856); gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows for sessions and agent ok. - Windows (xiaomi-gpu, win-run) and Linux (WSL magpie-desktop, wsl-run): go test -run 'TestMoveCodex|TestPortCodex' ./internal/sessions ok (atd0a61b856). Not tried by the review: a real Codex CLI or app holding a thread during a move, on any system; a WSL distro's Codex moved from Windows. At the pushed tree (rebased on origin/main7e0fe83d4), macOS (mote): gofmt clean; go vet darwin, GOOS=windows and GOOS=linux -tags nogui for sessions ok; go test -tags nogui ./internal/sessions ./internal/agent ok; -run Budget ./internal/gui ok.
392 lines
14 KiB
Go
392 lines
14 KiB
Go
package sessions
|
|
|
|
import (
|
|
"bytes"
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/klauspost/compress/zstd"
|
|
"modernc.org/sqlite"
|
|
|
|
"github.com/yetone/magpie/internal/filelock"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// codexState makes a Codex state database with a thread's row, as Codex
|
|
// 0.159's state_5.sqlite has it (the columns that matter).
|
|
func codexStateDB(t *testing.T, home, id, provider string) string {
|
|
t.Helper()
|
|
p := filepath.Join(home, "state_5.sqlite")
|
|
db, err := sql.Open("sqlite", p)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
if _, err := db.Exec(`CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, model_provider TEXT NOT NULL, title TEXT NOT NULL, archived INTEGER NOT NULL DEFAULT 0);
|
|
CREATE INDEX idx_threads_provider ON threads(model_provider);
|
|
INSERT INTO threads VALUES (?, 'x', ?, 'the title', 1), ('other', 'y', ?, 'another', 0)`, id, provider, provider); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return p
|
|
}
|
|
|
|
func threadProvider(t *testing.T, db, id string) (provider, title string, archived int) {
|
|
t.Helper()
|
|
d, err := sql.Open("sqlite", db)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer d.Close()
|
|
if err := d.QueryRow(`SELECT model_provider, title, archived FROM threads WHERE id = ?`, id).Scan(&provider, &title, &archived); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return
|
|
}
|
|
|
|
// A Codex session made with another provider (CC Switch's "custom") is
|
|
// hidden from Codex's history once Codex uses magpie (#887). The Sessions
|
|
// page says which provider each was made with and which Codex uses now;
|
|
// MoveCodexProvider changes the provider in its files and in Codex's state
|
|
// database and nothing else, keeps a copy of the files first, and moving
|
|
// it back gives the files it had, byte for byte.
|
|
func TestMoveCodexProvider(t *testing.T) {
|
|
_, codex := manageSetup(t)
|
|
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
|
b, err := os.ReadFile(main)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
orig := bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom"`), 1)
|
|
old := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
|
|
os.WriteFile(main, orig, 0o644)
|
|
os.Chtimes(main, old, old)
|
|
seg := filepath.Join(codex, "sessions", "2026", "09", "23", "rollout-2026-09-23T00-27-05-"+mgCX+"_01a0c9f1-3d6f-7f33-b3bd-25c1dd14251b.jsonl")
|
|
segOrig, _ := os.ReadFile(seg)
|
|
os.WriteFile(filepath.Join(codex, "config.toml"), []byte("model = \"gpt-6\"\nmodel_provider = \"magpie\"\n\n[model_providers.magpie]\nname = \"magpie\"\n"), 0o644)
|
|
db := codexStateDB(t, codex, mgCX, "custom")
|
|
|
|
m, ok := findManaged(ListAgent("codex"), mgCX)
|
|
if !ok || m.Provider != "custom" || m.UsesProvider != "magpie" {
|
|
t.Fatalf("listed %q, uses %q; want custom, magpie", m.Provider, m.UsesProvider)
|
|
}
|
|
|
|
mv, err := MoveCodexProvider(mgCX, "magpie")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if mv.From != "custom" || mv.To != "magpie" || len(mv.Files) != 1 || mv.Files[0] != main || len(mv.DB) != 1 {
|
|
t.Fatalf("moved %+v", mv)
|
|
}
|
|
now, _ := os.ReadFile(main)
|
|
if want := bytes.Replace(orig, []byte(`"model_provider":"custom"`), []byte(`"model_provider":"magpie"`), 1); !bytes.Equal(now, want) {
|
|
t.Fatalf("the file became\n%s", now)
|
|
}
|
|
if fi, _ := os.Stat(main); !fi.ModTime().Equal(old) {
|
|
t.Errorf("its time became %v, want %v", fi.ModTime(), old)
|
|
}
|
|
if b, _ := os.ReadFile(seg); !bytes.Equal(b, segOrig) {
|
|
t.Error("a segment naming no provider was changed")
|
|
}
|
|
if p, title, arch := threadProvider(t, db, mgCX); p != "magpie" || title != "the title" || arch != 1 {
|
|
t.Errorf("thread row %q %q %d", p, title, arch)
|
|
}
|
|
if p, _, _ := threadProvider(t, db, "other"); p != "custom" {
|
|
t.Errorf("another thread became %q", p)
|
|
}
|
|
if kept, _ := filepath.Glob(filepath.Join(mv.Backup, "files", "*")); len(kept) != 2 {
|
|
t.Fatalf("backup %v", kept)
|
|
} else if b, _ := os.ReadFile(filepath.Join(mv.Backup, "files", "0-"+filepath.Base(main))); !bytes.Equal(b, orig) {
|
|
t.Error("the backup isn't the file as it was")
|
|
}
|
|
if !strings.HasPrefix(mv.Backup, os.Getenv("XDG_CONFIG_HOME")) || !strings.Contains(mv.Backup, filepath.Join("trash", "codex-provider")) {
|
|
t.Errorf("backup in %s", mv.Backup)
|
|
}
|
|
if m, _ := findManaged(ListAgent("codex"), mgCX); m.Provider != "magpie" {
|
|
t.Fatalf("listed as %q after the move", m.Provider)
|
|
}
|
|
|
|
// undo: back to custom, the file as it was
|
|
if _, err := MoveCodexProvider(mgCX, "custom"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if b, _ := os.ReadFile(main); !bytes.Equal(b, orig) {
|
|
t.Fatal("moving back didn't give the file it was")
|
|
}
|
|
if p, _, _ := threadProvider(t, db, mgCX); p != "custom" {
|
|
t.Errorf("thread row %q after moving back", p)
|
|
}
|
|
|
|
// one being written is left alone
|
|
hot := time.Now()
|
|
os.Chtimes(main, hot, hot)
|
|
if _, err := MoveCodexProvider(mgCX, "magpie"); !errors.Is(err, ErrActive) {
|
|
t.Fatalf("err %v, want ErrActive", err)
|
|
}
|
|
if b, _ := os.ReadFile(main); !bytes.Equal(b, orig) {
|
|
t.Fatal("a running session was changed")
|
|
}
|
|
if _, err := MoveCodexProvider(mgCX, "bad id"); err == nil {
|
|
t.Fatal("a provider id with a space was taken")
|
|
}
|
|
}
|
|
|
|
// A rollout the Codex app compressed (.jsonl.zst) is moved too, and stays
|
|
// compressed.
|
|
func TestMoveCodexProviderPacked(t *testing.T) {
|
|
_, codex := manageSetup(t)
|
|
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
|
b, _ := os.ReadFile(main)
|
|
b = bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom"`), 1)
|
|
enc, _ := zstd.NewWriter(nil)
|
|
os.WriteFile(main+zstSuffix, enc.EncodeAll(b, nil), 0o644)
|
|
os.Remove(main)
|
|
old := time.Now().Add(-24 * time.Hour)
|
|
os.Chtimes(main+zstSuffix, old, old)
|
|
|
|
if m, _ := findManaged(ListAgent("codex"), mgCX); m.Provider != "custom" || m.UsesProvider != "openai" {
|
|
t.Fatalf("listed %q, uses %q", m.Provider, m.UsesProvider)
|
|
}
|
|
mv, err := MoveCodexProvider(mgCX, "openai")
|
|
if err != nil || len(mv.Files) != 1 {
|
|
t.Fatalf("%+v %v", mv, err)
|
|
}
|
|
f, err := os.Open(main + zstSuffix)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer f.Close()
|
|
dec, _ := zstd.NewReader(f)
|
|
defer dec.Close()
|
|
var got bytes.Buffer
|
|
if _, err := got.ReadFrom(dec); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if want := bytes.Replace(b, []byte(`"model_provider":"custom"`), []byte(`"model_provider":"openai"`), 1); !bytes.Equal(got.Bytes(), want) {
|
|
t.Fatal("the compressed file wasn't moved")
|
|
}
|
|
}
|
|
|
|
// Codex's provider is its profile's when config.toml chooses one.
|
|
func TestCodexProviderIn(t *testing.T) {
|
|
d := t.TempDir()
|
|
if p := CodexProviderIn(d); p != "openai" {
|
|
t.Fatalf("no config: %q", p)
|
|
}
|
|
os.WriteFile(filepath.Join(d, "config.toml"), []byte("model_provider = \"custom\"\nprofile = \"m\"\n[profiles.m]\nmodel_provider = \"magpie\"\n"), 0o644)
|
|
if p := CodexProviderIn(d); p != "magpie" {
|
|
t.Fatalf("profile: %q", p)
|
|
}
|
|
}
|
|
|
|
// Codex keeps places in a paginated rollout by byte (xybio on Discord, see
|
|
// TestPortCodexRolloutsKeepsBytePlaces): a move keeps the session_meta
|
|
// line's length, padded after its JSON for a shorter id, and a longer id
|
|
// is refused with the files as they were; moving back gives the bytes it
|
|
// had.
|
|
func TestMoveCodexProviderKeepsBytePlaces(t *testing.T) {
|
|
_, codex := manageSetup(t)
|
|
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
|
b, _ := os.ReadFile(main)
|
|
orig := bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom","history_mode":"paginated"`), 1)
|
|
old := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
|
|
os.WriteFile(main, orig, 0o644)
|
|
os.Chtimes(main, old, old)
|
|
|
|
if _, err := MoveCodexProvider(mgCX, "cc"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
now, _ := os.ReadFile(main)
|
|
if len(now) != len(orig) {
|
|
t.Fatalf("%d bytes, was %d", len(now), len(orig))
|
|
}
|
|
first := now[:bytes.IndexByte(now, '\n')]
|
|
if !bytes.HasSuffix(first, []byte("} ")) || !bytes.Contains(first, []byte(`"model_provider":"cc"`)) || !bytes.Equal(now[len(first):], orig[len(first):]) {
|
|
t.Fatalf("the file became\n%s", now)
|
|
}
|
|
if _, err := MoveCodexProvider(mgCX, "a-longer-provider"); err == nil {
|
|
t.Fatal("a longer id was written")
|
|
}
|
|
if b, _ := os.ReadFile(main); !bytes.Equal(b, now) {
|
|
t.Fatal("a refused move changed the file")
|
|
}
|
|
if _, err := MoveCodexProvider(mgCX, "custom"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if b, _ := os.ReadFile(main); !bytes.Equal(b, orig) {
|
|
t.Fatalf("moving back gave\n%s", b)
|
|
}
|
|
}
|
|
|
|
// holdThread holds a thread's writer lock in a Codex home as a Codex that
|
|
// has the thread open does (the app-server after thread/resume, a resumed
|
|
// TUI): thread-writer-locks/<id>.lock, locked on a descriptor of its own.
|
|
// It gives the lock file's path and the Codex letting go, which leaves
|
|
// the file, as a Codex that ended leaves it.
|
|
func holdThread(t *testing.T, home, id string) (path string, letGo func()) {
|
|
t.Helper()
|
|
locks := filepath.Join(home, "thread-writer-locks")
|
|
if err := os.MkdirAll(locks, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
path = filepath.Join(locks, id+".lock")
|
|
lf, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got, err := filelock.TryLock(lf); !got || err != nil {
|
|
lf.Close()
|
|
t.Fatalf("lock: %v %v", got, err)
|
|
}
|
|
var once sync.Once
|
|
letGo = func() { once.Do(func() { filelock.Unlock(lf); lf.Close() }) }
|
|
t.Cleanup(letGo)
|
|
return path, letGo
|
|
}
|
|
|
|
// providerTrash is what magpie's trash keeps of Codex provider moves.
|
|
func providerTrash(t *testing.T) []string {
|
|
t.Helper()
|
|
kept, _ := filepath.Glob(filepath.Join(settings.Dir(), "trash", "codex-provider", "*"))
|
|
return kept
|
|
}
|
|
|
|
// #3751: a Codex that has a thread open (the app-server after
|
|
// thread/resume, a resumed TUI) holds the thread's writer lock and keeps
|
|
// its rollout open to append to. A move put a new file in its place, and
|
|
// what that Codex wrote next went to the old one: a turn the upstream
|
|
// answered was gone from the rollout, and from what Codex sent after its
|
|
// next resume. A thread a Codex holds is left as it was, its files, time
|
|
// and row, with no copy kept (ErrActive: the Sessions page says to close
|
|
// it in Codex); once the Codex lets go it moves, and the lock file left
|
|
// behind goes, as Codex's own guard removes it.
|
|
func TestMoveCodexProviderLeavesAnOpenThread(t *testing.T) {
|
|
_, codex := manageSetup(t)
|
|
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
|
b, _ := os.ReadFile(main)
|
|
orig := bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom"`), 1)
|
|
old := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
|
|
os.WriteFile(main, orig, 0o644)
|
|
os.Chtimes(main, old, old)
|
|
db := codexStateDB(t, codex, mgCX, "custom")
|
|
lock, letGo := holdThread(t, codex, mgCX)
|
|
|
|
if _, err := MoveCodexProvider(mgCX, "magpie"); !errors.Is(err, ErrActive) {
|
|
t.Fatalf("err %v, want ErrActive", err)
|
|
}
|
|
if b, _ := os.ReadFile(main); !bytes.Equal(b, orig) {
|
|
t.Fatal("moved while a Codex had it open")
|
|
}
|
|
if fi, _ := os.Stat(main); !fi.ModTime().Equal(old) {
|
|
t.Errorf("its time became %v, want %v", fi.ModTime(), old)
|
|
}
|
|
if p, _, _ := threadProvider(t, db, mgCX); p != "custom" {
|
|
t.Errorf("its row moved to %q, its files didn't", p)
|
|
}
|
|
if kept := providerTrash(t); len(kept) != 0 {
|
|
t.Errorf("a copy kept of a thread left as it was: %v", kept)
|
|
}
|
|
if left, _ := filepath.Glob(filepath.Join(filepath.Dir(main), ".magpie-*")); len(left) > 0 {
|
|
t.Errorf("left behind: %v", left)
|
|
}
|
|
|
|
letGo()
|
|
mv, err := MoveCodexProvider(mgCX, "magpie")
|
|
if err != nil || len(mv.Files) != 1 || len(mv.DB) != 1 {
|
|
t.Fatalf("after the Codex let go: %+v %v", mv, err)
|
|
}
|
|
if got := codexMetaProvider(main); got != "magpie" {
|
|
t.Fatalf("file on %q", got)
|
|
}
|
|
if p, _, _ := threadProvider(t, db, mgCX); p != "magpie" {
|
|
t.Errorf("row on %q", p)
|
|
}
|
|
if _, err := os.Stat(lock); !errors.Is(err, fs.ErrNotExist) {
|
|
t.Errorf("the thread's lock file is left: %v", err)
|
|
}
|
|
}
|
|
|
|
// moveProbe is run by magpie_move_probe(), which a test's state database
|
|
// calls from a trigger as a move writes a thread's row.
|
|
var (
|
|
moveProbeOnce sync.Once
|
|
moveProbe func()
|
|
)
|
|
|
|
// probeRowMove has probe run from inside the state database db as a move
|
|
// writes a thread's row, which it does after the thread's files.
|
|
func probeRowMove(t *testing.T, db string, probe func()) {
|
|
t.Helper()
|
|
moveProbeOnce.Do(func() {
|
|
sqlite.MustRegisterScalarFunction("magpie_move_probe", 0, func(*sqlite.FunctionContext, []driver.Value) (driver.Value, error) {
|
|
if moveProbe != nil {
|
|
moveProbe()
|
|
}
|
|
return nil, nil
|
|
})
|
|
})
|
|
moveProbe = probe
|
|
t.Cleanup(func() { moveProbe = nil })
|
|
d, err := sql.Open("sqlite", db)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer d.Close()
|
|
if _, err := d.Exec(`CREATE TRIGGER probe BEFORE UPDATE OF model_provider ON threads BEGIN SELECT magpie_move_probe(); END`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
// A move holds the thread as Codex's own archive and delete hold one while
|
|
// they move its rollouts (thread-store's acquire_writer_lock): from before
|
|
// its files are copied until its row is written. A Codex that opens the
|
|
// thread meanwhile is turned away by Codex itself ("already has an active
|
|
// writer"), never handed a file about to be put out of its place, and the
|
|
// files and the row move together. Looked at from inside the row's write.
|
|
func TestMoveCodexProviderHoldsTheThread(t *testing.T) {
|
|
_, codex := manageSetup(t)
|
|
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
|
|
b, _ := os.ReadFile(main)
|
|
old := time.Now().Add(-24 * time.Hour)
|
|
os.WriteFile(main, bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom"`), 1), 0o644)
|
|
os.Chtimes(main, old, old)
|
|
db := codexStateDB(t, codex, mgCX, "custom")
|
|
lock := filepath.Join(codex, "thread-writer-locks", mgCX+".lock")
|
|
if err := os.MkdirAll(filepath.Dir(lock), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var seen []string
|
|
probeRowMove(t, db, func() {
|
|
lf, err := os.OpenFile(lock, os.O_RDWR, 0)
|
|
if err != nil {
|
|
seen = append(seen, "no lock file")
|
|
return
|
|
}
|
|
defer lf.Close()
|
|
if got, _ := filelock.TryLock(lf); got {
|
|
filelock.Unlock(lf)
|
|
seen = append(seen, "free")
|
|
} else {
|
|
seen = append(seen, "held")
|
|
}
|
|
seen = append(seen, "file on "+codexMetaProvider(main))
|
|
})
|
|
|
|
if _, err := MoveCodexProvider(mgCX, "magpie"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := strings.Join(seen, ", "); got != "held, file on magpie" {
|
|
t.Fatalf("as the row was written: %s; want held, file on magpie", got)
|
|
}
|
|
if _, err := os.Stat(lock); !errors.Is(err, fs.ErrNotExist) {
|
|
t.Errorf("the thread's lock file is left: %v", err)
|
|
}
|
|
}
|