package thintest import ( "context" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/chat" "amadan.net/oficina/equipo/internal/wire" ) // revoke revokes a runner as the owner. func (r *runnersRig) revoke(id string) { r.t.Helper() var revision int64 if err := r.inst.DB.Writer().QueryRow("SELECT revision FROM runners WHERE id = ?", id).Scan(&revision); err != nil { r.t.Fatal(err) } if err := r.inst.Store.RevokeRunner(r.ctx, equipo.Actor{Address: Owner}, id, revision); err != nil { r.t.Fatal(err) } } // Removing a primary keeps what it may have started its own until the // proof arrives: its running step is cancelled there, the replacement's // empty sync settles nothing, and Retry stays refused. A dispatch it never // started (protocol 2: no start authorization) moves to the replacement // as the next attempt, and the old attempt can never start. func TestContractRevokedPrimaryKeepsItsAttempts(t *testing.T) { r := newRunnersRig(t) ctx := r.ctx old := r.runner.Welcome.RunnerID oldGen := r.runner.Welcome.Generation running := taskID(t, r.call("v1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Running when revoked", "brief": "b"})) r.call("v2", wire.ToolStartTask, map[string]string{"task": running, "brief": "go"}) _, body := r.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) if !r.primary.lease(d.StepID, 1) { t.Fatal("start refused") } r.step("v-run", wire.StepReport{TaskID: running, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40), Findings: []wire.Finding{}}) unacked := taskID(t, r.call("v3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Dispatched, never acked", "brief": "b"})) r.call("v4", wire.ToolStartTask, map[string]string{"task": unacked, "brief": "go"}) r.runner.Close() r.revoke(old) token := r.inst.EnrolRunner(t).Token p, err := DialRunnerHello(ctx, r.inst.URL, token, primaryHello(0)) if err != nil { t.Fatal(err) } defer p.Close() if p.Welcome.Role != wire.RolePrimary { t.Fatalf("replacement welcome %+v", p.Welcome) } np := &peer{t: t, r: r.toolRig, fr: p} np.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}}) k, _ := r.client.Task(ctx, running) if s := k.Steps[0]; wire.StepTerminal(s.State) || s.Terminated || s.RunnerID != old { t.Fatalf("the replacement settled the removed primary's running attempt: %+v", s) } if _, err := r.client.RetryTask(ctx, running); Status(err) != 409 { t.Fatalf("retry of an unproven attempt: %v", err) } _, body = np.expect(wire.FrameDispatch) if d2 := body.(*wire.DispatchCommand); d2.TaskID != unacked || d2.Attempt != 2 { t.Fatalf("the never-started attempt %+v", d2) } // The removed primary may still report its proof; its old attempt of // the moved step can never start. back, err := DialRunnerHello(ctx, r.inst.URL, r.rig.runner, primaryHello(oldGen)) if err != nil { t.Fatal(err) } defer back.Close() bp := &peer{t: t, r: r.toolRig, fr: back} k, _ = r.client.Task(ctx, unacked) if bp.lease(k.Steps[0].ID, 1) { t.Fatal("a withdrawn attempt may start on the removed primary") } } // Never-dispatched waiting checks end on Cancel, locally: nothing is // sent to an empty runner id, and the task is cancelled at once. func TestContractCancelWaitingSteps(t *testing.T) { r := newRunnersRig(t) w, _ := r.newWorker("Tito Studio") w.fr.Close() time.Sleep(100 * time.Millisecond) task, _ := r.candidate("iOS waiting", true) if s := r.checksStep(task); s.Placement != wire.PlacementWaiting { t.Fatalf("not waiting %+v", s) } if _, err := r.client.CancelTask(r.ctx, task); err != nil { t.Fatal(err) } k, _ := r.client.Task(r.ctx, task) s := r.checksStep(task) if k.Stage != wire.StageCancelled || s.State != wire.StepCancelled || !s.Terminated { t.Fatalf("cancel of a waiting step: task %s step %+v", k.Stage, s) } var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE coalesce(runner_id, '') = '' AND kind IN (?, ?)", wire.FrameCancelStep, wire.FrameDispatch).Scan(&n); err != nil || n != 0 { t.Fatalf("%d commands to nobody: %v", n, err) } } // Engineering's pin survives the step's own save: a new task records the // runner its Engineering ran on. func TestContractEngineeringPinKept(t *testing.T) { r := newRunnersRig(t) task, _ := r.candidate("Pinned", false) k, err := r.client.Task(r.ctx, task) if err != nil || k.EngineeringRunner != r.runner.Welcome.RunnerID { t.Fatalf("pin %q, want %q: %v", k.EngineeringRunner, r.runner.Welcome.RunnerID, err) } } // startedOnWorker places checks on the only worker, starts the attempt, // takes the worker away for the offline limit (a fake clock), and has the // sweep withdraw the started attempt; the worker comes back to its cancel. func (r *runnersRig) startedOnWorker(title string) (task, step string, w *peer, sha string) { r.t.Helper() w, token := r.newWorker("Tito Studio") task, sha = r.candidate(title, true) _, body := w.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) if !w.lease(d.StepID, 1) { r.t.Fatal("start refused") } gen := w.fr.Welcome.Generation w.fr.Close() later := time.Now().UTC().Add(chat.OfflineLimit + time.Minute) r.inst.Store.Chat().SetClock(func() time.Time { return later }) if err := r.inst.Store.Chat().Place(r.ctx); err != nil { r.t.Fatal(err) } r.inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() }) w = r.dialWorker(token, "Tito Studio", gen) _, body = w.expect(wire.FrameCancelStep) if c := body.(*wire.CancelStepCommand); c.StepID != d.StepID || c.Attempt != 1 { r.t.Fatalf("cancel %+v", c) } return task, d.StepID, w, sha } // Withdrawal comes first (M6): a withdrawn attempt's delayed success does // not count; a failure without proof waits for the proof, and the proof // then places the next attempt; Retry works on that next attempt. func TestContractWithdrawnAttemptReports(t *testing.T) { r := newRunnersRig(t) task, step, w, sha := r.startedOnWorker("Withdrawn, then passed") w.send(wire.FrameStep, passed(task, step, 1, sha)) s := r.checksStep(task) if s.Checks == wire.ChecksPassed || s.Attempt != 2 { t.Fatalf("a withdrawn attempt's delayed success counted: %+v", s) } _, body := w.expect(wire.FrameDispatch) if d := body.(*wire.DispatchCommand); d.StepID != step || d.Attempt != 2 { t.Fatalf("next attempt %+v", d) } // Attempt 2 fails normally (with its proof): Retry gives attempt 3, // which may start. if !w.lease(step, 2) { t.Fatal("attempt 2 refused") } w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 2, State: wire.StepFailed, Reason: "provider_failed", Termination: true, Findings: []wire.Finding{}}) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 3 { t.Fatalf("retry after withdrawal %+v %v", acc, err) } w.expect(wire.FrameDispatch) if !w.lease(step, 3) { t.Fatal("attempt 3 refused after Retry") } } func TestContractWithdrawnProofAfterFailure(t *testing.T) { r := newRunnersRig(t) task, step, w, _ := r.startedOnWorker("Withdrawn, failed, proven") w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Findings: []wire.Finding{}}) if s := r.checksStep(task); s.Attempt != 1 || s.Terminated { t.Fatalf("before the proof %+v", s) } w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: step, Attempt: 1, State: wire.StepCancelled, Reason: "cancelled", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) _, body := w.expect(wire.FrameDispatch) if d := body.(*wire.DispatchCommand); d.StepID != step || d.Attempt != 2 { t.Fatalf("the proof did not place the next attempt: %+v", d) } } // A pack too large to relay is declared by its chunk count, and both ends // read it the same way: the checks end as not run (checks_unavailable). func TestContractTransferDeclaredTooLarge(t *testing.T) { r := newRunnersRig(t) w, _ := r.newWorker("Mac A") task, _ := r.candidate("iOS huge", true) _, body := r.primary.expect(wire.FrameSendPack) h := body.(*wire.SendPackCommand).Transfer w.expect(wire.FrameDispatch) c := chunk(h, []byte("PACK")) c.Total = wire.MaxTransferChunks + 1 r.primary.send(wire.FrameBlob, c) s := r.checksStep(task) if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != "checks_unavailable" { t.Fatalf("declared oversize %+v", s) } if n := r.relayed(w); n != 0 { t.Fatal("an oversized chunk was relayed") } } // Asking a specialist whose runner is offline is answered at once: the // runner is offline (runner_offline), nothing queues. func TestContractAskOfflineRunner(t *testing.T) { r := newToolRigAt(t, wire.ProtocolInjectionDefences) id, _, _ := r.askableTask("o", strings.Repeat("1", 40), strings.Repeat("2", 40)) r.runner.Close() deadline := time.Now().Add(5 * time.Second) for { runners, err := r.client.Runners(context.Background()) if err == nil && len(runners.Items) == 1 && !runners.Items[0].Online { break } if time.Now().After(deadline) { t.Fatalf("runner still online: %+v %v", runners, err) } time.Sleep(50 * time.Millisecond) } if _, err := r.client.Ask(r.ctx, id, "What did you change?", "", "off-1"); Status(err) != 409 || !strings.Contains(err.Error(), "runner_offline") { t.Fatalf("ask of an offline runner: %v", err) } if k, _ := r.client.Task(r.ctx, id); len(k.Questions) != 0 { t.Fatalf("a question queued for an offline runner: %+v", k.Questions) } }