Files
magpie/internal/sessions/codex_threads_move_test.go
T
JoeyWu-tech bec9df0888 sessions: a provider move leaves a thread a Codex has open (#3751)
#3751's second half; 67b12956 fixed 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, where
67b12956 put the move's lengths, says so, and so do the comments of
MoveCodexProvider, MoveCodexThreads and bringBack.

What was run (tree d652ce94, on origin/main 74dcf40a, 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 at 74dcf40a.
  - 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/main 1a804859 with 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/main bb5e68cea, 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 (at d0a61b856);
  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 (at d0a61b856).
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/main 7e0fe83d4), 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.
2026-10-31 18:52:01 +08:00

193 lines
7.6 KiB
Go

package sessions
import (
"bytes"
"database/sql"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// cxRollout writes a Codex rollout of the thread id on the provider p, as
// Codex 0.162 starts one, with the time at.
func cxRollout(t *testing.T, home, sub, id, p string, at time.Time) string {
t.Helper()
dir := filepath.Join(home, sub, "2026", "10", "21")
if sub == "archived_sessions" {
dir = filepath.Join(home, sub)
}
os.MkdirAll(dir, 0o755)
path := filepath.Join(dir, "rollout-2026-10-21T10-00-00-"+id+".jsonl")
b := `{"timestamp":"2026-10-21T10:00:00.000Z","type":"session_meta","payload":{"id":"` + id + `","timestamp":"2026-10-21T10:00:00.000Z","cwd":"/work/proj","originator":"codex_cli_rs","cli_version":"0.162.1","source":"cli","model_provider":"` + p + `","base_instructions":{"text":"x"}}}` + "\n" +
`{"timestamp":"2026-10-21T10:00:01.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"remember: the build uses make"}]}}` + "\n"
if err := os.WriteFile(path, []byte(b), 0o644); err != nil {
t.Fatal(err)
}
os.Chtimes(path, at, at)
return path
}
func cxThreadRows(t *testing.T, home string, rows map[string]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)`); err != nil {
t.Fatal(err)
}
for id, prov := range rows {
if _, err := db.Exec(`INSERT INTO threads VALUES (?, 'x', ?, 't', 0)`, id, prov); err != nil {
t.Fatal(err)
}
}
return p
}
// Codex lists only the threads of the provider it is on now, so the threads
// started while magpie was its provider ("magpie") were gone from Codex
// once it was off magpie (kaizaoji on X). MoveCodexThreads moves every
// thread on one provider to another, in its files and its row, a copy of
// each kept: an archived one too; one Codex wrote to in the last minute
// waits; a thread of another provider (CC Switch's "custom") stays.
func TestMoveCodexThreads(t *testing.T) {
_, home := manageSetup(t)
const (
old = "019a0000-0000-7000-8000-00000000000a"
archived = "019a0000-0000-7000-8000-00000000000b"
hot = "019a0000-0000-7000-8000-00000000000c"
theirs = "019a0000-0000-7000-8000-00000000000d"
)
day := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
oldPath := cxRollout(t, home, "sessions", old, "magpie", day)
arPath := cxRollout(t, home, "archived_sessions", archived, "magpie", day)
hotPath := cxRollout(t, home, "sessions", hot, "magpie", time.Now())
theirPath := cxRollout(t, home, "sessions", theirs, "custom", day)
db := cxThreadRows(t, home, map[string]string{old: "magpie", archived: "magpie", hot: "magpie", theirs: "custom"})
moved, err := MoveCodexThreads(home, "magpie", "openai")
if err != nil {
t.Fatal(err)
}
if len(moved) != 2 {
t.Fatalf("moved %+v, want the two not written to lately", moved)
}
for _, mv := range moved {
if mv.From != "magpie" || mv.To != "openai" || len(mv.DB) != 1 || mv.Backup == "" {
t.Fatalf("moved %+v", mv)
}
if _, err := os.Stat(filepath.Join(mv.Backup, "move.json")); err != nil {
t.Fatalf("no copy kept: %v", err)
}
}
want := map[string]string{oldPath: "openai", arPath: "openai", hotPath: "magpie", theirPath: "custom"}
for p, prov := range want {
if got := codexMetaProvider(p); got != prov {
t.Errorf("%s: file on %q, want %q", filepath.Base(p), got, prov)
}
if fi, _ := os.Stat(p); p != hotPath && !fi.ModTime().Equal(day) {
t.Errorf("%s: time %v, want %v kept", filepath.Base(p), fi.ModTime(), day)
}
}
for id, prov := range map[string]string{old: "openai", archived: "openai", hot: "magpie", theirs: "custom"} {
if got, _, _ := threadProvider(t, db, id); got != prov {
t.Errorf("row %s on %q, want %q", id, got, prov)
}
}
b, _ := os.ReadFile(oldPath)
if !strings.Contains(string(b), "remember: the build uses make") {
t.Fatalf("the thread's messages went:\n%s", b)
}
// the one written to lately goes once Codex is done with it
hour := time.Now().Add(-time.Hour)
os.Chtimes(hotPath, hour, hour)
if moved, err = MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 1 || moved[0].ID != hot {
t.Fatalf("again: %+v %v", moved, err)
}
if moved, err = MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 0 {
t.Fatalf("a third time: %+v %v", moved, err)
}
}
// A Codex folder with no state database, or none of its threads on the
// provider, is left as it is, with nothing kept in the trash.
func TestMoveCodexThreadsNone(t *testing.T) {
_, home := manageSetup(t)
day := time.Now().Add(-24 * time.Hour)
p := cxRollout(t, home, "sessions", "019a0000-0000-7000-8000-00000000000e", "magpie", day)
if moved, err := MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 0 {
t.Fatalf("no database: %+v %v", moved, err)
}
if got := codexMetaProvider(p); got != "magpie" {
t.Fatalf("file on %q", got)
}
if _, err := MoveCodexThreads(home, "magpie", "magpie"); err == nil {
t.Fatal("a move to the same provider went")
}
}
// bringBack's move (MoveCodexThreads) leaves a thread a Codex has open as
// it leaves one written to in the last minute (#3751): no error, its
// files and row on the provider they were, no copy kept. The others move,
// and that one does once its Codex has let go. A Codex home without
// thread-writer-locks (a Codex from before them) has none to look at: its
// threads move as before, and none is made there.
func TestMoveCodexThreadsLeavesAnOpenThread(t *testing.T) {
_, home := manageSetup(t)
const (
free = "019a0000-0000-7000-8000-0000000000a1"
open = "019a0000-0000-7000-8000-0000000000a2"
)
day := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
cxRollout(t, home, "sessions", free, "magpie", day)
openPath := cxRollout(t, home, "sessions", open, "magpie", day)
db := cxThreadRows(t, home, map[string]string{free: "magpie", open: "magpie"})
orig, _ := os.ReadFile(openPath)
_, letGo := holdThread(t, home, open)
moved, err := MoveCodexThreads(home, "magpie", "openai")
if err != nil || len(moved) != 1 || moved[0].ID != free {
t.Fatalf("moved %+v, %v; want %s alone", moved, err, free)
}
if b, _ := os.ReadFile(openPath); !bytes.Equal(b, orig) {
t.Fatal("moved while a Codex had it open")
}
if got, _, _ := threadProvider(t, db, open); got != "magpie" {
t.Errorf("its row moved to %q, its files didn't", got)
}
if kept := providerTrash(t); len(kept) != 1 {
t.Errorf("copies kept: %v, want the moved thread's alone", kept)
}
letGo()
if moved, err = MoveCodexThreads(home, "magpie", "openai"); err != nil || len(moved) != 1 || moved[0].ID != open {
t.Fatalf("after its Codex let go: %+v %v", moved, err)
}
if got := codexMetaProvider(openPath); got != "openai" {
t.Errorf("file on %q", got)
}
if got, _, _ := threadProvider(t, db, open); got != "openai" {
t.Errorf("row on %q", got)
}
old := filepath.Join(t.TempDir(), ".codex")
p := cxRollout(t, old, "sessions", free, "magpie", day)
cxThreadRows(t, old, map[string]string{free: "magpie"})
if moved, err := MoveCodexThreads(old, "magpie", "openai"); err != nil || len(moved) != 1 {
t.Fatalf("a home without writer locks: %+v %v", moved, err)
}
if got := codexMetaProvider(p); got != "openai" {
t.Errorf("file on %q in a home without writer locks", got)
}
if _, err := os.Stat(filepath.Join(old, "thread-writer-locks")); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("thread-writer-locks made where Codex keeps none: %v", err)
}
}