| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/thintest" |
| 5 | "bytes" |
| 6 | "database/sql" |
| 7 | "io/fs" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "golang.org/x/sys/unix" |
| 16 | _ "modernc.org/sqlite" |
| 17 | ) |
| 18 | |
| 19 | // A coordinator whose init frame differs from the launch policy, or that |
| 20 | // answers under another session, is stopped and the turn fails visibly; |
| 21 | // the next message gets a fresh, valid process. |
| 22 | func TestHeadlessPolicyGuards(t *testing.T) { |
| 23 | env, _, r := localEnv(t) |
| 24 | r.start(t) |
| 25 | s := open(t, env) |
| 26 | for _, word := range []string{"badinit", "othersession"} { |
| 27 | bad := s.send(t, "please "+word) |
| 28 | turn := s.waitTurn(t, bad.Turn.ID, wire.TurnFailed, wire.TurnReplied) |
| 29 | if turn.State != wire.TurnFailed || turn.Reason != "policy_rejected" { |
| 30 | t.Fatalf("%s: turn %s/%s, want failed/policy_rejected", word, turn.State, turn.Reason) |
| 31 | } |
| 32 | ok := s.send(t, "hello again") |
| 33 | s.waitTurn(t, ok.Turn.ID, wire.TurnReplied) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // Copies cannot refresh, so with a turn cap that leaves no room the |
| 38 | // process is rotated before every turn and the session resumes each time. |
| 39 | // The source home's lock is held only while refreshing and staging. |
| 40 | func TestHeadlessCopyRotation(t *testing.T) { |
| 41 | env, _, r := localEnv(t) |
| 42 | r.opts.Claude.MaxTurn = 25*time.Minute - 2*time.Second |
| 43 | r.opts.Claude.Margin = time.Second |
| 44 | r.start(t) |
| 45 | s := open(t, env) |
| 46 | var last wire.Sent |
| 47 | for i := range 3 { |
| 48 | last = s.send(t, "turn "+string(rune('a'+i))) |
| 49 | s.waitTurn(t, last.Turn.ID, wire.TurnReplied) |
| 50 | time.Sleep(1100 * time.Millisecond) |
| 51 | } |
| 52 | if text := s.reply(t, last.Turn.ID).Text; !strings.Contains(text, "Turn 3, resumed session, process turn 1.") { |
| 53 | t.Fatalf("not rotated onto a fresh copy with the same session: %q", text) |
| 54 | } |
| 55 | // While a coordinator process is up, nobody holds the source lock. |
| 56 | bs, err := os.ReadFile(r.cfg.AccountBindingsPath) |
| 57 | if err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | home := filepath.Join(filepath.Dir(filepath.Dir(r.cfg.AccountBindingsPath)), "accounts", "claude-1") |
| 61 | if !bytes.Contains(bs, []byte(home)) { |
| 62 | t.Fatal("unexpected bindings layout") |
| 63 | } |
| 64 | f, err := os.Open(home) |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | defer f.Close() |
| 69 | // A background rotation (this cap leaves the copy about two seconds) |
| 70 | // holds the lock for a moment to refresh and stage; held for the |
| 71 | // session, it would never come free. |
| 72 | deadline := time.Now().Add(3 * time.Second) |
| 73 | for err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil; err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) { |
| 74 | if time.Now().After(deadline) { |
| 75 | t.Fatalf("source home still locked during the session: %v", err) |
| 76 | } |
| 77 | time.Sleep(20 * time.Millisecond) |
| 78 | } |
| 79 | unix.Flock(int(f.Fd()), unix.LOCK_UN) |
| 80 | } |
| 81 | |
| 82 | // No credential bytes reach a frame, an event, the instance database or |
| 83 | // the runner's own state, and no runtime copy outlives its process. |
| 84 | // TestHeadlessPrewarm: when the copy stops covering a turn between |
| 85 | // messages, the runner rotates it in the background, so the next message |
| 86 | // starts on a fresh process that is already up (not cold) and resumes the |
| 87 | // session. |
| 88 | func TestHeadlessPrewarm(t *testing.T) { |
| 89 | env, _, r := localEnv(t) |
| 90 | r.opts.Claude.MaxTurn = 25*time.Minute - 5*time.Second |
| 91 | r.opts.Claude.Margin = time.Second |
| 92 | r.start(t) |
| 93 | s := open(t, env) |
| 94 | first := s.send(t, "hello") |
| 95 | s.waitTurn(t, first.Turn.ID, wire.TurnReplied) |
| 96 | time.Sleep(6 * time.Second) |
| 97 | second := s.send(t, "again") |
| 98 | s.waitTurn(t, second.Turn.ID, wire.TurnReplied) |
| 99 | turn, err := env.Client.Turn(s.ctx, second.Turn.ID) |
| 100 | if err != nil || turn.Timing == nil { |
| 101 | t.Fatalf("turn %+v %v", turn, err) |
| 102 | } |
| 103 | if turn.Timing.Cold { |
| 104 | t.Fatalf("the second turn started cold: %+v", turn.Timing) |
| 105 | } |
| 106 | if text := s.reply(t, second.Turn.ID).Text; !strings.Contains(text, "Turn 2, resumed session, process turn 1.") { |
| 107 | t.Fatalf("not a rotated process on the same session: %q", text) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // TestHeadlessNewHouseRuleStartsFresh: a session started under an older |
| 112 | // house rule is not resumed, so a changed rule reaches the coordinator. |
| 113 | func TestHeadlessNewHouseRuleStartsFresh(t *testing.T) { |
| 114 | env, _, r := localEnv(t) |
| 115 | r.start(t) |
| 116 | s := open(t, env) |
| 117 | first := s.send(t, "hello") |
| 118 | s.waitTurn(t, first.Turn.ID, wire.TurnReplied) |
| 119 | r.stop(t) |
| 120 | db, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db")) |
| 121 | if err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | if _, err = db.Exec("UPDATE sessions_lane SET account = 'claude-1'"); err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | db.Close() |
| 128 | r.start(t) |
| 129 | second := s.send(t, "again") |
| 130 | s.waitTurn(t, second.Turn.ID, wire.TurnReplied) |
| 131 | if text := s.reply(t, second.Turn.ID).Text; !strings.Contains(text, "fresh session") { |
| 132 | t.Fatalf("an old-rule session was resumed: %q", text) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func TestHeadlessNoCredentialLeaks(t *testing.T) { |
| 137 | env, inst, r := localEnv(t) |
| 138 | r.start(t) |
| 139 | s := open(t, env) |
| 140 | sent := s.send(t, "hello") |
| 141 | s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) |
| 142 | r.stop(t) |
| 143 | secrets := [][]byte{[]byte("fake-access"), []byte("fake-refresh"), []byte(".credentials.json"), []byte("claudeAiOauth")} |
| 144 | check := func(where string, raw []byte) { |
| 145 | for _, secret := range secrets { |
| 146 | if bytes.Contains(raw, secret) { |
| 147 | t.Fatalf("%s contains %q", where, secret) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | for _, table := range []string{"chat_events", "chat_messages", "chat_turns", "runner_commands", "runner_sessions"} { |
| 152 | rows, err := inst.DB.Writer().Query("SELECT * FROM " + table) |
| 153 | if err != nil { |
| 154 | t.Fatal(err) |
| 155 | } |
| 156 | cols, _ := rows.Columns() |
| 157 | for rows.Next() { |
| 158 | values := make([]sql.RawBytes, len(cols)) |
| 159 | ptrs := make([]any, len(cols)) |
| 160 | for i := range values { |
| 161 | ptrs[i] = &values[i] |
| 162 | } |
| 163 | if err = rows.Scan(ptrs...); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | for _, v := range values { |
| 167 | check(table, v) |
| 168 | } |
| 169 | } |
| 170 | rows.Close() |
| 171 | } |
| 172 | db, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db")) |
| 173 | if err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | defer db.Close() |
| 177 | for _, table := range []string{"outbox", "runs", "sessions", "meta", "inbox"} { |
| 178 | rows, err := db.Query("SELECT * FROM " + table) |
| 179 | if err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | cols, _ := rows.Columns() |
| 183 | for rows.Next() { |
| 184 | values := make([]sql.RawBytes, len(cols)) |
| 185 | ptrs := make([]any, len(cols)) |
| 186 | for i := range values { |
| 187 | ptrs[i] = &values[i] |
| 188 | } |
| 189 | rows.Scan(ptrs...) |
| 190 | for _, v := range values { |
| 191 | check("runner "+table, v) |
| 192 | } |
| 193 | } |
| 194 | rows.Close() |
| 195 | } |
| 196 | // Session homes hold transcripts only. |
| 197 | root := filepath.Join(filepath.Dir(r.cfg.StateDir), "sessions") |
| 198 | filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { |
| 199 | if err == nil && !d.IsDir() && !strings.HasSuffix(path, ".jsonl") { |
| 200 | t.Fatalf("non-transcript in session home: %s", path) |
| 201 | } |
| 202 | return nil |
| 203 | }) |
| 204 | // Runtime copies, namespace records and scratch are released when |
| 205 | // their process exits. |
| 206 | homes, _ := os.ReadDir(filepath.Join(r.cfg.ScratchRoot, "homes")) |
| 207 | for _, h := range homes { |
| 208 | t.Fatalf("runtime home left behind: %s", h.Name()) |
| 209 | } |
| 210 | left, _ := os.ReadDir(r.cfg.ScratchRoot) |
| 211 | for _, e := range left { |
| 212 | if e.Name() != "homes" && !strings.HasPrefix(e.Name(), ".equipo-root-owner") { |
| 213 | t.Fatalf("scratch left behind: %s", e.Name()) |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | // A runner killed outright leaves its credential copy behind; the next |
| 219 | // runner process removes it at start, before anything else runs. |
| 220 | func TestHeadlessRunnerKillLeavesNoCopies(t *testing.T) { |
| 221 | env, _, r := localEnv(t) |
| 222 | r.subprocess = true |
| 223 | r.start(t) |
| 224 | s := open(t, env) |
| 225 | sent := s.send(t, "take a while sleep:3000") |
| 226 | s.wait(t, "streaming", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[sent.Turn.ID] != "" }) |
| 227 | copies := func() (n int) { |
| 228 | entries, _ := os.ReadDir(filepath.Join(r.cfg.ScratchRoot, "homes")) |
| 229 | for _, e := range entries { |
| 230 | if strings.HasPrefix(e.Name(), "account-") { |
| 231 | n++ |
| 232 | } |
| 233 | } |
| 234 | return n |
| 235 | } |
| 236 | if copies() == 0 { |
| 237 | t.Fatal("no credential copy while a turn runs") |
| 238 | } |
| 239 | r.kill(t) |
| 240 | if copies() == 0 { |
| 241 | t.Fatal("expected the killed process to leave its copy") |
| 242 | } |
| 243 | r.start(t) |
| 244 | turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) |
| 245 | if turn.Attempt != 2 { |
| 246 | t.Fatalf("attempt %d after a kill, want 2", turn.Attempt) |
| 247 | } |
| 248 | r.stop(t) |
| 249 | if n := copies(); n != 0 { |
| 250 | t.Fatalf("%d credential copies outlived their processes", n) |
| 251 | } |
| 252 | left, _ := os.ReadDir(r.cfg.ScratchRoot) |
| 253 | for _, e := range left { |
| 254 | if e.Name() != "homes" && !strings.HasPrefix(e.Name(), ".equipo-root-owner") { |
| 255 | t.Fatalf("scratch left behind: %s", e.Name()) |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |