diff --git a/internal/sessions/cursor.go b/internal/sessions/cursor.go index b108e4f4b..ca4358960 100644 --- a/internal/sessions/cursor.go +++ b/internal/sessions/cursor.go @@ -179,7 +179,8 @@ func cursorParentOf(f file) string { // in -shm when they are; both would change the folder and make the chat // look written to a moment ago. A store with no log to replay is opened // immutable, which touches nothing; one with a log is read from a copy of -// the two files, in a folder of magpie's own that close removes. +// the two files, in a folder of magpie's own that close removes; a large +// store's copy is shared while it is unchanged (cursor_snapshot.go). func openCursorStore(path string) (db *sql.DB, closeDB func(), err error) { open := func(p, query string) (*sql.DB, error) { u := url.URL{Scheme: "file", Path: filepath.ToSlash(p), RawQuery: query} @@ -203,24 +204,14 @@ func openCursorStore(path string) (db *sql.DB, closeDB func(), err error) { } return db, func() { db.Close() }, nil } - tmp, err := os.MkdirTemp("", "magpie-cursor-") + if stamp, size, ok := cursorStamp(path); ok && size >= cursorSnapMin { + return sharedCursorStore(path, stamp, open) + } + db, tmp, err := snapshotCursorStore(path, open) if err != nil { return nil, nil, err } - gone := func() { os.RemoveAll(tmp) } - copied := filepath.Join(tmp, "store.db") - for _, side := range []string{"", "-wal"} { - if err := copyFile(path+side, copied+side); err != nil { - gone() - return nil, nil, err - } - } - db, err = open(copied, "_pragma=busy_timeout(3000)") - if err != nil { - gone() - return nil, nil, err - } - return db, func() { db.Close(); gone() }, nil + return db, func() { db.Close(); os.RemoveAll(tmp) }, nil } func copyFile(from, to string) error { diff --git a/internal/sessions/cursor_clone_darwin.go b/internal/sessions/cursor_clone_darwin.go new file mode 100644 index 000000000..5e60f9810 --- /dev/null +++ b/internal/sessions/cursor_clone_darwin.go @@ -0,0 +1,10 @@ +//go:build darwin + +package sessions + +import "golang.org/x/sys/unix" + +// cloneFile makes to share from's blocks on APFS, so a snapshot of a +// multi-GB Cursor database costs no disk until one side is written. It +// fails off APFS or across volumes, and the caller then copies. +func cloneFile(from, to string) error { return unix.Clonefile(from, to, unix.CLONE_NOFOLLOW) } diff --git a/internal/sessions/cursor_clone_other.go b/internal/sessions/cursor_clone_other.go new file mode 100644 index 000000000..bf4f566e5 --- /dev/null +++ b/internal/sessions/cursor_clone_other.go @@ -0,0 +1,7 @@ +//go:build !darwin + +package sessions + +import "errors" + +func cloneFile(from, to string) error { return errors.ErrUnsupported } diff --git a/internal/sessions/cursor_snapshot.go b/internal/sessions/cursor_snapshot.go new file mode 100644 index 000000000..7b1949ce5 --- /dev/null +++ b/internal/sessions/cursor_snapshot.go @@ -0,0 +1,158 @@ +package sessions + +import ( + "database/sql" + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" +) + +// A Cursor store with a live -wal is read from a copy (see openCursorStore). +// Cursor's editor keeps every chat in one state.vscdb, often several GB, and +// a listing, the stats, the manage page, a transcript and a search over its +// chats each opened it again, so one visit to Sessions wrote the whole file +// to the temp folder five or more times (#1988). A copy of a large store is +// now kept while the store and its -wal are unchanged and shared by every +// reader, and is removed cursorSnapLinger after its last reader lets go. +var ( + cursorSnapLinger = 30 * time.Second + cursorSnapMin int64 = 16 << 20 + // a magpie-cursor-* folder older than this is a copy a killed magpie + // left behind; a shared copy in use is touched on every reuse + cursorSnapStale = time.Hour + cursorCopies atomic.Int64 +) + +type cursorSnap struct { + path, dir, stamp string + db *sql.DB + users int + last time.Time + gone bool +} + +var cursorSnaps struct { + sync.Mutex + m map[string]*cursorSnap + sweep sync.Once +} + +// cursorStamp names a store's state by its and its -wal's size and time. +func cursorStamp(path string) (stamp string, size int64, ok bool) { + for _, side := range []string{"", "-wal"} { + fi, err := os.Stat(path + side) + if err != nil { + return "", 0, false + } + stamp += fmt.Sprintf("%d/%d;", fi.Size(), fi.ModTime().UnixNano()) + size += fi.Size() + } + return stamp, size, true +} + +// sharedCursorStore hands out the kept copy of path while stamp still +// matches, and makes one otherwise. +func sharedCursorStore(path, stamp string, open func(string, string) (*sql.DB, error)) (*sql.DB, func(), error) { + cursorSnaps.Lock() + defer cursorSnaps.Unlock() + if s := cursorSnaps.m[path]; s != nil { + if s.stamp == stamp { + s.users++ + now := time.Now() + os.Chtimes(s.dir, now, now) + return s.db, s.release(), nil + } + delete(cursorSnaps.m, path) + s.gone = true + if s.users == 0 { + s.drop() + } + } + db, dir, err := snapshotCursorStore(path, open) + if err != nil { + return nil, nil, err + } + s := &cursorSnap{path: path, dir: dir, stamp: stamp, db: db, users: 1} + if cursorSnaps.m == nil { + cursorSnaps.m = map[string]*cursorSnap{} + } + cursorSnaps.m[path] = s + return db, s.release(), nil +} + +func (s *cursorSnap) release() func() { + var once sync.Once + return func() { + once.Do(func() { + cursorSnaps.Lock() + defer cursorSnaps.Unlock() + s.users-- + s.last = time.Now() + if s.users > 0 { + return + } + if s.gone { + s.drop() + return + } + time.AfterFunc(cursorSnapLinger, func() { + cursorSnaps.Lock() + defer cursorSnaps.Unlock() + if s.gone || s.users > 0 || time.Since(s.last) < cursorSnapLinger { + return + } + if cursorSnaps.m[s.path] == s { + delete(cursorSnaps.m, s.path) + } + s.gone = true + s.drop() + }) + }) + } +} + +func (s *cursorSnap) drop() { + s.db.Close() + os.RemoveAll(s.dir) +} + +// snapshotCursorStore copies path and its -wal into a folder of magpie's +// own, cloning where the file system can so the copy takes no space. +func snapshotCursorStore(path string, open func(string, string) (*sql.DB, error)) (*sql.DB, string, error) { + cursorSnaps.sweep.Do(sweepCursorSnaps) + tmp, err := os.MkdirTemp("", "magpie-cursor-") + if err != nil { + return nil, "", err + } + copied := filepath.Join(tmp, "store.db") + for _, side := range []string{"", "-wal"} { + if cloneFile(path+side, copied+side) == nil { + continue + } + os.Remove(copied + side) + if err := copyFile(path+side, copied+side); err != nil { + os.RemoveAll(tmp) + return nil, "", err + } + } + cursorCopies.Add(1) + db, err := open(copied, "_pragma=busy_timeout(3000)") + if err != nil { + os.RemoveAll(tmp) + return nil, "", err + } + return db, tmp, nil +} + +// sweepCursorSnaps removes copies an earlier magpie was killed holding. +func sweepCursorSnaps() { + old, _ := filepath.Glob(filepath.Join(os.TempDir(), "magpie-cursor-*")) + for _, d := range old { + if fi, err := os.Stat(d); err == nil && fi.IsDir() && time.Since(fi.ModTime()) > cursorSnapStale { + os.RemoveAll(d) + } + } +} diff --git a/internal/sessions/cursor_snapshot_test.go b/internal/sessions/cursor_snapshot_test.go new file mode 100644 index 000000000..bf65d9219 --- /dev/null +++ b/internal/sessions/cursor_snapshot_test.go @@ -0,0 +1,136 @@ +package sessions + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +func cursorTempCopies(t *testing.T) []string { + t.Helper() + d, _ := filepath.Glob(filepath.Join(os.TempDir(), "magpie-cursor-*")) + return d +} + +// #1988: Cursor's state.vscdb is often several GB. Every listing, count, +// transcript and search read it from a fresh copy in the temp folder, so a +// visit to Sessions wrote it out again and again. Reads of an unchanged +// store share one copy, a change makes one new copy, and nothing is left. +func TestCursorEditorCopiedOncePerChange(t *testing.T) { + cursorSetup(t) + t.Setenv("TMPDIR", t.TempDir()) + minWas, lingerWas := cursorSnapMin, cursorSnapLinger + cursorSnapMin, cursorSnapLinger = 0, 100*time.Millisecond + t.Cleanup(func() { cursorSnapMin, cursorSnapLinger = minWas, lingerWas }) + + config, err := os.UserConfigDir() + if err != nil { + t.Fatal(err) + } + p := filepath.Join(config, "Cursor", "User", "globalStorage", "state.vscdb") + if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { + t.Fatal(err) + } + db, err := sql.Open("sqlite", p) + if err != nil { + t.Fatal(err) + } + db.SetMaxOpenConns(1) + defer db.Close() + for _, q := range []string{"PRAGMA journal_mode=WAL", "PRAGMA wal_autocheckpoint=0", "CREATE TABLE cursorDiskKV (key TEXT PRIMARY KEY, value BLOB)"} { + if _, err := db.Exec(q); err != nil { + t.Fatal(err) + } + } + put := func(k string, v any) { + b, _ := json.Marshal(v) + if _, err := db.Exec("INSERT OR REPLACE INTO cursorDiskKV VALUES (?,?)", k, b); err != nil { + t.Fatal(err) + } + } + at := time.Now().Add(-time.Hour) + var ids []string + for i := range 6 { + id := fmt.Sprintf("0000000%d-1111-2222-3333-444444444444", i) + ids = append(ids, id) + put("composerData:"+id, map[string]any{"composerId": id, "name": "Chat " + id[:8], "createdAt": at.UnixMilli(), "lastUpdatedAt": at.Add(time.Minute).UnixMilli(), "fullConversationHeadersOnly": []any{map[string]any{"bubbleId": "u"}, map[string]any{"bubbleId": "a"}}}) + put("bubbleId:"+id+":u", map[string]any{"type": 1, "text": "question " + id, "createdAt": at.Format(time.RFC3339Nano)}) + put("bubbleId:"+id+":a", map[string]any{"type": 2, "text": "answer", "createdAt": at.Add(time.Minute).Format(time.RFC3339Nano)}) + } + if fi, err := os.Stat(p + "-wal"); err != nil || fi.Size() == 0 { + t.Fatalf("fixture has no live -wal: %v", err) + } + + // a visit to Sessions: the list, the counts, each chat, a search + visit := func() { + ss := List(All) + Agents() + for _, id := range ids { + s, ok := findSession(ss, "cursor", id) + if !ok { + t.Fatalf("chat %s not listed", id) + } + if tr, err := TranscriptOf(s); err != nil || len(tr.Parts) != 2 { + t.Fatalf("transcript %+v: %v", tr, err) + } + if _, _, err := SearchSession(context.Background(), s, "nothing like this"); err != nil { + t.Fatal(err) + } + } + } + before := cursorCopies.Load() + visit() + visit() + if n := cursorCopies.Load() - before; n != 1 { + t.Fatalf("an unchanged state.vscdb was copied %d times, want 1", n) + } + + put("composerData:"+ids[0], map[string]any{"composerId": ids[0], "name": "Renamed", "createdAt": at.UnixMilli(), "lastUpdatedAt": at.Add(2 * time.Minute).UnixMilli(), "fullConversationHeadersOnly": []any{map[string]any{"bubbleId": "u"}, map[string]any{"bubbleId": "a"}}}) + if s := find(t, List(All), "cursor", ids[0]); s.Title != "Renamed" { + t.Fatalf("a change to the store wasn't read: %q", s.Title) + } + visit() + if n := cursorCopies.Load() - before; n != 2 { + t.Fatalf("copies after one change: %d, want 2", n) + } + + deadline := time.Now().Add(5 * time.Second) + for len(cursorTempCopies(t)) > 0 { + if time.Now().After(deadline) { + t.Fatalf("copies left in the temp folder: %v", cursorTempCopies(t)) + } + time.Sleep(20 * time.Millisecond) + } +} + +// A copy left by a magpie that was killed mid-read is removed; one a +// running magpie made a moment ago is not. +func TestCursorLeftCopiesSwept(t *testing.T) { + t.Setenv("TMPDIR", t.TempDir()) + left := filepath.Join(os.TempDir(), "magpie-cursor-left") + fresh := filepath.Join(os.TempDir(), "magpie-cursor-fresh") + for _, d := range []string{left, fresh} { + if err := os.MkdirAll(d, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(d, "store.db"), make([]byte, 1024), 0600); err != nil { + t.Fatal(err) + } + } + old := time.Now().Add(-2 * cursorSnapStale) + if err := os.Chtimes(left, old, old); err != nil { + t.Fatal(err) + } + sweepCursorSnaps() + if _, err := os.Stat(left); !os.IsNotExist(err) { + t.Fatalf("a left copy is still there: %v", err) + } + if _, err := os.Stat(fresh); err != nil { + t.Fatalf("a copy in use was removed: %v", err) + } +}