diff --git a/internal/agent/applied.go b/internal/agent/applied.go index 17ddce797..2586ebe12 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -2,6 +2,7 @@ package agent import ( "bufio" + "bytes" "encoding/json" "fmt" "log" @@ -13,7 +14,7 @@ import ( "sync" "time" - "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/provider" @@ -266,11 +267,15 @@ func (a *Agent) theInstalled() bool { if !elsewhere() || a.Path == "" { return false } - b, err := edit.Read(a.Path) + // the bytes filememo keeps, looked at in place: a copy of the file and + // two strings of it for each field's drift was 5 MB a poll of a Codex + // config.toml of 1.5 MB, in a magpie beside the installed one (a dev + // build) + b, err := filememo.Read("bytes", a.Path, func(b []byte) ([]byte, error) { return b, nil }) if err != nil { return false } - return strings.Contains(string(b), hostOf(installedURL())) && !strings.Contains(string(b), hostOf(gateway.URL())) + return bytes.Contains(b, []byte(hostOf(installedURL()))) && !bytes.Contains(b, []byte(hostOf(gateway.URL()))) } // bypassed: the agent was used — while this gateway was up and after magpie diff --git a/internal/agent/applied_test.go b/internal/agent/applied_test.go index 0c3a57f33..fd95456e3 100644 --- a/internal/agent/applied_test.go +++ b/internal/agent/applied_test.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path/filepath" + "runtime" "strings" "testing" "time" @@ -306,3 +307,35 @@ func TestDriftInstalledMagpie(t *testing.T) { t.Fatalf("wired to neither: %+v", d) } } + +// Whether the installed magpie wired the agent is looked up in the bytes +// already read, not in a copy of the file and two strings of it: each +// field's drift asked, 5 MB a poll of a Codex config.toml of 1.5 MB. +func TestInstalledWiringReadsNoCopy(t *testing.T) { + t.Setenv("MAGPIE_ADDR", "127.0.0.1:3426") + home, _ := codexHome(t, "", "") + cx := codex(home) + var cfg strings.Builder + cfg.WriteString("openai_base_url = \"http://" + gateway.DefaultAddr + gateway.CodexPath + "\"\nmodel = \"fake/m1\"\n") + for i := range 20000 { + fmt.Fprintf(&cfg, "[projects.\"/Users/someone/work/project-%05d\"]\ntrust_level = \"trusted\"\n", i) + } + path := filepath.Join(home, ".codex", "config.toml") + if err := os.WriteFile(path, []byte(cfg.String()), 0o644); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-time.Hour) + os.Chtimes(path, old, old) + if !cx.theInstalled() { + t.Fatal("the installed magpie's wiring not seen") + } + var m0, m1 runtime.MemStats + runtime.ReadMemStats(&m0) + for range 10 { + cx.theInstalled() + } + runtime.ReadMemStats(&m1) + if n := m1.TotalAlloc - m0.TotalAlloc; n > 1<<20 { + t.Fatalf("10 looks at an unchanged config allocated %d bytes", n) + } +}