package thin import ( "bytes" "context" "database/sql" "encoding/json" "log/slog" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/wiretest" "github.com/coder/websocket" ) // syncBuffer is a log sink tests read while the link writes. type syncBuffer struct { mu sync.Mutex b bytes.Buffer } func (s *syncBuffer) Write(p []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() return s.b.Write(p) } func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } // olderInstance answers like a slice 4 instance: its strict decoder // refuses a hello with any field it does not know, closing with a policy // violation before any welcome. func olderInstance(t *testing.T, c *websocket.Conn) (refused bool, hello []byte) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _, raw, err := c.Read(ctx) if err != nil { t.Fatal(err) } if wiretest.SameShape(wiretest.Fixture("frames/hello.json"), raw) != nil { c.Close(websocket.StatusPolicyViolation, "hello first") return true, raw } write(t, c, wiretest.Fixture("frames/welcome.json")) return false, raw } // A new runner against an older instance: its current hello is refused // once, it says hello again at protocol 1 (exactly the slice 4 hello), logs // that the instance is older, and runs at protocol 1. func TestLinkFallsBackToProtocol1(t *testing.T) { inst := newFakeInstance(t) logs := &syncBuffer{} link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}, func(*State) {}) link.Logger = slog.New(slog.NewTextHandler(logs, nil)) first := <-inst.conns if refused, raw := olderInstance(t, first); !refused || !strings.Contains(string(raw), `"protocol":`+itoa(int64(wire.ProtocolCurrent))) { t.Fatalf("first hello was not the current protocol: %s", raw) } second := <-inst.conns if refused, raw := olderInstance(t, second); refused { t.Fatalf("second hello is not the slice 4 hello: %s", raw) } read(t, second, wire.FrameSync) if p, role := link.Spoken(); p != wire.Protocol1 || role != wire.RolePrimary { t.Fatalf("spoken %d %q", p, role) } if !strings.Contains(logs.String(), "the instance is older") { t.Fatalf("no log line: %s", logs.String()) } // Everything it sends now is the slice 4 wire: a step report with // protocol 2 fields goes without them. state := link.State if err := state.tx(context.Background(), func(tx *sql.Tx) error { 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)}}) }); err != nil { t.Fatal(err) } link.Notify() _, raw := read(t, second, wire.FrameStep) if strings.Contains(string(raw), "termination_kind") || strings.Contains(string(raw), "have") { t.Fatalf("protocol 2 fields sent at protocol 1: %s", raw) } } // A runner that can only be a worker never runs at protocol 1: refused by // an older instance, it does not say hello again, logs why, and waits. func TestWorkerRefusesAnOlderInstance(t *testing.T) { defer func(d time.Duration) { olderRetry = d }(olderRetry) olderRetry = time.Hour inst := newFakeInstance(t) logs := &syncBuffer{} link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}, func(*State) {}) link.Logger = slog.New(slog.NewTextHandler(logs, nil)) link.WorkerOnly = true first := <-inst.conns olderInstance(t, first) select { case c := <-inst.conns: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _, raw, _ := c.Read(ctx) t.Fatalf("worker said hello again: %s", raw) case <-time.After(1500 * time.Millisecond): } if !strings.Contains(logs.String(), "this runner is a worker and the instance is an older release") { t.Fatalf("no clear log line: %s", logs.String()) } } // The runner offers the current protocol; against a protocol 2 instance // it speaks protocol 2 and learns its role, and what it sends then has // no protocol 3 field (a usage row's turns), which that instance's // strict decoder would refuse. func TestLinkSpeaksProtocol2(t *testing.T) { inst := newFakeInstance(t) link, _, _, _ := startLink(t, inst.url, &stubCoordinator{}) c := <-inst.conns _, raw := read(t, c, wire.FrameHello) var f wire.Frame _ = json.Unmarshal(raw, &f) _, body, _ := wire.ParseFrame(raw) if body.(*wire.Hello).Protocol != wire.ProtocolCurrent { t.Fatalf("hello %s", raw) } write(t, c, wiretest.Fixture("frames/welcome-worker.json")) read(t, c, wire.FrameSync) if p, role := link.Spoken(); p != wire.Protocol2 || role != wire.RoleWorker { t.Fatalf("spoken %d %q", p, role) } n := int64(3) state := link.State // A worker reports only steps it was dispatched (and, below 37, only // those positively not Engineering: holdBelow37). 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 { t.Fatal(err) } if err := state.tx(context.Background(), func(tx *sql.Tx) error { 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}}}) }); err != nil { t.Fatal(err) } link.Notify() _, raw = read(t, c, wire.FrameStep) if strings.Contains(string(raw), `"turns"`) || !strings.Contains(string(raw), `"connection":"claude-1"`) { t.Fatalf("protocol 3 field sent at protocol 2: %s", raw) } } // A runner the instance made a worker stays one, whatever its OS: the // role is kept in its state; refused by an older instance it does not fall // back to protocol 1, and it never accepts a primary's welcome. func TestWorkerIdentityPersists(t *testing.T) { defer func(d time.Duration) { olderRetry = d }(olderRetry) olderRetry = time.Hour inst := newFakeInstance(t) logs := &syncBuffer{} link, state, _, _ := startLink(t, inst.url, &stubCoordinator{}) link.Logger = slog.New(slog.NewTextHandler(logs, nil)) c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome-worker.json")) read(t, c, wire.FrameSync) if role, _ := state.meta(context.Background(), "role"); role != wire.RoleWorker { t.Fatalf("role not kept: %q", role) } write(t, c, wiretest.Fixture("frames/drain.json")) older := <-inst.conns if refused, _ := olderInstance(t, older); !refused { t.Fatal("the worker's hello was not protocol 2") } select { case again := <-inst.conns: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _, raw, _ := again.Read(ctx) t.Fatalf("a worker fell back to protocol 1: %s", raw) case <-time.After(1500 * time.Millisecond): } } func TestWorkerRefusesAPrimaryWelcome(t *testing.T) { defer func(d time.Duration) { olderRetry = d }(olderRetry) olderRetry = time.Hour inst := newFakeInstance(t) _, _, _, _ = startLink(t, inst.url, &stubCoordinator{}, func(s *State) { if err := s.setMeta(context.Background(), "role", wire.RoleWorker); err != nil { t.Fatal(err) } }) c := <-inst.conns read(t, c, wire.FrameHello) raw, _ := json.Marshal(wire.Frame{ID: "w-p", Type: wire.FrameWelcome, Data: json.RawMessage(`{"generation":3,"runner_id":"RUNNER1","protocol":2,"role":"primary"}`)}) write(t, c, raw) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() for { _, msg, err := c.Read(ctx) if err != nil { return } if f, _, _ := wire.ParseFrame(msg); f.Type == wire.FrameSync { t.Fatalf("a worker served as primary: %s", msg) } } } // startLinkAs is startLink for a runner enrolled with role ("" when its // credential predates roles). func startLinkAs(t *testing.T, origin, role string) *Link { t.Helper() testEnrolledRole = role defer func() { testEnrolledRole = wire.RolePrimary }() link, _, _, _ := startLink(t, origin, &stubCoordinator{}) return link } // A worker enrolled with an instance that was then rolled back, before it // ever saw a welcome: its enrolled role keeps it from protocol 1. func TestEnrolledWorkerNeverFallsBack(t *testing.T) { defer func(d time.Duration) { olderRetry = d }(olderRetry) olderRetry = time.Hour inst := newFakeInstance(t) startLinkAs(t, inst.url, wire.RoleWorker) olderInstance(t, <-inst.conns) select { case <-inst.conns: t.Fatal("an enrolled worker said hello at protocol 1") case <-time.After(1500 * time.Millisecond): } } // A runner upgraded from before roles knows nothing of its own: it learns // its role from the instance at protocol 2 and, until then, never falls // back to protocol 1 (it might be a worker). func TestUnknownRoleWaitsForTheInstance(t *testing.T) { defer func(d time.Duration) { olderRetry = d }(olderRetry) olderRetry = time.Hour inst := newFakeInstance(t) link := startLinkAs(t, inst.url, "") olderInstance(t, <-inst.conns) select { case <-inst.conns: t.Fatal("a runner of unknown role fell back to protocol 1") case <-time.After(1500 * time.Millisecond): } _ = link } func TestUnknownRoleLearnsFromProtocol2(t *testing.T) { inst := newFakeInstance(t) link := startLinkAs(t, inst.url, "") c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome-worker.json")) read(t, c, wire.FrameSync) if role, _ := link.State.meta(context.Background(), "role"); role != wire.RoleWorker { t.Fatalf("role not learned: %q", role) } } // The first hello goes out before the instance has said which protocol // it speaks, and an older instance's strict decoder refuses a field it // does not know (and the runner would then fall back to protocol 1): so // it never says a repository is empty. After a protocol 6 welcome the // next hello, sent at once rather than at the heartbeat, carries the // empty repository; at protocol 5 no hello ever does. func TestHandshakeHelloLeavesOutEmptyRepos(t *testing.T) { const empty = "amadan.net/paulca/threatmin" hello := func() wire.Hello { return wire.Hello{Repos: []string{"amadan.net/oficina/sample", empty}, CreateIn: []string{}, Catalog: []wire.RepoInfo{ {Repo: "amadan.net/oficina/sample", DefaultBranch: "main", Names: []string{"sample"}, Hints: []string{}}, {Repo: empty, Names: []string{"threatmin"}, Hints: []string{}, Empty: true}, }, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}} } for _, protocol := range []int{wire.ProtocolHostedChecks, wire.ProtocolEmptyRepos} { inst := newFakeInstance(t) link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) c := <-inst.conns _, raw := read(t, c, wire.FrameHello) if strings.Contains(string(raw), `"empty"`) || !strings.Contains(string(raw), `"repo":"amadan.net/oficina/sample"`) || !strings.Contains(string(raw), `"protocol":`+itoa(int64(wire.ProtocolCurrent))) { t.Fatalf("handshake hello: %s", raw) } 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"}`)}) write(t, c, welcome) read(t, c, wire.FrameSync) if protocol < wire.ProtocolEmptyRepos { link.HelloSoon() } _, raw = read(t, c, wire.FrameHello) if got := strings.Contains(string(raw), `"empty":true`); got != (protocol >= wire.ProtocolEmptyRepos) { t.Fatalf("protocol %d hello: %s", protocol, raw) } var f wire.Frame _ = json.Unmarshal(raw, &f) var h wire.Hello if err := wire.Strict(f.Data, &h); err != nil || len(h.Repos) != 2 { t.Fatalf("protocol %d hello %+v %v", protocol, h, err) } } }