| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "log/slog" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "amadan.net/oficina/equipo/internal/wire/wiretest" |
| 16 | "github.com/coder/websocket" |
| 17 | ) |
| 18 | |
| 19 | // syncBuffer is a log sink tests read while the link writes. |
| 20 | type syncBuffer struct { |
| 21 | mu sync.Mutex |
| 22 | b bytes.Buffer |
| 23 | } |
| 24 | |
| 25 | func (s *syncBuffer) Write(p []byte) (int, error) { |
| 26 | s.mu.Lock() |
| 27 | defer s.mu.Unlock() |
| 28 | return s.b.Write(p) |
| 29 | } |
| 30 | func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } |
| 31 | |
| 32 | // olderInstance answers like a slice 4 instance: its strict decoder |
| 33 | // refuses a hello with any field it does not know, closing with a policy |
| 34 | // violation before any welcome. |
| 35 | func olderInstance(t *testing.T, c *websocket.Conn) (refused bool, hello []byte) { |
| 36 | t.Helper() |
| 37 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 38 | defer cancel() |
| 39 | _, raw, err := c.Read(ctx) |
| 40 | if err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | if wiretest.SameShape(wiretest.Fixture("frames/hello.json"), raw) != nil { |
| 44 | c.Close(websocket.StatusPolicyViolation, "hello first") |
| 45 | return true, raw |
| 46 | } |
| 47 | write(t, c, wiretest.Fixture("frames/welcome.json")) |
| 48 | return false, raw |
| 49 | } |
| 50 | |
| 51 | // A new runner against an older instance: its current hello is refused |
| 52 | // once, it says hello again at protocol 1 (exactly the slice 4 hello), logs |
| 53 | // that the instance is older, and runs at protocol 1. |
| 54 | func TestLinkFallsBackToProtocol1(t *testing.T) { |
| 55 | inst := newFakeInstance(t) |
| 56 | logs := &syncBuffer{} |
| 57 | link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}, func(*State) {}) |
| 58 | link.Logger = slog.New(slog.NewTextHandler(logs, nil)) |
| 59 | first := <-inst.conns |
| 60 | if refused, raw := olderInstance(t, first); !refused || !strings.Contains(string(raw), `"protocol":`+itoa(int64(wire.ProtocolCurrent))) { |
| 61 | t.Fatalf("first hello was not the current protocol: %s", raw) |
| 62 | } |
| 63 | second := <-inst.conns |
| 64 | if refused, raw := olderInstance(t, second); refused { |
| 65 | t.Fatalf("second hello is not the slice 4 hello: %s", raw) |
| 66 | } |
| 67 | read(t, second, wire.FrameSync) |
| 68 | if p, role := link.Spoken(); p != wire.Protocol1 || role != wire.RolePrimary { |
| 69 | t.Fatalf("spoken %d %q", p, role) |
| 70 | } |
| 71 | if !strings.Contains(logs.String(), "the instance is older") { |
| 72 | t.Fatalf("no log line: %s", logs.String()) |
| 73 | } |
| 74 | // Everything it sends now is the slice 4 wire: a step report with |
| 75 | // protocol 2 fields goes without them. |
| 76 | state := link.State |
| 77 | if err := state.tx(context.Background(), func(tx *sql.Tx) error { |
| 78 | return state.enqueue(tx, wire.FrameStep, "", wire.StepReport{TaskID: "tk1", StepID: "s1", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}, TerminationKind: wire.TerminationProcessGroup, Have: []string{strings.Repeat("2", 40)}}) |
| 79 | }); err != nil { |
| 80 | t.Fatal(err) |
| 81 | } |
| 82 | link.Notify() |
| 83 | _, raw := read(t, second, wire.FrameStep) |
| 84 | if strings.Contains(string(raw), "termination_kind") || strings.Contains(string(raw), "have") { |
| 85 | t.Fatalf("protocol 2 fields sent at protocol 1: %s", raw) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // A runner that can only be a worker never runs at protocol 1: refused by |
| 90 | // an older instance, it does not say hello again, logs why, and waits. |
| 91 | func TestWorkerRefusesAnOlderInstance(t *testing.T) { |
| 92 | defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| 93 | olderRetry = time.Hour |
| 94 | inst := newFakeInstance(t) |
| 95 | logs := &syncBuffer{} |
| 96 | link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}, func(*State) {}) |
| 97 | link.Logger = slog.New(slog.NewTextHandler(logs, nil)) |
| 98 | link.WorkerOnly = true |
| 99 | first := <-inst.conns |
| 100 | olderInstance(t, first) |
| 101 | select { |
| 102 | case c := <-inst.conns: |
| 103 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 104 | defer cancel() |
| 105 | _, raw, _ := c.Read(ctx) |
| 106 | t.Fatalf("worker said hello again: %s", raw) |
| 107 | case <-time.After(1500 * time.Millisecond): |
| 108 | } |
| 109 | if !strings.Contains(logs.String(), "this runner is a worker and the instance is an older release") { |
| 110 | t.Fatalf("no clear log line: %s", logs.String()) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // The runner offers the current protocol; against a protocol 2 instance |
| 115 | // it speaks protocol 2 and learns its role, and what it sends then has |
| 116 | // no protocol 3 field (a usage row's turns), which that instance's |
| 117 | // strict decoder would refuse. |
| 118 | func TestLinkSpeaksProtocol2(t *testing.T) { |
| 119 | inst := newFakeInstance(t) |
| 120 | link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}) |
| 121 | c := <-inst.conns |
| 122 | _, raw := read(t, c, wire.FrameHello) |
| 123 | var f wire.Frame |
| 124 | _ = json.Unmarshal(raw, &f) |
| 125 | _, body, _ := wire.ParseFrame(raw) |
| 126 | if body.(*wire.Hello).Protocol != wire.ProtocolCurrent { |
| 127 | t.Fatalf("hello %s", raw) |
| 128 | } |
| 129 | write(t, c, wiretest.Fixture("frames/welcome-worker.json")) |
| 130 | read(t, c, wire.FrameSync) |
| 131 | if p, role := link.Spoken(); p != wire.Protocol2 || role != wire.RoleWorker { |
| 132 | t.Fatalf("spoken %d %q", p, role) |
| 133 | } |
| 134 | n := int64(3) |
| 135 | state := link.State |
| 136 | // A worker reports only steps it was dispatched (and, below 37, only |
| 137 | // those positively not Engineering: holdBelow37). |
| 138 | if err := state.AcceptDispatch(context.Background(), "d-s1", wire.DispatchCommand{Person: "p@example.com", TaskID: "tk1", StepID: "s1", Attempt: 1, Specialist: wire.SpecialistChecks, Findings: []wire.Finding{}}); err != nil { |
| 139 | t.Fatal(err) |
| 140 | } |
| 141 | if err := state.tx(context.Background(), func(tx *sql.Tx) error { |
| 142 | return state.enqueue(tx, wire.FrameStep, "", wire.StepReport{TaskID: "tk1", StepID: "s1", Attempt: 1, State: wire.StepDone, Findings: []wire.Finding{}, Termination: true, Usage: []wire.Usage{{Provider: "claude", Connection: "claude-1", Model: "m", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, Turns: &n}}}) |
| 143 | }); err != nil { |
| 144 | t.Fatal(err) |
| 145 | } |
| 146 | link.Notify() |
| 147 | _, raw = read(t, c, wire.FrameStep) |
| 148 | if strings.Contains(string(raw), `"turns"`) || !strings.Contains(string(raw), `"connection":"claude-1"`) { |
| 149 | t.Fatalf("protocol 3 field sent at protocol 2: %s", raw) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | // A runner the instance made a worker stays one, whatever its OS: the |
| 154 | // role is kept in its state; refused by an older instance it does not fall |
| 155 | // back to protocol 1, and it never accepts a primary's welcome. |
| 156 | func TestWorkerIdentityPersists(t *testing.T) { |
| 157 | defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| 158 | olderRetry = time.Hour |
| 159 | inst := newFakeInstance(t) |
| 160 | logs := &syncBuffer{} |
| 161 | link, state, _, _ := startLink(t, inst.url, &stubCoordinator{}) |
| 162 | link.Logger = slog.New(slog.NewTextHandler(logs, nil)) |
| 163 | c := <-inst.conns |
| 164 | read(t, c, wire.FrameHello) |
| 165 | write(t, c, wiretest.Fixture("frames/welcome-worker.json")) |
| 166 | read(t, c, wire.FrameSync) |
| 167 | if role, _ := state.meta(context.Background(), "role"); role != wire.RoleWorker { |
| 168 | t.Fatalf("role not kept: %q", role) |
| 169 | } |
| 170 | write(t, c, wiretest.Fixture("frames/drain.json")) |
| 171 | older := <-inst.conns |
| 172 | if refused, _ := olderInstance(t, older); !refused { |
| 173 | t.Fatal("the worker's hello was not protocol 2") |
| 174 | } |
| 175 | select { |
| 176 | case again := <-inst.conns: |
| 177 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 178 | defer cancel() |
| 179 | _, raw, _ := again.Read(ctx) |
| 180 | t.Fatalf("a worker fell back to protocol 1: %s", raw) |
| 181 | case <-time.After(1500 * time.Millisecond): |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | func TestWorkerRefusesAPrimaryWelcome(t *testing.T) { |
| 186 | defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| 187 | olderRetry = time.Hour |
| 188 | inst := newFakeInstance(t) |
| 189 | _, _, _, _ = startLink(t, inst.url, &stubCoordinator{}, func(s *State) { |
| 190 | if err := s.setMeta(context.Background(), "role", wire.RoleWorker); err != nil { |
| 191 | t.Fatal(err) |
| 192 | } |
| 193 | }) |
| 194 | c := <-inst.conns |
| 195 | read(t, c, wire.FrameHello) |
| 196 | raw, _ := json.Marshal(wire.Frame{ID: "w-p", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":2,"role":"primary"}`)}) |
| 197 | write(t, c, raw) |
| 198 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 199 | defer cancel() |
| 200 | for { |
| 201 | _, msg, err := c.Read(ctx) |
| 202 | if err != nil { |
| 203 | return |
| 204 | } |
| 205 | if f, _, _ := wire.ParseFrame(msg); f.Type == wire.FrameSync { |
| 206 | t.Fatalf("a worker served as primary: %s", msg) |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // startLinkAs is startLink for a runner enrolled with role ("" when its |
| 212 | // credential predates roles). |
| 213 | func startLinkAs(t *testing.T, origin, role string) *Link { |
| 214 | t.Helper() |
| 215 | testEnrolledRole = role |
| 216 | defer func() { testEnrolledRole = wire.RolePrimary }() |
| 217 | link, _, _, _ := startLink(t, origin, &stubCoordinator{}) |
| 218 | return link |
| 219 | } |
| 220 | |
| 221 | // A worker enrolled with an instance that was then rolled back, before it |
| 222 | // ever saw a welcome: its enrolled role keeps it from protocol 1. |
| 223 | func TestEnrolledWorkerNeverFallsBack(t *testing.T) { |
| 224 | defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| 225 | olderRetry = time.Hour |
| 226 | inst := newFakeInstance(t) |
| 227 | startLinkAs(t, inst.url, wire.RoleWorker) |
| 228 | olderInstance(t, <-inst.conns) |
| 229 | select { |
| 230 | case <-inst.conns: |
| 231 | t.Fatal("an enrolled worker said hello at protocol 1") |
| 232 | case <-time.After(1500 * time.Millisecond): |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // A runner upgraded from before roles knows nothing of its own: it learns |
| 237 | // its role from the instance at protocol 2 and, until then, never falls |
| 238 | // back to protocol 1 (it might be a worker). |
| 239 | func TestUnknownRoleWaitsForTheInstance(t *testing.T) { |
| 240 | defer func(d time.Duration) { olderRetry = d }(olderRetry) |
| 241 | olderRetry = time.Hour |
| 242 | inst := newFakeInstance(t) |
| 243 | link := startLinkAs(t, inst.url, "") |
| 244 | olderInstance(t, <-inst.conns) |
| 245 | select { |
| 246 | case <-inst.conns: |
| 247 | t.Fatal("a runner of unknown role fell back to protocol 1") |
| 248 | case <-time.After(1500 * time.Millisecond): |
| 249 | } |
| 250 | _ = link |
| 251 | } |
| 252 | |
| 253 | func TestUnknownRoleLearnsFromProtocol2(t *testing.T) { |
| 254 | inst := newFakeInstance(t) |
| 255 | link := startLinkAs(t, inst.url, "") |
| 256 | c := <-inst.conns |
| 257 | read(t, c, wire.FrameHello) |
| 258 | write(t, c, wiretest.Fixture("frames/welcome-worker.json")) |
| 259 | read(t, c, wire.FrameSync) |
| 260 | if role, _ := link.State.meta(context.Background(), "role"); role != wire.RoleWorker { |
| 261 | t.Fatalf("role not learned: %q", role) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // The first hello goes out before the instance has said which protocol |
| 266 | // it speaks, and an older instance's strict decoder refuses a field it |
| 267 | // does not know (and the runner would then fall back to protocol 1): so |
| 268 | // it never says a repository is empty. After a protocol 6 welcome the |
| 269 | // next hello, sent at once rather than at the heartbeat, carries the |
| 270 | // empty repository; at protocol 5 no hello ever does. |
| 271 | func TestHandshakeHelloLeavesOutEmptyRepos(t *testing.T) { |
| 272 | const empty = "amadan.net/paulca/threatmin" |
| 273 | hello := func() wire.Hello { |
| 274 | return wire.Hello{Repos: []string{"amadan.net/oficina/sample", empty}, CreateIn: []string{}, Catalog: []wire.RepoInfo{ |
| 275 | {Repo: "amadan.net/oficina/sample", DefaultBranch: "main", Names: []string{"sample"}, Hints: []string{}}, |
| 276 | {Repo: empty, Names: []string{"threatmin"}, Hints: []string{}, Empty: true}, |
| 277 | }, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}} |
| 278 | } |
| 279 | for _, protocol := range []int{wire.ProtocolHostedChecks, wire.ProtocolEmptyRepos} { |
| 280 | inst := newFakeInstance(t) |
| 281 | link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) |
| 282 | c := <-inst.conns |
| 283 | _, raw := read(t, c, wire.FrameHello) |
| 284 | if strings.Contains(string(raw), `"empty"`) || !strings.Contains(string(raw), `"repo":"amadan.net/oficina/sample"`) || !strings.Contains(string(raw), `"protocol":`+itoa(int64(wire.ProtocolCurrent))) { |
| 285 | t.Fatalf("handshake hello: %s", raw) |
| 286 | } |
| 287 | welcome, _ := json.Marshal(wire.Frame{ID: "w-e", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":` + itoa(int64(protocol)) + `,"role":"primary"}`)}) |
| 288 | write(t, c, welcome) |
| 289 | read(t, c, wire.FrameSync) |
| 290 | if protocol < wire.ProtocolEmptyRepos { |
| 291 | link.HelloSoon() |
| 292 | } |
| 293 | _, raw = read(t, c, wire.FrameHello) |
| 294 | if got := strings.Contains(string(raw), `"empty":true`); got != (protocol >= wire.ProtocolEmptyRepos) { |
| 295 | t.Fatalf("protocol %d hello: %s", protocol, raw) |
| 296 | } |
| 297 | var f wire.Frame |
| 298 | _ = json.Unmarshal(raw, &f) |
| 299 | var h wire.Hello |
| 300 | if err := wire.Strict(f.Data, &h); err != nil || len(h.Repos) != 2 { |
| 301 | t.Fatalf("protocol %d hello %+v %v", protocol, h, err) |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | |