Files
magpie/internal/sessions/codex_provider_test.go
T
yetone 67b12956ac sessions: a Codex rollout magpie rewrites keeps every line where it was
xybio (Discord #feedback): the Codex app often wouldn't reopen recent
threads: "invalid paginated history lineage for <id>: cutoff byte offset
is past the source rollout". Codex 0.162 keeps a fork's place in its
parent by byte (session_meta.history_base.end_byte_offset, checked by
rollout_lineage.rs validate_cutoff_bounds), and its state database keeps
turns and how far it has read by byte too. PortCodexRollouts (since
4896fc3ba, 10-21) wrote magpie's compaction item as Codex's summary
message, and since 79c8667c9 dropped Claude's sealed reasoning: both
shorter lines, so a parent shrank and every fork made before the pass
named a byte past its end.

Now every rewritten line keeps its length (fitLine): a shorter one is
padded with spaces after its JSON, which serde_json skips; a longer one
(a short summary under Codex's prefix) is left as it was in a paginated
rollout, and written as before in a legacy one, where Codex keeps no
place by byte. MoveCodexProvider, the sibling that rewrites session_meta,
pads the same way and refuses a longer provider id for a paginated
rollout. Forks already broken are repaired once per Codex home
(repairLineages): every line kept its count, and Codex names each line's
ordinal, so a fork's end_byte_offset is set again to where its parent's
line end_ordinal_exclusive-1 ends now, in a first line kept as long.

Run, at a47596ea6 plus this change:
- go test -count=1 ./internal/sessions/ ./internal/codexsummary/: ok;
  ./internal/agent/ -run 'Codex|Port|Move|Session': ok.
- gofmt -l internal/ clean; go vet ./internal/sessions/ ./internal/agent/,
  GOOS=windows and GOOS=linux go vet ./internal/sessions/: clean.
- Real, Codex 0.162.1 in a sandbox CODEX_HOME against a local mock
  Responses server that returns a magpie-claude1: reasoning item: codex
  exec made a paginated thread (50877 bytes), app-server thread/fork
  forked it, then a port pass. Old code: the parent went to 70570 bytes
  from 82912 and thread/resume and thread/read of the fork gave the
  reporter's exact error. New code: the parent kept 82912 bytes with no
  magpie-claude1: left, the fork resumed and read, the parent resumed,
  and codex exec resume ran a turn on the fork. A new-code pass over the
  old-code home repaired the fork (82912 -> 70570 in its history_base),
  after which it resumed and read.

Broken by hand:
- fitLine returning the rewrite as it is:
  TestPortCodexRolloutsKeepsBytePlaces red ("lines end at [... 11329],
  were at [... 14362]", the fork's offset past the end),
  TestPortCodexRolloutsLongerLine and TestMoveCodexProviderKeepsBytePlaces
  red.
- repairLineages a no-op: TestPortCodexRolloutsRepairsForks red.

Not tried: the Codex desktop app itself (the app-server it runs was);
a .zst parent against real Codex (the Go tests cover zst ports); Codex in
WSL, which the pass skips as before. The state database's turn offsets
for a parent already shrunk are left as they are; Codex 0.162.1 resumed
and forked such a parent in the sandbox.
2026-10-27 23:33:26 +08:00

221 lines
8.2 KiB
Go

package sessions
import (
"bytes"
"database/sql"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/klauspost/compress/zstd"
_ "modernc.org/sqlite"
)
// 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)
}
}