package thin import ( "context" "encoding/json" "io" "log/slog" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // A worker's step reports below 37 (a rollback to an instance that // places no Engineering on a Mac): only a report positively of a step // this worker was dispatched that is not Engineering goes; any other is // kept for an instance that speaks 37. A report is classified by its own // task and step, whatever attempt the step has moved on to (a failover // advances it while earlier reports wait), and a classification that // fails keeps the frame. func TestWorkerReportsBelow37(t *testing.T) { ctx := context.Background() st, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } dispatch := func(id, specialist string) stepRow { t.Helper() d := wire.DispatchCommand{Person: "p@example.com", TaskID: "tk" + id, StepID: "s" + id, Attempt: 1, Specialist: specialist, Repo: "amadan.net/woodstar/panes", Branch: "equipo/tk" + id + "-panes", BaseSHA: "1111111111111111111111111111111111111111", Findings: []wire.Finding{}} if err := st.AcceptDispatch(ctx, "d-"+id, d); err != nil { t.Fatal(err) } return stepRow{DispatchCommand: d} } running := func(r stepRow) wire.StepReport { return wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepRunning, Findings: []wire.Finding{}} } eng, chk := dispatch("e", wire.SpecialistEngineering), dispatch("c", wire.SpecialistChecks) for _, r := range []stepRow{eng, chk} { if err := st.ReportStep(ctx, r, running(r)); err != nil { t.Fatal(err) } } // A failover: the Engineering step moves to attempt 2 while its // attempt 1 report still waits. if err := st.advanceStep(ctx, &eng, nil, running(eng)); err != nil || eng.Attempt != 2 { t.Fatalf("advance %v (attempt %d)", err, eng.Attempt) } frames, _, err := st.Unacked(ctx, 0) if err != nil { t.Fatal(err) } reports := map[string][]wire.Frame{} for _, f := range frames { if f.Type != wire.FrameStep { continue } body, _ := f.Decode() rep := body.(*wire.StepReport) reports[rep.StepID] = append(reports[rep.StepID], f) } if len(reports[eng.StepID]) != 2 || len(reports[chk.StepID]) != 1 { t.Fatalf("queued %v", reports) } for _, f := range reports[eng.StepID] { if !heldBelow37(st.holdBelow37(ctx, f, true, wire.Protocol35)) { t.Fatalf("an Engineering report %s was sent at 35", f.Data) } if heldBelow37(st.holdBelow37(ctx, f, true, wire.ProtocolMacEngineering)) || heldBelow37(st.holdBelow37(ctx, f, false, wire.Protocol35)) { t.Fatalf("held at 37, or on a primary: %s", f.Data) } } check := reports[chk.StepID][0] if heldBelow37(st.holdBelow37(ctx, check, true, wire.Protocol35)) { t.Fatal("a checks report was held at 35") } // Uncertain is kept: a report naming nothing dispatched here, a // dispatch that cannot be read, a database that cannot be read. stray, err := wire.NewFrame("stray", wire.FrameStep, wire.StepReport{TaskID: "tkz", StepID: "sz", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}}) if err != nil { t.Fatal(err) } if !heldBelow37(st.holdBelow37(ctx, stray, true, wire.Protocol35)) { t.Fatal("a report of no step here was sent at 35") } if _, err := st.db.Exec("UPDATE steps SET body='{' WHERE step_id=?", chk.StepID); err != nil { t.Fatal(err) } if !heldBelow37(st.holdBelow37(ctx, check, true, wire.Protocol35)) { t.Fatal("a report whose dispatch cannot be read was sent at 35") } st.Close() if !heldBelow37(st.holdBelow37(ctx, reports[eng.StepID][0], true, wire.Protocol35)) { t.Fatal("a report was sent at 35 when the state could not be read") } } func heldBelow37(hold bool, _ error) bool { return hold } // A protocol 35 worker (a rollback) told to cancel a step before the // step's dispatch arrives: the cancellation's record names no specialist // yet, so its report waits; the dispatch that follows says Checks, the // record takes that (still cancelled, never run), and the waiting report // goes on the same connection. Cancelled before an Engineering dispatch, // the report still waits for 37. func TestWorkerCancelBeforeDispatchBelow37(t *testing.T) { inst := newFakeInstance(t) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) st, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } t.Cleanup(func() { st.Close() }) link := &Link{Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Origin: inst.url, Token: "token", State: st, Role: wire.RoleWorker, WorkerOnly: true, Hello: func() wire.Hello { return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}} }} ran := make(chan string, 4) steps := &StepEngine{State: st, Notify: link.Notify, Exec: func(_ context.Context, r stepRow, _ func(wire.StepReport)) wire.StepReport { ran <- r.StepID return wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepDone, Termination: true, Findings: []wire.Finding{}} }} link.Steps = steps if err := steps.Start(ctx); err != nil { t.Fatal(err) } done := make(chan error, 1) go func() { done <- link.Run(ctx) }() t.Cleanup(func() { cancel(); <-done; steps.Wait() }) c := <-inst.conns read(t, c, wire.FrameHello) send := func(id, kind string, body any) { t.Helper() f, err := wire.NewFrame(id, kind, body) if err != nil { t.Fatal(err) } raw, _ := json.Marshal(f) write(t, c, raw) } send("i-welcome", wire.FrameWelcome, wire.Welcome{Generation: 1, RunnerID: "RUNNER2", Protocol: wire.Protocol35, Role: wire.RoleWorker}) reports := make(chan wire.StepReport, 8) go func() { for { _, raw, err := c.Read(context.Background()) if err != nil { return } if f, body, err := wire.ParseFrame(raw); err == nil && f.Type == wire.FrameStep { reports <- *body.(*wire.StepReport) } } }() // none: no report of step (any, for "") goes within a moment. A // report already sent and not acked may go again (the fake instance // never acks), as after a reconnect. none := func(what, step string) { t.Helper() deadline := time.After(1500 * time.Millisecond) for { select { case r := <-reports: if step == "" || r.StepID == step { t.Fatalf("%s: sent at 35 %+v", what, r) } case <-deadline: return } } } dispatch := func(id, specialist string) { send("i-d-"+id, wire.FrameDispatch, wire.DispatchCommand{Person: "p@example.com", TaskID: "tk" + id, StepID: "s" + id, Attempt: 1, Specialist: specialist, Repo: "amadan.net/woodstar/panes", Branch: "equipo/tk" + id + "-panes", BaseSHA: "1111111111111111111111111111111111111111", Findings: []wire.Finding{}}) } for _, id := range []string{"c", "e"} { send("i-c-"+id, wire.FrameCancelStep, wire.CancelStepCommand{Person: "p@example.com", TaskID: "tk" + id, StepID: "s" + id, Attempt: 1}) } none("a cancellation of a step not yet dispatched", "") dispatch("c", wire.SpecialistChecks) select { case r := <-reports: if r.StepID != "sc" || r.State != wire.StepCancelled || !r.Termination { t.Fatalf("the checks step's report %+v", r) } case <-time.After(10 * time.Second): t.Fatal("the cancelled checks step's report never went at 35") } dispatch("e", wire.SpecialistEngineering) none("the cancelled Engineering step's report", "se") select { case id := <-ran: t.Fatalf("a cancelled step ran: %s", id) default: } }