| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | gitleakscmd "github.com/zricethezav/gitleaks/v8/cmd" |
| 7 | "log/slog" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 19 | "amadan.net/oficina/equipo/internal/fakeopencode" |
| 20 | "amadan.net/oficina/equipo/internal/fakepi" |
| 21 | "amadan.net/oficina/equipo/internal/runner" |
| 22 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 23 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 24 | "amadan.net/oficina/equipo/internal/testci" |
| 25 | "amadan.net/oficina/equipo/internal/wire" |
| 26 | "amadan.net/oficina/equipo/internal/wire/wiretest" |
| 27 | "amadan.net/rastrillo/rastrillo/budget" |
| 28 | "github.com/coder/websocket" |
| 29 | ) |
| 30 | |
| 31 | func TestMain(m *testing.M) { |
| 32 | switch filepath.Base(os.Args[0]) { |
| 33 | case "scanner", "gitleaks": |
| 34 | gitleakscmd.Execute() |
| 35 | return |
| 36 | case "claude": |
| 37 | os.Exit(fakeclaude.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) |
| 38 | case "node": |
| 39 | // fakepi, started as Node with the Pi CLI's path first. |
| 40 | os.Exit(fakepi.Main(os.Args[2:], os.Stdin, os.Stdout, os.Stderr)) |
| 41 | case "opencode": |
| 42 | // fakeopencode, started as the pinned binary. |
| 43 | os.Exit(fakeopencode.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) |
| 44 | case "equipo-tool-proxy": |
| 45 | os.Exit(serveToolProxy(os.Args)) |
| 46 | } |
| 47 | if len(os.Args) > 1 && os.Args[1] == "__namespace" { |
| 48 | os.Exit(containment.NamespaceMain(os.Args[2:])) |
| 49 | } |
| 50 | if testHelper != nil { |
| 51 | if code, ok := testHelper(); ok { |
| 52 | os.Exit(code) |
| 53 | } |
| 54 | } |
| 55 | // The fake carlos binaries answer no version verb: a current release |
| 56 | // stands in, and the guard's own tests set theirs. |
| 57 | readCarlosVersion = func(context.Context, string) string { return "v0.43.3" } |
| 58 | code := budget.Main(m) |
| 59 | if scannerBuild.binary != "" { |
| 60 | _ = os.RemoveAll(filepath.Dir(scannerBuild.binary)) |
| 61 | } |
| 62 | os.Exit(code) |
| 63 | } |
| 64 | |
| 65 | // testHelper, when a test build's file sets it, may run this binary as |
| 66 | // one of its helper processes instead of the tests (ok). |
| 67 | var testHelper func() (code int, ok bool) |
| 68 | |
| 69 | // stubCoordinator streams two deltas and replies, or waits to be cancelled. |
| 70 | type stubCoordinator struct { |
| 71 | mu sync.Mutex |
| 72 | turns []TurnInput |
| 73 | } |
| 74 | |
| 75 | func (s *stubCoordinator) Turn(ctx context.Context, in TurnInput, emit func(string)) TurnResult { |
| 76 | s.mu.Lock() |
| 77 | s.turns = append(s.turns, in) |
| 78 | s.mu.Unlock() |
| 79 | if strings.Contains(in.Text, "wait") { |
| 80 | <-ctx.Done() |
| 81 | return TurnResult{Reason: "cancelled"} |
| 82 | } |
| 83 | emit("Hel") |
| 84 | emit("lo.") |
| 85 | return TurnResult{Text: "Hello.", Usage: []wire.Usage{{InputTokens: i64(1), OutputTokens: i64(2), Complete: true}}} |
| 86 | } |
| 87 | func (s *stubCoordinator) Close() {} |
| 88 | |
| 89 | func i64(v int64) *int64 { return &v } |
| 90 | |
| 91 | // testEnrolledRole is the role startLink's runner was enrolled with. |
| 92 | var testEnrolledRole = wire.RolePrimary |
| 93 | |
| 94 | // testTaskEnded is startLink's Link.TaskEnded (nil: none). |
| 95 | var testTaskEnded func(context.Context, string) |
| 96 | |
| 97 | // fakeInstance is the instance end of the stream, driven from fixtures. |
| 98 | type fakeInstance struct { |
| 99 | t *testing.T |
| 100 | url string |
| 101 | conns chan *websocket.Conn |
| 102 | } |
| 103 | |
| 104 | func newFakeInstance(t *testing.T) *fakeInstance { |
| 105 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 106 | if err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | f := &fakeInstance{t: t, url: "http://" + l.Addr().String(), conns: make(chan *websocket.Conn, 4)} |
| 110 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 111 | if r.URL.Path != wire.StreamPath || r.Header.Get("Authorization") != "Bearer token" { |
| 112 | http.Error(w, "forbidden", http.StatusForbidden) |
| 113 | return |
| 114 | } |
| 115 | c, err := websocket.Accept(w, r, nil) |
| 116 | if err != nil { |
| 117 | return |
| 118 | } |
| 119 | f.conns <- c |
| 120 | <-r.Context().Done() |
| 121 | })} |
| 122 | go srv.Serve(l) |
| 123 | t.Cleanup(func() { srv.Close() }) |
| 124 | return f |
| 125 | } |
| 126 | |
| 127 | func read(t *testing.T, c *websocket.Conn, kind string) (wire.Frame, []byte) { |
| 128 | t.Helper() |
| 129 | for { |
| 130 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 131 | _, raw, err := c.Read(ctx) |
| 132 | cancel() |
| 133 | if err != nil { |
| 134 | t.Fatalf("waiting for %s: %v", kind, err) |
| 135 | } |
| 136 | f, _, err := wire.ParseFrame(raw) |
| 137 | if err != nil { |
| 138 | t.Fatal(err) |
| 139 | } |
| 140 | if f.Type == kind { |
| 141 | if kind == wire.FrameHello { |
| 142 | // A protocol 2 hello carries the slice 4 hello's fields and |
| 143 | // the protocol 2 ones; at protocol 1 it is the slice 4 hello. |
| 144 | old, err := wire.Encode(f, wire.Protocol1) |
| 145 | if err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | check, _ := json.Marshal(old) |
| 149 | if err = wiretest.SameShape(wiretest.Fixture("frames/hello.json"), check); err != nil { |
| 150 | t.Fatalf("hello frame: %v\n%s", err, raw) |
| 151 | } |
| 152 | return f, raw |
| 153 | } |
| 154 | if err = wiretest.SameShape(wiretest.Fixture("frames/"+kind+".json"), raw); err != nil { |
| 155 | t.Fatalf("%s frame: %v\n%s", kind, err, raw) |
| 156 | } |
| 157 | return f, raw |
| 158 | } |
| 159 | if f.Type == wire.FrameLease { |
| 160 | // The fake instance confirms the lease, as the real one does |
| 161 | // for the current connection. |
| 162 | ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 163 | rawAck, _ := json.Marshal(ack) |
| 164 | write(t, c, rawAck) |
| 165 | continue |
| 166 | } |
| 167 | if f.Type != wire.FrameHello && f.Type != wire.FrameDelta && f.Type != wire.FrameAck { |
| 168 | t.Fatalf("waiting for %s, got %s", kind, raw) |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | func write(t *testing.T, c *websocket.Conn, raw []byte) { |
| 174 | t.Helper() |
| 175 | if err := c.Write(context.Background(), websocket.MessageText, raw); err != nil { |
| 176 | t.Fatal(err) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | func startLink(t *testing.T, origin string, coord Coordinator, seed ...func(*State)) (*Link, *State, context.CancelFunc, chan error) { |
| 181 | t.Helper() |
| 182 | return startLinkWith(t, origin, coord, nil, seed...) |
| 183 | } |
| 184 | |
| 185 | // startLinkWith is startLink with hello, when set, as the runner's hello, |
| 186 | // in place before the link first dials. |
| 187 | func startLinkWith(t *testing.T, origin string, coord Coordinator, hello func() wire.Hello, seed ...func(*State)) (*Link, *State, context.CancelFunc, chan error) { |
| 188 | t.Helper() |
| 189 | ctx, cancel := context.WithCancel(context.Background()) |
| 190 | state, err := OpenState(ctx, t.TempDir()) |
| 191 | if err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | for _, f := range seed { |
| 195 | f(state) |
| 196 | } |
| 197 | t.Cleanup(func() { state.Close() }) |
| 198 | sessions := filepath.Join(t.TempDir(), "sessions") |
| 199 | if err := os.MkdirAll(sessions, 0700); err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | link := &Link{Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)), Origin: origin, Token: "token", State: state, Role: testEnrolledRole, Files: &Files{State: state, SessionRoot: sessions}, Hello: func() wire.Hello { |
| 203 | return wire.Hello{Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{{LocalID: "claude-a", Person: "owner@example.com", Provider: "claude", Kind: "subscription", Label: "owner@example.com", State: "healthy"}}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}} |
| 204 | }} |
| 205 | if hello != nil { |
| 206 | link.Hello = hello |
| 207 | } |
| 208 | link.TaskEnded = testTaskEnded |
| 209 | engine := &Engine{State: state, Emit: link.Delta, Notify: link.Notify, Authorize: link.Confirm, Open: func(string, string, runner.AccountBinding) (Coordinator, error) { return coord, nil }} |
| 210 | link.Engine = engine |
| 211 | if err = engine.Start(ctx); err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | done := make(chan error, 1) |
| 215 | go func() { done <- link.Run(ctx) }() |
| 216 | t.Cleanup(func() { cancel(); engine.Wait() }) |
| 217 | return link, state, cancel, done |
| 218 | } |
| 219 | |
| 220 | // The runner end of the contract: it speaks the recorded frames and |
| 221 | // accepts the instance's recorded frames. |
| 222 | func TestRunnerContract(t *testing.T) { |
| 223 | inst := newFakeInstance(t) |
| 224 | coord := &stubCoordinator{} |
| 225 | _, state, _, _ := startLink(t, inst.url, coord) |
| 226 | c := <-inst.conns |
| 227 | read(t, c, wire.FrameHello) |
| 228 | write(t, c, wiretest.Fixture("frames/welcome.json")) |
| 229 | read(t, c, wire.FrameSync) |
| 230 | write(t, c, wiretest.Fixture("frames/message.json")) |
| 231 | ack, raw := read(t, c, wire.FrameAck) |
| 232 | var a wire.Ack |
| 233 | json.Unmarshal(ack.Data, &a) |
| 234 | if a.ID != "c7" { |
| 235 | t.Fatalf("ack %s", raw) |
| 236 | } |
| 237 | delta, _ := read(t, c, wire.FrameDelta) |
| 238 | var d wire.DeltaReport |
| 239 | json.Unmarshal(delta.Data, &d) |
| 240 | reply, _ := read(t, c, wire.FrameReply) |
| 241 | var r wire.Reply |
| 242 | json.Unmarshal(reply.Data, &r) |
| 243 | if d.TurnID != "t_0001" || d.Offset != 0 || !strings.HasPrefix("Hello.", d.Text) || r.Text != "Hello." || r.TurnID != "t_0001" || r.Attempt != 1 { |
| 244 | t.Fatalf("delta %+v reply %+v", d, r) |
| 245 | } |
| 246 | if got := coord.turns[0]; got.Text != "hello" || len(got.Tail) != 2 || got.Person != "owner@example.com" { |
| 247 | t.Fatalf("turn input %+v", got) |
| 248 | } |
| 249 | // A resent message frame is acked again and not run twice. |
| 250 | write(t, c, wiretest.Fixture("frames/message.json")) |
| 251 | read(t, c, wire.FrameAck) |
| 252 | ackFrame, _ := wire.NewFrame("i-ack", wire.FrameAck, wire.Ack{ID: reply.ID}) |
| 253 | rawAck, _ := json.Marshal(ackFrame) |
| 254 | write(t, c, rawAck) |
| 255 | deadline := time.Now().Add(5 * time.Second) |
| 256 | for { |
| 257 | s, _ := state.Sync(context.Background()) |
| 258 | if len(s.Runs) == 0 { |
| 259 | break |
| 260 | } |
| 261 | if time.Now().After(deadline) { |
| 262 | t.Fatalf("run not finished after ack: %+v", s.Runs) |
| 263 | } |
| 264 | time.Sleep(20 * time.Millisecond) |
| 265 | } |
| 266 | if len(coord.turns) != 1 { |
| 267 | t.Fatalf("turn ran %d times", len(coord.turns)) |
| 268 | } |
| 269 | // Drain: the runner reconnects and presents its generation. |
| 270 | write(t, c, wiretest.Fixture("frames/drain.json")) |
| 271 | c2 := <-inst.conns |
| 272 | _, raw = read(t, c2, wire.FrameHello) |
| 273 | var h wire.Frame |
| 274 | json.Unmarshal(raw, &h) |
| 275 | var hello wire.Hello |
| 276 | json.Unmarshal(h.Data, &hello) |
| 277 | if hello.Generation != 3 { |
| 278 | t.Fatalf("reconnect generation %d, want the granted 3", hello.Generation) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | func TestRunnerCancelAndSupersede(t *testing.T) { |
| 283 | testci.Quarantine(t) |
| 284 | inst := newFakeInstance(t) |
| 285 | coord := &stubCoordinator{} |
| 286 | _, _, _, done := startLink(t, inst.url, coord) |
| 287 | c := <-inst.conns |
| 288 | read(t, c, wire.FrameHello) |
| 289 | write(t, c, wiretest.Fixture("frames/welcome.json")) |
| 290 | read(t, c, wire.FrameSync) |
| 291 | msg, _ := wire.NewFrame("c9", wire.FrameMessage, wire.MessageCommand{Person: "owner@example.com", TurnID: "t_wait", Attempt: 1, Text: "wait for it", Tail: []wire.TailMessage{}}) |
| 292 | raw, _ := json.Marshal(msg) |
| 293 | write(t, c, raw) |
| 294 | read(t, c, wire.FrameAck) |
| 295 | cancelFrame, _ := wire.NewFrame("c10", wire.FrameCancel, wire.CancelCommand{Person: "owner@example.com", TurnID: "t_wait", Attempt: 1}) |
| 296 | raw, _ = json.Marshal(cancelFrame) |
| 297 | write(t, c, raw) |
| 298 | read(t, c, wire.FrameAck) |
| 299 | turn, raw := read(t, c, wire.FrameTurn) |
| 300 | var report wire.TurnReport |
| 301 | json.Unmarshal(turn.Data, &report) |
| 302 | if report.State != wire.TurnCancelled || report.TurnID != "t_wait" || report.Attempt != 1 { |
| 303 | t.Fatalf("cancel report %s", raw) |
| 304 | } |
| 305 | c.Close(wire.CloseSuperseded, "superseded") |
| 306 | select { |
| 307 | case err := <-done: |
| 308 | if err != ErrSuperseded { |
| 309 | t.Fatalf("link ended with %v", err) |
| 310 | } |
| 311 | case <-time.After(10 * time.Second): |
| 312 | t.Fatal("superseded runner kept running") |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // Recovery: a run the previous process held becomes attempt 2, once. |
| 317 | func TestRunnerRecovery(t *testing.T) { |
| 318 | ctx := context.Background() |
| 319 | dir := t.TempDir() |
| 320 | state, err := OpenState(ctx, dir) |
| 321 | if err != nil { |
| 322 | t.Fatal(err) |
| 323 | } |
| 324 | defer state.Close() |
| 325 | if err = state.Accept(ctx, "c1", wire.MessageCommand{Person: "p", TurnID: "t1", Attempt: 1, Text: "x"}); err != nil { |
| 326 | t.Fatal(err) |
| 327 | } |
| 328 | for i, want := range []wire.TurnReport{{TurnID: "t1", Attempt: 2, State: wire.TurnRunning}, {TurnID: "t1", Attempt: 2, State: wire.TurnFailed, Reason: "runner_restarted"}} { |
| 329 | if err = state.Recover(ctx); err != nil { |
| 330 | t.Fatal(err) |
| 331 | } |
| 332 | frames, _, _ := state.Unacked(ctx, 0) |
| 333 | var got wire.TurnReport |
| 334 | json.Unmarshal(frames[len(frames)-1].Data, &got) |
| 335 | if got != want { |
| 336 | t.Fatalf("recovery %d: %+v, want %+v", i, got, want) |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // login runs the official sign-in into a new dedicated home and records |
| 342 | // the observed email in the bindings for the runner's person. |
| 343 | func TestLogin(t *testing.T) { |
| 344 | root := t.TempDir() |
| 345 | self, _ := os.Executable() |
| 346 | bin := filepath.Join(root, "bin") |
| 347 | os.Mkdir(bin, 0700) |
| 348 | raw, _ := os.ReadFile(self) |
| 349 | claudePath := filepath.Join(bin, "claude") |
| 350 | if err := os.WriteFile(claudePath, raw, 0755); err != nil { |
| 351 | t.Fatal(err) |
| 352 | } |
| 353 | state := filepath.Join(root, "state") |
| 354 | os.Mkdir(state, 0700) |
| 355 | credential, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "t", Person: "owner@example.com"}}) |
| 356 | os.WriteFile(filepath.Join(state, "credentials.json"), credential, 0600) |
| 357 | config := filepath.Join(root, "config") |
| 358 | os.Mkdir(config, 0700) |
| 359 | c := runner.Config{StateDir: state, ClaudePath: claudePath, AccountBindingsPath: filepath.Join(config, "bindings.json")} |
| 360 | var out strings.Builder |
| 361 | // The official CLI is interactive; the fake signs in as this email. |
| 362 | command := func(ctx context.Context, binary string, args []string, dir string, env []string) error { |
| 363 | cmd := exec.CommandContext(ctx, binary, args...) |
| 364 | cmd.Dir, cmd.Env = dir, append(env, "FAKE_LOGIN_EMAIL=owner@example.com") |
| 365 | return cmd.Run() |
| 366 | } |
| 367 | err := Login(context.Background(), c, "claude", LoginOptions{Root: filepath.Join(root, "accounts"), Output: &out, Command: command}) |
| 368 | if err != nil { |
| 369 | t.Fatal(err) |
| 370 | } |
| 371 | if !strings.Contains(out.String(), "owner@example.com") || !strings.Contains(out.String(), "claude-1") { |
| 372 | t.Fatalf("output %q", out.String()) |
| 373 | } |
| 374 | bs, err := runner.LoadBindings(c.AccountBindingsPath) |
| 375 | if err != nil || len(bs) != 1 || bs[0].ID != "claude-1" || bs[0].PersonID != "owner@example.com" || bs[0].AccountID != "owner@example.com" || bs[0].ProviderHome != filepath.Join(root, "accounts", "claude-1") { |
| 376 | t.Fatalf("bindings %+v %v", bs, err) |
| 377 | } |
| 378 | // A second login gets the next home. |
| 379 | if err = Login(context.Background(), c, "claude", LoginOptions{Root: filepath.Join(root, "accounts"), Output: &out, Command: command}); err == nil { |
| 380 | t.Fatal("the same account was bound twice") |
| 381 | } |
| 382 | if _, err = os.Stat(filepath.Join(root, "accounts", "claude-2")); err != nil { |
| 383 | t.Fatalf("second home: %v", err) |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | func (s *stubCoordinator) count() int { s.mu.Lock(); defer s.mu.Unlock(); return len(s.turns) } |
| 388 | |
| 389 | // A run held from a previous process is not executed until the instance |
| 390 | // confirms this connection's lease. |
| 391 | func TestRunnerExecutesOnlyWithConfirmedLease(t *testing.T) { |
| 392 | inst := newFakeInstance(t) |
| 393 | coord := &stubCoordinator{} |
| 394 | startLink(t, inst.url, coord, func(s *State) { |
| 395 | if err := s.Accept(context.Background(), "c1", wire.MessageCommand{Person: "owner@example.com", TurnID: "t_held", Attempt: 1, Text: "hi", Tail: []wire.TailMessage{}}); err != nil { |
| 396 | t.Fatal(err) |
| 397 | } |
| 398 | }) |
| 399 | c := <-inst.conns |
| 400 | time.Sleep(300 * time.Millisecond) |
| 401 | if coord.count() != 0 { |
| 402 | t.Fatal("executed before any connection") |
| 403 | } |
| 404 | read(t, c, wire.FrameHello) |
| 405 | write(t, c, wiretest.Fixture("frames/welcome.json")) |
| 406 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 407 | defer cancel() |
| 408 | for { |
| 409 | _, raw, err := c.Read(ctx) |
| 410 | if err != nil { |
| 411 | t.Fatalf("no lease check: %v", err) |
| 412 | } |
| 413 | f, _, _ := wire.ParseFrame(raw) |
| 414 | if f.Type == wire.FrameLease { |
| 415 | if coord.count() != 0 { |
| 416 | t.Fatal("executed before the lease was confirmed") |
| 417 | } |
| 418 | time.Sleep(200 * time.Millisecond) |
| 419 | if coord.count() != 0 { |
| 420 | t.Fatal("executed without the lease ack") |
| 421 | } |
| 422 | ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 423 | rawAck, _ := json.Marshal(ack) |
| 424 | write(t, c, rawAck) |
| 425 | break |
| 426 | } |
| 427 | } |
| 428 | read(t, c, wire.FrameReply) |
| 429 | if coord.count() != 1 { |
| 430 | t.Fatalf("turns run %d", coord.count()) |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | // A cancel that arrives before its message holds the turn cancelled: the |
| 435 | // late message is never executed and termination is reported. |
| 436 | func TestRunnerCancelBeforeMessage(t *testing.T) { |
| 437 | inst := newFakeInstance(t) |
| 438 | coord := &stubCoordinator{} |
| 439 | startLink(t, inst.url, coord) |
| 440 | c := <-inst.conns |
| 441 | read(t, c, wire.FrameHello) |
| 442 | write(t, c, wiretest.Fixture("frames/welcome.json")) |
| 443 | read(t, c, wire.FrameSync) |
| 444 | cancelFrame, _ := wire.NewFrame("c20", wire.FrameCancel, wire.CancelCommand{Person: "owner@example.com", TurnID: "t_late", Attempt: 1}) |
| 445 | raw, _ := json.Marshal(cancelFrame) |
| 446 | write(t, c, raw) |
| 447 | msg, _ := wire.NewFrame("c21", wire.FrameMessage, wire.MessageCommand{Person: "owner@example.com", TurnID: "t_late", Attempt: 1, Text: "hi", Tail: []wire.TailMessage{}}) |
| 448 | raw, _ = json.Marshal(msg) |
| 449 | write(t, c, raw) |
| 450 | f, _ := read(t, c, wire.FrameTurn) |
| 451 | var report wire.TurnReport |
| 452 | json.Unmarshal(f.Data, &report) |
| 453 | if report.State != wire.TurnCancelled || report.TurnID != "t_late" || coord.count() != 0 { |
| 454 | t.Fatalf("report %+v after %d turns", report, coord.count()) |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | // Only the ack of a terminal report finishes a run; recovery keeps a |
| 459 | // durable cancel and reports it instead of retrying. |
| 460 | func TestRunnerRecoveryAcksAndCancels(t *testing.T) { |
| 461 | ctx := context.Background() |
| 462 | s, err := OpenState(ctx, t.TempDir()) |
| 463 | if err != nil { |
| 464 | t.Fatal(err) |
| 465 | } |
| 466 | defer s.Close() |
| 467 | s.Accept(ctx, "c1", wire.MessageCommand{Person: "p", TurnID: "t1", Attempt: 1, Text: "x"}) |
| 468 | if err = s.Recover(ctx); err != nil { |
| 469 | t.Fatal(err) |
| 470 | } |
| 471 | frames, _, _ := s.Unacked(ctx, 0) |
| 472 | announcement := frames[len(frames)-1].ID |
| 473 | // The retried attempt replies before the announcement's ack arrives. |
| 474 | held, _, _ := s.next(ctx, "p", wire.LaneCoordinator) |
| 475 | if err = s.Report(ctx, held, &wire.Reply{TurnID: "t1", Attempt: held.Attempt, Text: "done"}, nil, nil); err != nil { |
| 476 | t.Fatal(err) |
| 477 | } |
| 478 | if err = s.Acked(ctx, announcement); err != nil { |
| 479 | t.Fatal(err) |
| 480 | } |
| 481 | if sync, _ := s.Sync(ctx); len(sync.Runs) != 1 || sync.Runs[0].State != runReported { |
| 482 | t.Fatalf("acked recovery announcement finished the run before its reply was acked: %+v", sync.Runs) |
| 483 | } |
| 484 | s.Accept(ctx, "c2", wire.MessageCommand{Person: "p", TurnID: "t2", Attempt: 1, Text: "y"}) |
| 485 | if _, err = s.RequestCancel(ctx, "c3", wire.CancelCommand{Person: "p", TurnID: "t2", Attempt: 1}); err != nil { |
| 486 | t.Fatal(err) |
| 487 | } |
| 488 | if err = s.Recover(ctx); err != nil { |
| 489 | t.Fatal(err) |
| 490 | } |
| 491 | frames, _, _ = s.Unacked(ctx, 0) |
| 492 | var last wire.TurnReport |
| 493 | for _, f := range frames { |
| 494 | var r wire.TurnReport |
| 495 | if json.Unmarshal(f.Data, &r) == nil && r.TurnID == "t2" { |
| 496 | last = r |
| 497 | } |
| 498 | } |
| 499 | if last.State != wire.TurnCancelled { |
| 500 | t.Fatalf("recovery resurrected a cancelled turn: %+v", last) |
| 501 | } |
| 502 | if r, ok, _ := s.next(ctx, "p", wire.LaneCoordinator); ok && r.TurnID == "t2" { |
| 503 | t.Fatal("cancelled turn still runnable") |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | func TestSweepOrphans(t *testing.T) { |
| 508 | root := t.TempDir() |
| 509 | c := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state")} |
| 510 | keep := []string{filepath.Join(c.ScratchRoot, "homes", "unrelated"), filepath.Join(c.StateDir, "private")} |
| 511 | gone := []string{filepath.Join(c.ScratchRoot, "homes", "account-1"), filepath.Join(c.ScratchRoot, "homes", "config-1"), filepath.Join(c.ScratchRoot, "policy-1"), filepath.Join(c.WorkspaceRoot, "converse-1"), filepath.Join(c.StateDir, "coord-tool-1"), filepath.Join(c.ScratchRoot, "t", "123456")} |
| 512 | for _, d := range append(append([]string{}, keep...), gone...) { |
| 513 | os.MkdirAll(d, 0700) |
| 514 | } |
| 515 | if err := sweepOrphans(c); err != nil { |
| 516 | t.Fatal(err) |
| 517 | } |
| 518 | for _, d := range gone { |
| 519 | if _, err := os.Stat(d); err == nil { |
| 520 | t.Fatalf("%s survived", d) |
| 521 | } |
| 522 | } |
| 523 | for _, d := range keep { |
| 524 | if _, err := os.Stat(d); err != nil { |
| 525 | t.Fatalf("%s removed", d) |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | // Roots shared with another runner's state directory are refused before |
| 531 | // anything is swept; a root held by a running runner is refused too. |
| 532 | func TestPrepareRootsRefusesSharedRoots(t *testing.T) { |
| 533 | root := t.TempDir() |
| 534 | mine := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state-a")} |
| 535 | other := mine |
| 536 | other.StateDir = filepath.Join(root, "state-b") |
| 537 | release, err := prepareRoots(other) |
| 538 | if err != nil { |
| 539 | t.Fatal(err) |
| 540 | } |
| 541 | live := filepath.Join(other.ScratchRoot, "homes", "account-live") |
| 542 | os.MkdirAll(live, 0700) |
| 543 | if _, err = prepareRoots(other); err != ErrRootShared { |
| 544 | t.Fatalf("second claim while held: %v", err) |
| 545 | } |
| 546 | release() |
| 547 | if _, err = prepareRoots(mine); err != ErrRootShared { |
| 548 | t.Fatalf("roots of another state directory accepted: %v", err) |
| 549 | } |
| 550 | if _, err = os.Stat(live); err != nil { |
| 551 | t.Fatal("another runner's credential copy was swept") |
| 552 | } |
| 553 | again, err := prepareRoots(other) |
| 554 | if err != nil { |
| 555 | t.Fatalf("owner could not reclaim its roots: %v", err) |
| 556 | } |
| 557 | again() |
| 558 | } |
| 559 | |
| 560 | // Startup takes ownership before recovery: a second runner sharing the |
| 561 | // first one's roots is refused before any recovery or sweep runs, and the |
| 562 | // first runner's namespace record and scratch survive. |
| 563 | func TestStartupRefusesSharedRootsBeforeRecovery(t *testing.T) { |
| 564 | root := t.TempDir() |
| 565 | first := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state-a")} |
| 566 | second := first |
| 567 | second.StateDir = filepath.Join(root, "state-b") |
| 568 | release, err := startup(context.Background(), first, nil, func(context.Context) error { return nil }) |
| 569 | if err != nil { |
| 570 | t.Fatal(err) |
| 571 | } |
| 572 | defer release() |
| 573 | live := []string{filepath.Join(first.ScratchRoot, "attempt-0123456789abcdef0123456789abcdef"), filepath.Join(first.ScratchRoot, "homes", "account-live"), filepath.Join(first.ScratchRoot, "policy-live")} |
| 574 | for _, d := range live { |
| 575 | os.MkdirAll(d, 0700) |
| 576 | } |
| 577 | record := filepath.Join(first.ScratchRoot, "0123456789abcdef0123456789abcdef.json") |
| 578 | os.WriteFile(record, []byte("{}"), 0600) |
| 579 | recovered := false |
| 580 | if _, err = startup(context.Background(), second, nil, func(context.Context) error { recovered = true; return nil }); err != ErrRootShared { |
| 581 | t.Fatalf("second runner on shared roots: %v", err) |
| 582 | } |
| 583 | if recovered { |
| 584 | t.Fatal("recovery ran before root ownership was checked") |
| 585 | } |
| 586 | for _, p := range append(live, record) { |
| 587 | if _, err := os.Stat(p); err != nil { |
| 588 | t.Fatalf("the first runner's %s was touched", filepath.Base(p)) |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | |