| 1 | package headless |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/stagingtest" |
| 15 | "amadan.net/oficina/equipo/internal/thintest" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // session is one client: a snapshot, a conversation folded from events, |
| 20 | // and an open stream. |
| 21 | type session struct { |
| 22 | env *Env |
| 23 | ctx context.Context |
| 24 | conv *thintest.Conversation |
| 25 | stream *thintest.Stream |
| 26 | // followed closes when the stream's last event has been applied. |
| 27 | followed chan struct{} |
| 28 | } |
| 29 | |
| 30 | func open(t *testing.T, env *Env) *session { |
| 31 | t.Helper() |
| 32 | limit := 10 * time.Minute |
| 33 | if env.Live { |
| 34 | // Live review and checks run for many minutes. |
| 35 | limit = 50 * time.Minute |
| 36 | } |
| 37 | ctx, cancel := context.WithTimeout(context.Background(), limit) |
| 38 | t.Cleanup(cancel) |
| 39 | snap, err := env.Client.Snapshot(ctx) |
| 40 | if err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | s := &session{env: env, ctx: ctx, conv: thintest.NewConversation(snap)} |
| 44 | s.follow(t) |
| 45 | return s |
| 46 | } |
| 47 | |
| 48 | // follow opens the stream at the conversation's cursor, retrying while an |
| 49 | // instance restarts. |
| 50 | func (s *session) follow(t *testing.T) { |
| 51 | t.Helper() |
| 52 | deadline := time.Now().Add(90 * time.Second) |
| 53 | for { |
| 54 | stream, err := s.env.Client.Open(s.ctx, s.conv.Cursor) |
| 55 | if err == nil { |
| 56 | s.stream = stream |
| 57 | t.Cleanup(stream.Close) |
| 58 | followed := make(chan struct{}) |
| 59 | s.followed = followed |
| 60 | go func() { |
| 61 | defer close(followed) |
| 62 | s.conv.Follow(stream) |
| 63 | }() |
| 64 | return |
| 65 | } |
| 66 | if thintest.Status(err) == 410 || time.Now().After(deadline) { |
| 67 | t.Fatalf("open stream: %v", err) |
| 68 | } |
| 69 | time.Sleep(500 * time.Millisecond) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | // close ends the stream once every event it brought has been applied: |
| 74 | // the conversation's cursor holds still after it. |
| 75 | func (s *session) close() { |
| 76 | if s.stream != nil { |
| 77 | s.stream.Close() |
| 78 | <-s.stream.Done |
| 79 | <-s.followed |
| 80 | s.stream = nil |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | func key() string { return "h-" + strings.ToLower(rand.Text()) } |
| 85 | |
| 86 | func (s *session) send(t *testing.T, text string) wire.Sent { |
| 87 | t.Helper() |
| 88 | if s.env.RunID != "" { |
| 89 | text += "\nSuite run: " + s.env.RunID |
| 90 | } |
| 91 | s.env.Turn(t) |
| 92 | sent, err := s.env.Client.Send(s.ctx, text, key()) |
| 93 | if err != nil { |
| 94 | t.Fatalf("send: %v", err) |
| 95 | } |
| 96 | return sent |
| 97 | } |
| 98 | |
| 99 | func (s *session) wait(t *testing.T, what string, timeout time.Duration, cond func(*thintest.Conversation) bool) { |
| 100 | t.Helper() |
| 101 | if !s.conv.Wait(timeout, cond) { |
| 102 | var state string |
| 103 | s.conv.Locked(func(c *thintest.Conversation) { |
| 104 | raw, _ := json.Marshal(c.Turns) |
| 105 | state = string(raw) |
| 106 | }) |
| 107 | t.Fatalf("timed out waiting for %s; turns %s", what, state) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | func (s *session) waitTurn(t *testing.T, id string, states ...string) wire.Turn { |
| 112 | t.Helper() |
| 113 | var out wire.Turn |
| 114 | s.wait(t, "turn "+id+" "+strings.Join(states, "|"), 4*time.Minute, func(c *thintest.Conversation) bool { |
| 115 | out = c.Turns[id] |
| 116 | for _, st := range states { |
| 117 | if out.State == st { |
| 118 | return true |
| 119 | } |
| 120 | } |
| 121 | return false |
| 122 | }) |
| 123 | return out |
| 124 | } |
| 125 | |
| 126 | func (s *session) reply(t *testing.T, turn string) wire.Message { |
| 127 | t.Helper() |
| 128 | var out wire.Message |
| 129 | s.conv.Locked(func(c *thintest.Conversation) { |
| 130 | for _, m := range c.Replies() { |
| 131 | if m.TurnID == turn { |
| 132 | if out.ID != "" { |
| 133 | t.Fatalf("two replies for turn %s", turn) |
| 134 | } |
| 135 | out = m |
| 136 | } |
| 137 | } |
| 138 | }) |
| 139 | if out.ID == "" { |
| 140 | t.Fatalf("no reply for turn %s", turn) |
| 141 | } |
| 142 | return out |
| 143 | } |
| 144 | |
| 145 | // firstToken sends text and returns the time to the first streamed delta. |
| 146 | func (s *session) firstToken(t *testing.T, text string) (time.Duration, wire.Sent) { |
| 147 | t.Helper() |
| 148 | start := time.Now() |
| 149 | sent := s.send(t, text) |
| 150 | commit := time.Since(start) |
| 151 | var first time.Time |
| 152 | s.wait(t, "first delta", 3*time.Minute, func(c *thintest.Conversation) bool { |
| 153 | first = c.FirstDelta[sent.Turn.ID] |
| 154 | return !first.IsZero() || wire.Terminal(c.Turns[sent.Turn.ID].State) |
| 155 | }) |
| 156 | if first.IsZero() { |
| 157 | t.Fatalf("turn ended without a delta: %+v", s.conv.Turns[sent.Turn.ID]) |
| 158 | } |
| 159 | s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) |
| 160 | clock := turnClock{Commit: commit, FirstDelta: first.Sub(start), Message: time.Since(start)} |
| 161 | s.conv.Locked(func(c *thintest.Conversation) { |
| 162 | if at, ok := c.FirstActivity[sent.Turn.ID]; ok { |
| 163 | clock.FirstActivity = at.Sub(start) |
| 164 | } |
| 165 | }) |
| 166 | if turn, err := s.env.Client.Turn(s.ctx, sent.Turn.ID); err == nil { |
| 167 | clock.Timing = turn.Timing |
| 168 | } |
| 169 | TurnClocks[t.Name()+"/"+strconv.Itoa(len(TurnClocks))+"/"+sent.Turn.ID] = clock |
| 170 | return first.Sub(start), sent |
| 171 | } |
| 172 | |
| 173 | // Timings collects first-token measurements for the report; Witness |
| 174 | // what each Engineering scenario saw. |
| 175 | var ( |
| 176 | Timings = map[string]time.Duration{} |
| 177 | Witness = map[string]any{} |
| 178 | ) |
| 179 | |
| 180 | func report(t *testing.T) { |
| 181 | path := os.Getenv("EQUIPO_HEADLESS_REPORT") |
| 182 | if path == "" { |
| 183 | return |
| 184 | } |
| 185 | out := map[string]any{} |
| 186 | for k, v := range Timings { |
| 187 | out[k] = v.Round(time.Millisecond).String() |
| 188 | } |
| 189 | for k, v := range TurnClocks { |
| 190 | out[k] = v |
| 191 | } |
| 192 | for k, v := range Witness { |
| 193 | out["witness/"+k] = v |
| 194 | } |
| 195 | raw, _ := json.MarshalIndent(out, "", " ") |
| 196 | if err := os.WriteFile(path, raw, 0600); err != nil { |
| 197 | t.Log(err) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // Scenario 1: a signed-in device says hello and sees the first streamed |
| 202 | // text quickly. Cold (no coordinator process: fresh or resumed session) |
| 203 | // and warm (process already up) are measured separately. |
| 204 | func scenarioFirstToken(t *testing.T, env *Env) { |
| 205 | env.RestartRunner(t) |
| 206 | s := open(t, env) |
| 207 | // The edge can drop a stream (a 502 on staging); follow like a client. |
| 208 | s.keep() |
| 209 | me, err := env.Client.Me(s.ctx) |
| 210 | if err != nil || me.Address == "" { |
| 211 | t.Fatalf("me: %+v %v", me, err) |
| 212 | } |
| 213 | s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) |
| 214 | cold, first := s.firstToken(t, "hello") |
| 215 | warm, second := s.firstToken(t, "Thanks. Reply with one short sentence.") |
| 216 | env.RestartRunner(t) |
| 217 | resumed, third := s.firstToken(t, "Still there? One short sentence.") |
| 218 | Timings[t.Name()+"/cold"], Timings[t.Name()+"/warm"], Timings[t.Name()+"/cold_resume"] = cold, warm, resumed |
| 219 | t.Logf("first token: cold %v, warm %v, cold resume %v", cold, warm, resumed) |
| 220 | for _, sent := range []wire.Sent{first, second, third} { |
| 221 | if r := s.reply(t, sent.Turn.ID); r.Text == "" { |
| 222 | t.Fatalf("empty reply for %s", sent.Turn.ID) |
| 223 | } |
| 224 | } |
| 225 | if !env.Live { |
| 226 | if r := s.reply(t, second.Turn.ID).Text; !strings.Contains(r, "process turn 2.") { |
| 227 | t.Fatalf("second turn did not reuse the warm process: %q", r) |
| 228 | } |
| 229 | if r := s.reply(t, third.Turn.ID).Text; !strings.Contains(r, "Turn 3, resumed session, process turn 1.") { |
| 230 | t.Fatalf("restarted runner did not resume the session: %q", r) |
| 231 | } |
| 232 | } |
| 233 | for _, sample := range []struct { |
| 234 | name string |
| 235 | first, limit time.Duration |
| 236 | cold bool |
| 237 | }{ |
| 238 | {"warm", warm, 5 * time.Second, false}, {"cold", cold, env.ResumeThreshold, true}, {"cold_resume", resumed, env.ResumeThreshold, true}, |
| 239 | } { |
| 240 | samples, err := stagingtest.Latency(sample.first, sample.limit, func() time.Duration { |
| 241 | if sample.cold { |
| 242 | env.RestartRunner(t) |
| 243 | } |
| 244 | elapsed, _ := s.firstToken(t, "Reply with one short sentence.") |
| 245 | return elapsed |
| 246 | }) |
| 247 | for i, elapsed := range samples { |
| 248 | Timings[fmt.Sprintf("%s/%s/sample_%d", t.Name(), sample.name, i+1)] = elapsed |
| 249 | } |
| 250 | t.Logf("%s first-token samples: %v (limit %v)", sample.name, samples, sample.limit) |
| 251 | if err != nil { |
| 252 | t.Error(err) |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // Scenario 3: with the runner offline the message waits as queued; when |
| 258 | // the runner reconnects it is answered exactly once. |
| 259 | func scenarioRunnerOffline(t *testing.T, env *Env) { |
| 260 | s := open(t, env) |
| 261 | // The edge can drop a stream (a 502 on staging); follow like a client. |
| 262 | s.keep() |
| 263 | env.StopRunner(t) |
| 264 | s.wait(t, "runner offline", 90*time.Second, func(c *thintest.Conversation) bool { return !c.Runner.Online }) |
| 265 | sent := s.send(t, "Are you there? One short sentence.") |
| 266 | time.Sleep(time.Second) |
| 267 | if st := s.conv.Turns[sent.Turn.ID].State; st != wire.TurnQueued { |
| 268 | t.Fatalf("offline turn is %s, want queued", st) |
| 269 | } |
| 270 | env.StartRunner(t) |
| 271 | s.wait(t, "runner online", 60*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) |
| 272 | s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) |
| 273 | s.reply(t, sent.Turn.ID) |
| 274 | page, err := env.Client.Messages(s.ctx, "", 200) |
| 275 | if err != nil { |
| 276 | t.Fatal(err) |
| 277 | } |
| 278 | count := 0 |
| 279 | for _, m := range page.Items { |
| 280 | if m.TurnID == sent.Turn.ID && m.Role == wire.RoleCoordinator { |
| 281 | count++ |
| 282 | } |
| 283 | } |
| 284 | if count != 1 { |
| 285 | t.Fatalf("%d replies stored for one turn", count) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | // Scenario 6: two quick messages while the coordinator is busy reach it |
| 290 | // as one frame and produce one reply. |
| 291 | func scenarioQuickMessages(t *testing.T, env *Env) { |
| 292 | s := open(t, env) |
| 293 | // The edge can drop a stream (a 502 on staging); follow like a client. |
| 294 | s.keep() |
| 295 | busy := s.send(t, env.Slow) |
| 296 | s.waitTurn(t, busy.Turn.ID, wire.TurnRunning, wire.TurnReplied) |
| 297 | a := s.send(t, "One more thing:") |
| 298 | b, err := env.Client.Send(s.ctx, "what is two plus two? Reply with the number only.", key()) |
| 299 | if err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | if b.Turn.ID != a.Turn.ID || len(b.Turn.MessageIDs) != 2 { |
| 303 | t.Fatalf("quick messages split: %s %s %v", a.Turn.ID, b.Turn.ID, b.Turn.MessageIDs) |
| 304 | } |
| 305 | s.waitTurn(t, busy.Turn.ID, wire.TurnReplied) |
| 306 | s.waitTurn(t, a.Turn.ID, wire.TurnReplied) |
| 307 | r := s.reply(t, a.Turn.ID) |
| 308 | if !env.Live && !strings.Contains(r.Text, "You sent 2 messages") { |
| 309 | t.Fatalf("coordinator did not get both messages in one frame: %q", r.Text) |
| 310 | } |
| 311 | if env.Live && !strings.Contains(r.Text, "4") { |
| 312 | t.Fatalf("joined reply %q", r.Text) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // Scenario 7: a dropped stream resumes from its cursor with nothing lost |
| 317 | // or repeated; an expired cursor gets 410 and recovers from a snapshot. |
| 318 | func scenarioStreamResume(t *testing.T, env *Env) { |
| 319 | s := open(t, env) |
| 320 | s.wait(t, "runner online", 60*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) |
| 321 | s.close() |
| 322 | cursor := s.conv.Cursor |
| 323 | sent := s.send(t, "Reply with the word resumed.") |
| 324 | deadline := time.Now().Add(3 * time.Minute) |
| 325 | for { |
| 326 | turn, err := env.Client.Turn(s.ctx, sent.Turn.ID) |
| 327 | if err == nil && wire.Terminal(turn.State) { |
| 328 | break |
| 329 | } |
| 330 | if time.Now().After(deadline) { |
| 331 | t.Fatalf("turn did not end: %+v %v", turn, err) |
| 332 | } |
| 333 | time.Sleep(300 * time.Millisecond) |
| 334 | } |
| 335 | before := s.conv.Applied |
| 336 | s.follow(t) |
| 337 | s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) |
| 338 | s.reply(t, sent.Turn.ID) |
| 339 | if s.conv.Applied == before { |
| 340 | t.Fatal("no events replayed from the cursor") |
| 341 | } |
| 342 | // The same events again from the old cursor change nothing. Only the |
| 343 | // replay counts, up to where the conversation stood: the live stream |
| 344 | // closes first, and nothing after that point is a repeat. The |
| 345 | // conversation goes on after a reply (on staging a runner's hello |
| 346 | // stores a connection's fresh headroom at any moment), and an event |
| 347 | // newer than the conversation's cursor is news, not a replay. |
| 348 | s.close() |
| 349 | top := s.conv.Cursor |
| 350 | applied := s.conv.Applied |
| 351 | // The whole replay is bounded, opening it again included. |
| 352 | rctx, cancel := context.WithTimeout(s.ctx, 30*time.Second) |
| 353 | defer cancel() |
| 354 | again, err := env.Client.Open(rctx, cursor) |
| 355 | if err != nil { |
| 356 | t.Fatal(err) |
| 357 | } |
| 358 | if env.duringReplay != nil { |
| 359 | env.duringReplay(t, s) |
| 360 | } |
| 361 | last := cursor |
| 362 | replay: |
| 363 | for { |
| 364 | select { |
| 365 | case e, ok := <-again.Events: |
| 366 | if !ok { |
| 367 | // The edge can drop a stream (a 502 on staging): resume the |
| 368 | // replay from what it brought, as a client would. |
| 369 | again.Close() |
| 370 | for again, err = env.Client.Open(rctx, last); err != nil; again, err = env.Client.Open(rctx, last) { |
| 371 | if thintest.Status(err) == 410 || rctx.Err() != nil { |
| 372 | t.Fatalf("reopen the replay at %d: %v", last, err) |
| 373 | } |
| 374 | time.Sleep(500 * time.Millisecond) |
| 375 | } |
| 376 | continue |
| 377 | } |
| 378 | if e.Cursor > top { |
| 379 | t.Fatalf("the replay passed cursor %d without it (at %d)", top, e.Cursor) |
| 380 | } |
| 381 | s.conv.Apply(e) |
| 382 | last = max(last, e.Cursor) |
| 383 | if e.Cursor == top { |
| 384 | break replay |
| 385 | } |
| 386 | case <-rctx.Done(): |
| 387 | t.Fatalf("the replay did not reach cursor %d (at %d)", top, last) |
| 388 | } |
| 389 | } |
| 390 | again.Close() |
| 391 | if s.conv.Applied != applied { |
| 392 | t.Fatal("replayed events applied twice") |
| 393 | } |
| 394 | stale := s.conv.Cursor + 1_000_000_000 |
| 395 | if env.AgeEvents(t) { |
| 396 | stale = cursor |
| 397 | } |
| 398 | if _, err = env.Client.Open(s.ctx, stale); thintest.Status(err) != 410 { |
| 399 | t.Fatalf("stale cursor: %v", err) |
| 400 | } |
| 401 | snap, err := env.Client.Snapshot(s.ctx) |
| 402 | if err != nil { |
| 403 | t.Fatal(err) |
| 404 | } |
| 405 | s.close() |
| 406 | s.conv.Reset(snap) |
| 407 | s.follow(t) |
| 408 | found := false |
| 409 | for _, m := range snap.Messages { |
| 410 | found = found || m.TurnID == sent.Turn.ID && m.Role == wire.RoleCoordinator |
| 411 | } |
| 412 | if !found { |
| 413 | t.Fatal("snapshot lost the reply") |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | // Scenario 8: the instance restarts during a turn. The turn finishes or |
| 418 | // fails visibly; nothing the person sent or was sent is lost. |
| 419 | func scenarioInstanceRestart(t *testing.T, env *Env) { |
| 420 | s := open(t, env) |
| 421 | s.wait(t, "runner online", 60*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) |
| 422 | sent := s.send(t, env.Slow) |
| 423 | s.waitTurn(t, sent.Turn.ID, wire.TurnRunning, wire.TurnReplied) |
| 424 | s.close() |
| 425 | s.restartInstance(t) |
| 426 | // Reopen from the cursor, and again if anything still cuts the stream. |
| 427 | s.keep() |
| 428 | turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied, wire.TurnFailed) |
| 429 | if turn.State == wire.TurnFailed && turn.Reason == "" { |
| 430 | t.Fatal("failed without a reason") |
| 431 | } |
| 432 | snap, err := env.Client.Snapshot(s.ctx) |
| 433 | if err != nil { |
| 434 | t.Fatal(err) |
| 435 | } |
| 436 | ids := map[string]bool{} |
| 437 | for _, m := range snap.Messages { |
| 438 | ids[m.ID] = true |
| 439 | } |
| 440 | if !ids[sent.Message.ID] || turn.State == wire.TurnReplied && !ids[turn.ReplyID] { |
| 441 | t.Fatalf("restart lost messages: %+v", turn) |
| 442 | } |
| 443 | // The conversation carries on (fake CLI only, to save live turns). |
| 444 | if !env.Live { |
| 445 | next := s.send(t, "And now? One short sentence.") |
| 446 | s.waitTurn(t, next.Turn.ID, wire.TurnReplied) |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | // restartInstance restarts the instance and returns only once the old |
| 451 | // process has stopped and a new one serves. The platform's restart command |
| 452 | // returns before the box cycles the instance (2-35 s later on staging), so |
| 453 | // a probe stream opened first marks the old process: draining closes every |
| 454 | // stream. A draining process still answers briefly, but its new streams end |
| 455 | // at once, so the new process is the one that holds a stream open. |
| 456 | func (s *session) restartInstance(t *testing.T) { |
| 457 | t.Helper() |
| 458 | const stops, serves, hold = 2 * time.Minute, 90 * time.Second, 2 * time.Second |
| 459 | var cursor int64 |
| 460 | s.conv.Locked(func(c *thintest.Conversation) { cursor = c.Cursor }) |
| 461 | probe, err := s.env.Client.Open(s.ctx, cursor) |
| 462 | if err != nil { |
| 463 | t.Fatalf("instance restart: open the probe stream: %v", err) |
| 464 | } |
| 465 | defer probe.Close() |
| 466 | // A full event buffer would stall the reader before it sees the end. |
| 467 | drain := func(st *thintest.Stream) { |
| 468 | go func() { |
| 469 | for range st.Events { |
| 470 | } |
| 471 | }() |
| 472 | } |
| 473 | drain(probe) |
| 474 | issued := time.Now() |
| 475 | s.env.RestartInst(t) |
| 476 | select { |
| 477 | case <-probe.Done: |
| 478 | case <-time.After(stops): |
| 479 | t.Fatalf("instance restart: the old instance still serves %v after the restart command returned", stops) |
| 480 | } |
| 481 | stopped := time.Now() |
| 482 | deadline := stopped.Add(serves) |
| 483 | for { |
| 484 | ctx, cancel := context.WithTimeout(s.ctx, 30*time.Second) |
| 485 | stream, err := s.env.Client.Open(ctx, cursor) |
| 486 | held := false |
| 487 | if err == nil { |
| 488 | drain(stream) |
| 489 | select { |
| 490 | case <-stream.Done: |
| 491 | case <-time.After(hold): |
| 492 | held = true |
| 493 | } |
| 494 | stream.Close() |
| 495 | } |
| 496 | cancel() |
| 497 | if held { |
| 498 | break |
| 499 | } |
| 500 | if time.Now().After(deadline) { |
| 501 | t.Fatalf("instance restart: no new instance holds a stream %v after the old one stopped (last error %v)", serves, err) |
| 502 | } |
| 503 | time.Sleep(500 * time.Millisecond) |
| 504 | } |
| 505 | t.Logf("instance restart: old instance stopped %v after the command, new one serving %v later", |
| 506 | stopped.Sub(issued).Round(100*time.Millisecond), time.Since(stopped).Round(100*time.Millisecond)) |
| 507 | } |
| 508 | |
| 509 | // Coordinator cancel: the attempt's process is stopped, the draft |
| 510 | // discarded, the turn ends cancelled, and the next message is answered. |
| 511 | func scenarioCancel(t *testing.T, env *Env) { |
| 512 | s := open(t, env) |
| 513 | // The edge can drop a stream (a 502 on staging); follow like a client. |
| 514 | s.keep() |
| 515 | sent := s.send(t, env.Slow) |
| 516 | s.waitTurn(t, sent.Turn.ID, wire.TurnRunning) |
| 517 | s.wait(t, "draft", time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[sent.Turn.ID] != "" }) |
| 518 | if _, err := env.Client.Cancel(s.ctx, sent.Turn.ID); err != nil { |
| 519 | t.Fatal(err) |
| 520 | } |
| 521 | s.waitTurn(t, sent.Turn.ID, wire.TurnCancelled) |
| 522 | if s.conv.Drafts[sent.Turn.ID] != "" { |
| 523 | t.Fatal("draft kept after cancel") |
| 524 | } |
| 525 | if !env.Live { |
| 526 | next := s.send(t, "Never mind. One short sentence.") |
| 527 | s.waitTurn(t, next.Turn.ID, wire.TurnReplied) |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | // Crash recovery: the runner process is killed (SIGKILL) mid-turn; on |
| 532 | // restart it takes a new attempt from its durable state and the turn is |
| 533 | // answered once. |
| 534 | func scenarioRunnerCrash(t *testing.T, env *Env) { |
| 535 | s := open(t, env) |
| 536 | // The edge can drop a stream (a 502 on staging); follow like a client. |
| 537 | s.keep() |
| 538 | sent := s.send(t, env.Slow) |
| 539 | s.waitTurn(t, sent.Turn.ID, wire.TurnRunning) |
| 540 | s.wait(t, "streaming", 2*time.Minute, func(c *thintest.Conversation) bool { return c.Drafts[sent.Turn.ID] != "" }) |
| 541 | env.KillRunner(t) |
| 542 | env.StartRunner(t) |
| 543 | turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied) |
| 544 | if turn.Attempt != 2 { |
| 545 | t.Fatalf("recovered turn attempt %d, want 2", turn.Attempt) |
| 546 | } |
| 547 | s.reply(t, sent.Turn.ID) |
| 548 | } |
| 549 | |
| 550 | var scenarios = []struct { |
| 551 | name string |
| 552 | run func(*testing.T, *Env) |
| 553 | }{ |
| 554 | // Moving in first: on staging a fresh runner moves in at once, and |
| 555 | // these settle it before the other scenarios talk to it. |
| 556 | {"2b_move_in", scenarioMoveIn}, |
| 557 | {"2b_first_message", scenarioFirstMessage}, |
| 558 | {"2b_access", scenarioAccessChange}, |
| 559 | {"2b_desk_failure", scenarioDeskFailure}, |
| 560 | {"2b_notebook", scenarioNotebook}, |
| 561 | {"1_first_token", scenarioFirstToken}, |
| 562 | {"3_runner_offline", scenarioRunnerOffline}, |
| 563 | {"6_quick_messages", scenarioQuickMessages}, |
| 564 | {"7_stream_resume", scenarioStreamResume}, |
| 565 | {"8_instance_restart", scenarioInstanceRestart}, |
| 566 | {"cancel", scenarioCancel}, |
| 567 | {"runner_crash", scenarioRunnerCrash}, |
| 568 | {"2_project", scenarioProject}, |
| 569 | {"2_find", scenarioFindAndRead}, |
| 570 | {"2_new_work", scenarioNewWork}, |
| 571 | {"2_question", scenarioQuestion}, |
| 572 | {"2_project_home", scenarioProjectHome}, |
| 573 | {"3_engineering", scenarioEngineering}, |
| 574 | {"3_step_cancel", scenarioStepCancel}, |
| 575 | {"3_step_contained", scenarioStepContained}, |
| 576 | {"3_step_refused", scenarioStepRefused}, |
| 577 | {"4_step_crash", scenarioStepCrash}, |
| 578 | {"3_grant", scenarioGrant}, |
| 579 | {"3_empty_repo", scenarioEmptyRepo}, |
| 580 | {"3_empty_engineering", scenarioEmptyEngineering}, |
| 581 | {"3_empty_merge", scenarioEmptyMerge}, |
| 582 | {"3_empty_merge_rebuilt", scenarioEmptyMergeRebuilt}, |
| 583 | {"3_empty_fix_round", scenarioEmptyFixRound}, |
| 584 | {"4_review", scenarioReview}, |
| 585 | {"4_checks_honest", scenarioChecksHonest}, |
| 586 | {"4_witness", scenarioReviewWitness}, |
| 587 | {"4b_ask", scenarioAsk}, |
| 588 | {"4b_witness", scenarioAskWitness}, |
| 589 | {"4c_checks_card", scenarioChecksCard}, |
| 590 | {"4c_rebase", scenarioRebase}, |
| 591 | {"4c_duplicate", scenarioDuplicate}, |
| 592 | {"4c_witness", scenarioMergeWitness}, |
| 593 | {"conn1_witness", scenarioConnWitness}, |
| 594 | {"assistant_attachments", scenarioAssistantAttachments}, |
| 595 | } |
| 596 | |
| 597 | // TestHeadless runs every scenario against a fresh local instance and |
| 598 | // runner with the fake CLI in real bubblewrap. |
| 599 | func TestHeadless(t *testing.T) { |
| 600 | for _, sc := range scenarios { |
| 601 | t.Run(sc.name, func(t *testing.T) { |
| 602 | env, _, r := localEnv(t) |
| 603 | r.subprocess = sc.name == "runner_crash" || sc.name == "4_step_crash" |
| 604 | // Moving in is on for its own scenarios; those that reset the |
| 605 | // desk start the runner themselves. |
| 606 | r.opts.NoMoveIn = !strings.HasPrefix(sc.name, "2b_") |
| 607 | if sc.name == "2b_first_message" { |
| 608 | r.opts.Claude.MoveInNote = "\nmovein-pause:700" |
| 609 | } |
| 610 | if sc.name != "2b_desk_failure" { |
| 611 | r.start(t) |
| 612 | } |
| 613 | sc.run(t, env) |
| 614 | }) |
| 615 | } |
| 616 | report(t) |
| 617 | } |
| 618 | |
| 619 | // TestHeadlessStreamResumeWhileLive is scenario 7 while something new |
| 620 | // reaches the conversation as it reads the replay: on staging a runner's |
| 621 | // hello stores a connection's fresh headroom at any moment after a reply. |
| 622 | // Only the replay must change nothing; what is new still applies. |
| 623 | func TestHeadlessStreamResumeWhileLive(t *testing.T) { |
| 624 | env, _, r := localEnv(t) |
| 625 | r.opts.NoMoveIn = true |
| 626 | r.start(t) |
| 627 | var added string |
| 628 | var live *session |
| 629 | env.duringReplay = func(t *testing.T, s *session) { |
| 630 | c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: "codex"}) |
| 631 | if err != nil { |
| 632 | t.Fatal(err) |
| 633 | } |
| 634 | added, live = c.ID, s |
| 635 | } |
| 636 | scenarioStreamResume(t, env) |
| 637 | // What was new during the replay reaches the conversation all the same. |
| 638 | live.wait(t, "the connection added during the replay", 30*time.Second, func(c *thintest.Conversation) bool { |
| 639 | _, ok := c.Connections[added] |
| 640 | return ok |
| 641 | }) |
| 642 | } |
| 643 | |
| 644 | // TestStaging runs the same scenarios against staging with the real CLI. |
| 645 | // The gate script sets the origin, the device bearer and the controls. |
| 646 | func TestStaging(t *testing.T) { |
| 647 | env := stagingEnv(t) |
| 648 | only := os.Getenv("EQUIPO_STAGING_SCENARIOS") |
| 649 | for _, sc := range scenarios { |
| 650 | if only != "" && !strings.Contains(","+only+",", ","+sc.name+",") { |
| 651 | continue |
| 652 | } |
| 653 | if !t.Run(sc.name, func(t *testing.T) { |
| 654 | before := *env.turns |
| 655 | defer func() { |
| 656 | used := *env.turns - before |
| 657 | t.Logf("model turns used: %d (total %d)", used, *env.turns) |
| 658 | Witness[t.Name()+"/turns"] = used |
| 659 | }() |
| 660 | sc.run(t, env) |
| 661 | }) { |
| 662 | break |
| 663 | } |
| 664 | } |
| 665 | t.Logf("model turns used: %d", *env.turns) |
| 666 | report(t) |
| 667 | fmt.Fprintf(os.Stderr, "staging turns %d\n", *env.turns) |
| 668 | } |
| 669 | |