diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 3886ad132..b0b67ea8b 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -404,15 +404,21 @@ its search would go on finding: `grokSearchRowsDrop` deletes the session's row and its subagents', waiting on Grok's own write lock (`BEGIN IMMEDIATE`, busy timeout 5 s), before any file is moved. A row that can't be taken out stops the delete, so the session stays whole rather than -half gone; no index, or one without those tables, deletes as before. Restore -brings the folder back; the row isn't put back, so Grok Build's search finds -the restored session again only if Grok Build indexes the folder again. +half gone; no index, or one without those tables, deletes as before. The rows +are kept, every column as Grok Build had them, in the trash entry's +`grok_search.json` (not in the note the Trash page lists, the text can be +large); Restore puts them back (`INSERT OR IGNORE`, so a row Grok Build wrote +again meanwhile is kept, and an index that can't be written doesn't stop the +restore), and a delete that fails after dropping them puts them back too. Implementation: [`grok_search.go`](../../internal/sessions/grok_search.go), the `grok` branch of `sessionPaths` and `Delete` in [`manage.go`](../../internal/sessions/manage.go); tests `TestGrokDeleteRestore`, `TestGrokDeleteLeavesTheSessionWhenItsIndexRowCantGo`, -`TestGrokSearchRowsDrop` and `TestGrokSessionDeleteOnThePage`. +`TestGrokSearchRowsDrop`, `TestGrokSearchRowsComeBackWhole` and +`TestGrokSessionDeleteOnThePage`. The schema (session_docs: session_id, cwd, +updated_at, title, content, content_hash; some versions add an offset column) +was read from Grok Build 1.0.67's own index and binary. A deleted Codex session also leaves the Codex app's list (zhuddan on Discord). The app (ChatGPT.app's Codex, 26.x) lists threads from its own catalog, `/sqlite/codex.db` (`codex-dev.db` for a non-prod build), table diff --git a/internal/sessions/grok_delete_test.go b/internal/sessions/grok_delete_test.go index 592eec6b0..6c6322daa 100644 --- a/internal/sessions/grok_delete_test.go +++ b/internal/sessions/grok_delete_test.go @@ -209,6 +209,13 @@ func TestGrokDeleteRestore(t *testing.T) { t.Fatalf("%s isn't back: %v", p, err) } } + // the index has its rows again, its search finds them, and the other + // session's is not doubled + for id, word := range map[string]string{grokMain: grokWordMain, grokSub: grokWordSub, grokFork: grokWordFork} { + if rows, found := grokSearchCount(t, index, id, word); rows != 1 || found != 1 { + t.Fatalf("%s after the restore: %d rows and %d found, want 1 and 1", id, rows, found) + } + } Reset() if back, ok := findManaged(ListAgent("grok"), grokMain); !ok || back.Title != m.Title || !back.Deletable { t.Fatalf("the restored session: %+v", back) @@ -274,13 +281,13 @@ func TestGrokSearchRowsDrop(t *testing.T) { } // no index: a Grok Build that never searched deletes as before - if err := grokSearchRowsDrop([]string{grokMain}); err != nil { + if _, err := grokSearchRowsDrop([]string{grokMain}); err != nil { t.Fatalf("no index: %v", err) } index := grokSearchDB() grokSearchMake(t, index, [][2]string{{grokMain, grokWordMain}, {grokFork, grokWordFork}}) - if err := grokSearchRowsDrop([]string{grokMain}); err != nil { + if _, err := grokSearchRowsDrop([]string{grokMain}); err != nil { t.Fatal(err) } if rows, found := grokSearchCount(t, index, grokMain, grokWordMain); rows != 0 || found != 0 { @@ -290,7 +297,7 @@ func TestGrokSearchRowsDrop(t *testing.T) { t.Fatalf("the other session: %d rows, %d found", rows, found) } // nothing of it left to take out is not an error - if err := grokSearchRowsDrop([]string{grokMain}); err != nil { + if _, err := grokSearchRowsDrop([]string{grokMain}); err != nil { t.Fatalf("already gone: %v", err) } @@ -307,7 +314,54 @@ func TestGrokSearchRowsDrop(t *testing.T) { if err := os.Rename(bare, index); err != nil { t.Fatal(err) } - if err := grokSearchRowsDrop([]string{grokMain}); err != nil { + if _, err := grokSearchRowsDrop([]string{grokMain}); err != nil { t.Fatalf("no tables: %v", err) } } + +// A session's index rows come back whole with it: every column, the offset +// Grok Build keeps too, and a row Grok Build wrote again meanwhile is not +// written over. +func TestGrokSearchRowsComeBackWhole(t *testing.T) { + home := t.TempDir() + t.Setenv("GROK_HOME", filepath.Join(home, ".grok")) + index := grokSearchDB() + grokSearchMake(t, index, [][2]string{{grokMain, grokWordMain}, {grokFork, grokWordFork}}) + db, err := sql.Open("sqlite", sqliteURL(index, "_pragma=busy_timeout(2000)")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec(`UPDATE session_docs SET last_indexed_offset = 4242, content_hash = 'h1' WHERE session_id = ?`, grokMain); err != nil { + t.Fatal(err) + } + rows, err := grokSearchRowsDrop([]string{grokMain}) + if err != nil || len(rows) != 1 { + t.Fatalf("dropped %v, %v", rows, err) + } + dir := t.TempDir() + if err := grokSearchKeep(dir, rows); err != nil { + t.Fatal(err) + } + if err := grokSearchPut(grokSearchKept(dir)); err != nil { + t.Fatal(err) + } + var off int + var hash string + if err := db.QueryRow(`SELECT last_indexed_offset, content_hash FROM session_docs WHERE session_id = ?`, grokMain).Scan(&off, &hash); err != nil || off != 4242 || hash != "h1" { + t.Fatalf("row back as %d %q, %v", off, hash, err) + } + if r, f := grokSearchCount(t, index, grokMain, grokWordMain); r != 1 || f != 1 { + t.Fatalf("%d rows, %d found", r, f) + } + // Grok Build indexed it again first: its row stays + if _, err := db.Exec(`UPDATE session_docs SET content_hash = 'newer' WHERE session_id = ?`, grokMain); err != nil { + t.Fatal(err) + } + if err := grokSearchPut(grokSearchKept(dir)); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT content_hash FROM session_docs WHERE session_id = ?`, grokMain).Scan(&hash); err != nil || hash != "newer" { + t.Fatalf("restore wrote over %q, %v", hash, err) + } +} diff --git a/internal/sessions/grok_search.go b/internal/sessions/grok_search.go index 4a7c4f4cb..5f2834a35 100644 --- a/internal/sessions/grok_search.go +++ b/internal/sessions/grok_search.go @@ -3,8 +3,10 @@ package sessions import ( "context" "database/sql" + "encoding/json" "os" "path/filepath" + "strings" ) // Grok Build keeps a search index of its own beside the sessions it reads: @@ -28,49 +30,184 @@ func grokSearchDB() string { return filepath.Join(GrokDir(), "sessions", "session_search.sqlite") } +// grokSearchRow is one dropped row of session_docs as the index had it, every +// column by name, so Restore puts back what was there whatever columns this +// Grok Build's version keeps (1.0.67 has six; a later one may add more). +type grokSearchRow struct { + Cols []string `json:"cols"` + Vals []any `json:"vals"` +} + +// grokSearchFile is where a trashed session's dropped rows are kept, beside +// its note. Their text can be large, so they are not in the note the Trash +// page lists. +const grokSearchFile = "grok_search.json" + // grokSearchRowsDrop takes the given sessions' rows out of Grok Build's -// search index, their FTS entries going with them through session_docs_ad. -// It runs before any of a session's files are moved, and its error stops -// the delete: a session still listed with its text still searchable is -// whole, where a folder moved out from under its row is not. -func grokSearchRowsDrop(ids []string) error { +// search index, their FTS entries going with them through session_docs_ad, +// and returns them so a restore can put them back. It runs before any of a +// session's files are moved, and its error stops the delete: a session still +// listed with its text still searchable is whole, where a folder moved out +// from under its row is not. +func grokSearchRowsDrop(ids []string) ([]grokSearchRow, error) { if len(ids) == 0 { - return nil + return nil, nil } path := grokSearchDB() if fi, err := os.Stat(path); err != nil || !fi.Mode().IsRegular() { - return nil + return nil, nil } - db, err := sql.Open("sqlite", sqliteURL(path, "_pragma=busy_timeout(5000)")) + conn, closeDB, err := grokSearchOpen(path) if err != nil { - return err + return nil, err } - defer db.Close() + defer closeDB() ctx := context.Background() - conn, err := db.Conn(ctx) - if err != nil { - return err - } - defer conn.Close() // a Grok Build that keeps no such tables: nothing to do var n int if err := conn.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name IN ('session_docs', 'session_docs_fts')`).Scan(&n); err != nil || n != 2 { - return err + return nil, err } // Grok Build may be indexing a session while the page deletes it: the // write lock is taken first, so this waits for its own write (up to the // busy timeout) instead of failing at once, and the rows taken are the // rows the index has when the delete goes through if _, err := conn.ExecContext(ctx, `BEGIN IMMEDIATE`); err != nil { + return nil, err + } + var took []grokSearchRow + for _, id := range ids { + rows, err := grokSearchRead(ctx, conn, id) + if err == nil { + _, err = conn.ExecContext(ctx, `DELETE FROM session_docs WHERE session_id = ?`, id) + } + if err != nil { + conn.ExecContext(ctx, `ROLLBACK`) + return nil, err + } + took = append(took, rows...) + } + if _, err := conn.ExecContext(ctx, `COMMIT`); err != nil { + conn.ExecContext(ctx, `ROLLBACK`) + return nil, err + } + return took, nil +} + +func grokSearchOpen(path string) (*sql.Conn, func(), error) { + db, err := sql.Open("sqlite", sqliteURL(path, "_pragma=busy_timeout(5000)")) + if err != nil { + return nil, nil, err + } + conn, err := db.Conn(context.Background()) + if err != nil { + db.Close() + return nil, nil, err + } + return conn, func() { conn.Close(); db.Close() }, nil +} + +// grokSearchRead is the rows session_docs has of one session, whole. +func grokSearchRead(ctx context.Context, conn *sql.Conn, id string) ([]grokSearchRow, error) { + r, err := conn.QueryContext(ctx, `SELECT * FROM session_docs WHERE session_id = ?`, id) + if err != nil { + return nil, err + } + defer r.Close() + cols, err := r.Columns() + if err != nil { + return nil, err + } + var out []grokSearchRow + for r.Next() { + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + if err := r.Scan(ptrs...); err != nil { + return nil, err + } + for i, v := range vals { + if b, ok := v.([]byte); ok { + vals[i] = string(b) + } + } + out = append(out, grokSearchRow{Cols: cols, Vals: vals}) + } + return out, r.Err() +} + +// grokSearchPut puts dropped rows back into the index, the FTS entries +// following through session_docs_ai. A row the index has again by then +// (Grok Build indexed the session in the meantime) is left as it is, and +// the index being gone, unreadable or of another shape is not an error a +// restore stops on: the session is whole either way. +func grokSearchPut(rows []grokSearchRow) error { + if len(rows) == 0 { + return nil + } + path := grokSearchDB() + if fi, err := os.Stat(path); err != nil || !fi.Mode().IsRegular() { + return nil + } + conn, closeDB, err := grokSearchOpen(path) + if err != nil { return err } - for _, id := range ids { - if _, err := conn.ExecContext(ctx, `DELETE FROM session_docs WHERE session_id = ?`, id); err != nil { + defer closeDB() + ctx := context.Background() + if _, err := conn.ExecContext(ctx, `BEGIN IMMEDIATE`); err != nil { + return err + } + for _, r := range rows { + if len(r.Cols) == 0 || len(r.Cols) != len(r.Vals) { + continue + } + marks := strings.TrimSuffix(strings.Repeat("?,", len(r.Cols)), ",") + quoted := make([]string, len(r.Cols)) + for i, c := range r.Cols { + quoted[i] = `"` + strings.ReplaceAll(c, `"`, `""`) + `"` + } + q := `INSERT OR IGNORE INTO session_docs (` + strings.Join(quoted, ", ") + `) VALUES (` + marks + `)` + if _, err := conn.ExecContext(ctx, q, r.Vals...); err != nil { conn.ExecContext(ctx, `ROLLBACK`) return err } } - _, err = conn.ExecContext(ctx, `COMMIT`) - return err + if _, err := conn.ExecContext(ctx, `COMMIT`); err != nil { + conn.ExecContext(ctx, `ROLLBACK`) + return err + } + return nil +} + +// grokSearchKeep writes the dropped rows into the trash folder dir. +func grokSearchKeep(dir string, rows []grokSearchRow) error { + if len(rows) == 0 { + return nil + } + b, err := json.Marshal(rows) + if err != nil { + return err + } + tmp := filepath.Join(dir, grokSearchFile+".tmp") + if err := os.WriteFile(tmp, b, 0o600); err != nil { + return err + } + return os.Rename(tmp, filepath.Join(dir, grokSearchFile)) +} + +// grokSearchKept reads them again; none kept (or unreadable) is none. +func grokSearchKept(dir string) []grokSearchRow { + b, err := os.ReadFile(filepath.Join(dir, grokSearchFile)) + if err != nil { + return nil + } + var rows []grokSearchRow + if json.Unmarshal(b, &rows) != nil { + return nil + } + return rows } diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index 1e28b2901..74b70a5c0 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -38,9 +38,8 @@ import ( // agy's conversation_summaries.db and jetbox_summaries_proto.pb, // which it keeps open, keep the row, and agy lists no conversation whose // files are gone, as a restore brings it back to its /resume list. A -// restored Grok Build session is whole again; its row does not come back -// with it, so Grok Build's search finds it only once Grok Build has indexed -// the folder again. +// restored Grok Build session is whole again, and the index rows it dropped +// (kept whole in the trash entry's grok_search.json) go back with it. // Hermes's, Alma's and OpenMausBot's are rows in a database the agent keeps open and // writes, so they are only listed, and so are OpenCode's and ZCode's, and // Cline's, whose sessions.db lists a session whose files are gone. Kimi Code's are @@ -551,16 +550,26 @@ func Delete(agent, id string) (Trashed, error) { // going, a subagent's under its own id: those rows go before a file // does, so a delete that can't take them out moves nothing and the // session is whole rather than gone from the list and found by search + var grokRows []grokSearchRow if agent == "grok" { - if err := grokSearchRowsDrop(append([]string{id}, subIDs(fs, id)...)); err != nil { + var err error + if grokRows, err = grokSearchRowsDrop(append([]string{id}, subIDs(fs, id)...)); err != nil { return Trashed{}, err } } + // a delete that stops after that puts the rows back + undone := func() { grokSearchPut(grokRows) } t := Trashed{Agent: agent, ID: id, Title: s.Title, Cwd: s.Cwd, Last: s.Last, Deleted: now} name := now.UTC().Format("20060102T150405.000000000") + "-" + id dir := filepath.Join(TrashDir(), agent, name) t.Key = agent + "/" + name if err := os.MkdirAll(filepath.Join(dir, "files"), 0o700); err != nil { + undone() + return Trashed{}, err + } + if err := grokSearchKeep(dir, grokRows); err != nil { + os.RemoveAll(dir) + undone() return Trashed{}, err } for i, p := range paths { @@ -572,6 +581,7 @@ func Delete(agent, id string) (Trashed, error) { move(filepath.Join(dir, "files", back.Name), back.From) } os.RemoveAll(dir) + undone() return Trashed{}, err } t.Items = append(t.Items, m) @@ -962,6 +972,10 @@ func Restore(key string) (Trashed, error) { if t.Agent == "codex" && len(t.CodexCatalog) > 0 { restoreCodexCatalog(t.CodexCatalog) } + // Grok Build's search finds it again + if t.Agent == "grok" { + grokSearchPut(grokSearchKept(dir)) + } os.RemoveAll(dir) wslRelistNow(t.Items) return t, nil