diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 5add9467f..d02aa0c74 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -13,6 +13,8 @@ import ( "slices" "strconv" "strings" + "sync" + satomic "sync/atomic" "time" "github.com/pelletier/go-toml/v2" @@ -1869,13 +1871,72 @@ func codexChatGPT(dir string) bool { // newest day of it at most — from the log database the Codex app and the // TUI share: the address it opened, and whether that was refused (nothing // listening there). Zero when none is logged. +// +// Every Drift asks it, so it is read again only when the database or its +// -wal changed, or the day it covers moved past what it found (#1665: a +// read per ask was ~2,500 opens of logs_2.sqlite in 25s of a start, each +// one file system work a Windows filter driver adds its own to). func codexReached(dir string, since time.Time) (at time.Time, to string, refused bool) { logs, _ := filepath.Glob(filepath.Join(dir, "logs_*.sqlite")) if len(logs) == 0 { return } slices.Sort(logs) - db, err := provider.OpenReadOnly(logs[len(logs)-1]) + path := logs[len(logs)-1] + key := reachedKey{path: path, since: since.Unix(), db: stampOf(path), wal: stampOf(path + "-wal")} + reachedMu.Lock() + if c, ok := reachedMemo[dir]; ok && c.key == key && time.Since(c.read) < reachedFor && + (c.at.IsZero() || time.Since(c.at) < 24*time.Hour) { + reachedMu.Unlock() + return c.at, c.to, c.refused + } + reachedMu.Unlock() + at, to, refused = codexReachedRead(path, since) + reachedMu.Lock() + reachedMemo[dir] = reachedRead{key: key, read: time.Now(), at: at, to: to, refused: refused} + reachedMu.Unlock() + return +} + +// reachedFor is how long a read of Codex's log stands while its files say +// nothing changed: a file system whose times are coarse can miss a write +// that kept the size. +const reachedFor = 15 * time.Second + +type reachedKey struct { + path string + since int64 + db, wal fileStamp +} + +type fileStamp struct{ size, mod int64 } + +func stampOf(path string) fileStamp { + fi, err := os.Stat(path) + if err != nil { + return fileStamp{size: -1} + } + return fileStamp{size: fi.Size(), mod: fi.ModTime().UnixNano()} +} + +type reachedRead struct { + key reachedKey + read time.Time + at time.Time + to string + refused bool +} + +var ( + reachedMu sync.Mutex + reachedMemo = map[string]reachedRead{} + // reachedOpens counts the reads of the database, for the tests + reachedOpens satomic.Int64 +) + +func codexReachedRead(path string, since time.Time) (at time.Time, to string, refused bool) { + reachedOpens.Add(1) + db, err := provider.OpenReadOnly(path) if err != nil { return } diff --git a/internal/agent/codex_reached_test.go b/internal/agent/codex_reached_test.go new file mode 100644 index 000000000..cd57004cb --- /dev/null +++ b/internal/agent/codex_reached_test.go @@ -0,0 +1,66 @@ +package agent + +import ( + "database/sql" + "os" + "path/filepath" + "testing" + "time" +) + +// #1665: Drift asks where Codex's requests went on every poll, and each ask +// opened logs_*.sqlite again (~2,500 opens in 25s of a start on Windows, +// each one work a filter driver multiplies). The log is read again only +// once it changed; asked again meanwhile, the answer is the one read. +func TestCodexReachedReadsLogOnlyWhenItChanged(t *testing.T) { + home, _ := codexHome(t, "", "") + dir := filepath.Join(home, ".codex") + os.MkdirAll(dir, 0o700) + db, err := sql.Open("sqlite", filepath.Join(dir, "logs_2.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec(`PRAGMA journal_mode=WAL`); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`CREATE TABLE logs (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, ts_nanos INTEGER NOT NULL, + level TEXT NOT NULL, target TEXT NOT NULL, feedback_log_body TEXT)`); err != nil { + t.Fatal(err) + } + at := time.Now().Add(-time.Minute).Unix() + log := func(url string) { + at++ + if _, err := db.Exec(`INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body) VALUES (?, 0, 'INFO', 'codex_api::endpoint::responses_websocket', ?)`, + at, "responses_websocket.connect{}: connecting to websocket: "+url); err != nil { + t.Fatal(err) + } + } + log("ws://127.0.0.1:3425/backend-api/codex/responses") + since := time.Now().Add(-time.Hour) + + before := reachedOpens.Load() + for range 50 { + got, to, _ := codexReached(dir, since) + if got.Unix() != at || to != "ws://127.0.0.1:3425/backend-api/codex/responses" { + t.Fatalf("read %v %q, want %v and magpie's address", got, to, at) + } + } + if n := reachedOpens.Load() - before; n != 1 { + t.Fatalf("50 asks read the log %d times, want 1", n) + } + + // a new request logged is read on the next ask + log("wss://chatgpt.com/backend-api/codex/responses") + if got, to, _ := codexReached(dir, since); got.Unix() != at || to != "wss://chatgpt.com/backend-api/codex/responses" { + t.Fatalf("after a new request: %v %q", got, to) + } + if n := reachedOpens.Load() - before; n != 2 { + t.Fatalf("the log read %d times, want 2 once it changed", n) + } + + // asked from a later time, the answer is read for that time + if got, _, _ := codexReached(dir, time.Now().Add(time.Minute)); !got.IsZero() { + t.Fatalf("since after every request: %v", got) + } +}