package thin import ( "context" "encoding/json" "errors" "os" "path/filepath" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) func dispatchFor(task, step string, attempt int64) wire.DispatchCommand { return wire.DispatchCommand{Person: "owner@example.com", TaskID: task, StepID: step, Attempt: attempt, Specialist: wire.SpecialistEngineering, Repo: "amadan.net/oficina/sample", Branch: "equipo/" + task + "-x", Findings: []wire.Finding{}} } func outbox(t *testing.T, s *State) []wire.StepReport { t.Helper() frames, _, err := s.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } var out []wire.StepReport for _, f := range frames { if f.Type == wire.FrameStep { var r wire.StepReport json.Unmarshal(f.Data, &r) out = append(out, r) } } return out } // TestStepStateCancelFirst: a cancel that arrives before its dispatch // holds the attempt cancelled; the late dispatch is never executed and // the instance still gets a termination report. func TestStepStateCancelFirst(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() if err := s.RequestStepCancel(ctx, "c1", wire.CancelStepCommand{Person: "owner@example.com", TaskID: "tk1", StepID: "s1", Attempt: 1}); err != nil { t.Fatal(err) } if err := s.AcceptDispatch(ctx, "c2", dispatchFor("tk1", "s1", 1)); err != nil { t.Fatal(err) } ran := false e := &StepEngine{State: s, Notify: func() {}, Exec: func(context.Context, stepRow, func(wire.StepReport)) wire.StepReport { ran = true return wire.StepReport{State: wire.StepDone} }} r, ok, err := s.nextStep(ctx) if err != nil || !ok || !r.Cancel { t.Fatalf("next %+v %v %v", r, ok, err) } e.runOne(ctx, r) reps := outbox(t, s) if ran || len(reps) != 1 || reps[0].State != wire.StepCancelled || !reps[0].Termination { t.Fatalf("ran %v reports %+v", ran, reps) } // A cancel for a running attempt is durable: a restart sees it. if err := s.AcceptDispatch(ctx, "c3", dispatchFor("tk2", "s2", 1)); err != nil { t.Fatal(err) } if err := s.RequestStepCancel(ctx, "c4", wire.CancelStepCommand{TaskID: "tk2", StepID: "s2", Attempt: 1}); err != nil { t.Fatal(err) } if r, _, _ := s.nextStep(ctx); r.StepID != "s2" || !r.Cancel || !s.stepCancelled(ctx, r) { t.Fatalf("cancel not recorded: %+v", r) } } // TestStepStateRecover: after a crash, an attempt that had not committed // ends failed with termination; a committed one keeps only its push; a // cancelled one ends cancelled. One attempt of a task runs at a time. func TestStepStateRecover(t *testing.T) { ctx := context.Background() dir := t.TempDir() s, err := OpenState(ctx, dir) if err != nil { t.Fatal(err) } for i, d := range []wire.DispatchCommand{dispatchFor("tka", "sa", 1), dispatchFor("tkb", "sb", 1), dispatchFor("tkc", "sc", 1)} { if err := s.AcceptDispatch(ctx, "f"+itoa(int64(i)), d); err != nil { t.Fatal(err) } } // A second running attempt of the same task is not held. if err := s.AcceptDispatch(ctx, "f9", dispatchFor("tka", "sa", 2)); err != nil { t.Fatal(err) } b, _, _ := s.nextStep(ctx) if err := s.setStepPhase(ctx, stepRow{DispatchCommand: dispatchFor("tkb", "sb", 1)}, phaseCommitted, "1111111111111111111111111111111111111111", "2222222222222222222222222222222222222222"); err != nil { t.Fatal(err) } if err := s.RequestStepCancel(ctx, "f10", wire.CancelStepCommand{TaskID: "tkc", StepID: "sc", Attempt: 1}); err != nil { t.Fatal(err) } _ = b s.Close() s, err = OpenState(ctx, dir) if err != nil { t.Fatal(err) } defer s.Close() if err := s.RecoverSteps(ctx, nil); err != nil { t.Fatal(err) } got := map[string]wire.StepReport{} for _, r := range outbox(t, s) { got[r.StepID] = r } if r := got["sa"]; r.State != wire.StepFailed || r.Reason != "runner_restarted" || !r.Termination || r.Attempt != 1 { t.Fatalf("sa %+v", r) } if r := got["sc"]; r.State != wire.StepCancelled || !r.Termination { t.Fatalf("sc %+v", r) } if _, ok := got["sb"]; ok { t.Fatal("a committed attempt was settled instead of pushed") } r, ok, _ := s.nextStep(ctx) if !ok || r.StepID != "sb" || r.Phase != phaseCommitted || r.Candidate == "" { t.Fatalf("committed attempt %+v", r) } sync, _ := s.Sync(ctx) if len(sync.Steps) != 3 { t.Fatalf("sync %+v", sync.Steps) } // The ack of a final report finishes the attempt. frames, _, _ := s.Unacked(ctx, 0) for _, f := range frames { if err := s.Acked(ctx, f.ID); err != nil { t.Fatal(err) } } if sync, _ = s.Sync(ctx); len(sync.Steps) != 1 || sync.Steps[0].StepID != "sb" { t.Fatalf("after acks %+v", sync.Steps) } } // TestEngineerRefusesOtherPersons: a dispatch for someone this runner // does not execute for, or for another branch or specialist, runs nothing. func TestEngineerRefusesOtherPersons(t *testing.T) { e := &Engineer{Owners: []string{"owner@example.com"}} for name, d := range map[string]wire.DispatchCommand{ "another person": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1) d.Person = "mallory@example.com" return d }(), "not a task branch": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1); d.Branch = "main"; return d }(), "bad repository": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1); d.Repo = "github.com/x/y"; return d }(), "another specialist": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1); d.Specialist = "review"; return d }(), } { ctx, cancel := context.WithTimeout(context.Background(), time.Second) rep := e.Exec(ctx, stepRow{DispatchCommand: d}, func(wire.StepReport) { t.Fatalf("%s: progressed", name) }) cancel() if rep.State != wire.StepFailed || rep.Reason != "policy_rejected" || !rep.Termination { t.Fatalf("%s: %+v", name, rep) } } } // TestStopStepNeedsVerifiedExit: a step's termination counts only when // the containment verified the namespace's exit; a Wait error (exit not // verified, proof not durable) or no exit at all is no termination, so // nothing is committed, published or retried on it. func TestStopStepNeedsVerifiedExit(t *testing.T) { for name, tc := range map[string]struct { wait error exit bool want bool }{ "verified": {nil, true, true}, "verify failed": {errors.New("exit proof not durable"), true, false}, "exit never seen": {nil, false, false}, } { exited := make(chan error, 1) killed := false kill := func() { killed = true if tc.exit { exited <- tc.wait } } if got := stopStep(func() {}, exited, kill, false, 10*time.Millisecond, 50*time.Millisecond); got != tc.want || !killed { t.Fatalf("%s: terminated %v (killed %v), want %v", name, got, killed, tc.want) } } } // TestStepFilesKeptUntilAcked: a step's private repository outlives its // push until the final report is acked; then it is swept. func TestStepFilesKeptUntilAcked(t *testing.T) { ctx := context.Background() state := t.TempDir() s, err := OpenState(ctx, state) if err != nil { t.Fatal(err) } defer s.Close() e := &Engineer{} e.O.Runner.StateDir = state d := dispatchFor("tk6", "s6", 1) if err := s.AcceptDispatch(ctx, "f1", d); err != nil { t.Fatal(err) } r, _, _ := s.nextStep(ctx) dir := filepath.Join(e.root(), stepKey(r)) if err := os.MkdirAll(filepath.Join(dir, "git"), 0700); err != nil { t.Fatal(err) } if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: "tk6", StepID: "s6", Attempt: 1, State: wire.StepDone, Pushed: true, Termination: true}); err != nil { t.Fatal(err) } e.Sweep(ctx, s) if _, err := os.Stat(dir); err != nil { t.Fatalf("swept before the report was acked: %v", err) } frames, _, _ := s.Unacked(ctx, 0) for _, f := range frames { if err := s.Acked(ctx, f.ID); err != nil { t.Fatal(err) } } e.Sweep(ctx, s) if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) { t.Fatalf("kept after the ack: %v", err) } } // TestStepPendingTermination: an attempt that ended without a verified // exit stays pending, through its ack and a restart, until a probe // verifies the namespace's exit; then a follow-up report carries the // termination, so the instance can allow Retry. func TestStepPendingTermination(t *testing.T) { ctx := context.Background() dir := t.TempDir() s, err := OpenState(ctx, dir) if err != nil { t.Fatal(err) } if err := s.AcceptDispatch(ctx, "f1", dispatchFor("tk7", "s7", 1)); err != nil { t.Fatal(err) } r, _, _ := s.nextStep(ctx) if err := s.setStepNamespace(ctx, r, "ns-7"); err != nil { t.Fatal(err) } if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: "tk7", StepID: "s7", Attempt: 1, State: wire.StepFailed, Reason: "provider_failed"}); err != nil { t.Fatal(err) } ack := func() { frames, _, _ := s.Unacked(ctx, 0) for _, f := range frames { s.Acked(ctx, f.ID) } } ack() s.Close() if s, err = OpenState(ctx, dir); err != nil { t.Fatal(err) } defer s.Close() verified := false verify := func(_ context.Context, id string) bool { return id == "ns-7" && verified } e := &StepEngine{State: s, Notify: func() {}, Verify: verify} e.Probe(ctx) if reps := outbox(t, s); len(reps) != 0 { t.Fatalf("reported without proof: %+v", reps) } verified = true e.Probe(ctx) reps := outbox(t, s) if len(reps) != 1 || reps[0].State != wire.StepFailed || reps[0].Reason != "provider_failed" || !reps[0].Termination { t.Fatalf("follow-up %+v", reps) } e.Probe(ctx) if len(outbox(t, s)) != 1 { t.Fatal("follow-up sent twice") } ack() if steps, _ := s.finishedSteps(ctx); len(steps) != 1 { t.Fatalf("not finished after the follow-up's ack: %+v", steps) } } // TestStepRecoverWithoutProof: after a crash, a running attempt whose // namespace exit cannot be verified is reported failed without // termination and stays pending for later probes. func TestStepRecoverWithoutProof(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() s.AcceptDispatch(ctx, "f1", dispatchFor("tk8", "s8", 1)) r, _, _ := s.nextStep(ctx) s.setStepNamespace(ctx, r, "ns-8") if err := s.RecoverSteps(ctx, func(context.Context, string) bool { return false }); err != nil { t.Fatal(err) } reps := outbox(t, s) if len(reps) != 1 || reps[0].Termination || reps[0].Reason != "runner_restarted" { t.Fatalf("recovered %+v", reps) } if p, _ := s.pendingSteps(ctx); len(p) != 1 || p[0].ns != "ns-8" { t.Fatalf("pending %+v", p) } } // TestSyncHoldsPendingTermination: an attempt whose failure report (no // termination proof) is not yet acked, and one still waiting for its // proof after the ack, are both in sync: present, termination // unverified. Only an attempt the runner has finished is absent. func TestSyncHoldsPendingTermination(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() s.AcceptDispatch(ctx, "f1", dispatchFor("tk9", "s9", 1)) r, _, _ := s.nextStep(ctx) if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: "tk9", StepID: "s9", Attempt: 1, State: wire.StepFailed, Reason: "provider_failed"}); err != nil { t.Fatal(err) } held := func() []wire.StepRun { sync, err := s.Sync(ctx) if err != nil { t.Fatal(err) } return sync.Steps } if h := held(); len(h) != 1 || h[0].StepID != "s9" || h[0].State != runPending { t.Fatalf("unacked pending report: %+v", h) } frames, _, _ := s.Unacked(ctx, 0) for _, f := range frames { s.Acked(ctx, f.ID) } if h := held(); len(h) != 1 || h[0].State != runPending { t.Fatalf("acked, proof still pending: %+v", h) } } // An attempt that recorded nothing before the crash is not ended by // default: verify is asked about it by name (UnrecordedStep), and while // unproven it stays pending under that record. func TestStepRecoverUnrecorded(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() s.AcceptDispatch(ctx, "f1", dispatchFor("tk9", "s9", 1)) r, _, _ := s.nextStep(ctx) var asked []string if err := s.RecoverSteps(ctx, func(_ context.Context, id string) bool { asked = append(asked, id); return false }); err != nil { t.Fatal(err) } if len(asked) != 1 || asked[0] != UnrecordedStep(r.key()) { t.Fatalf("asked %v", asked) } if reps := outbox(t, s); len(reps) != 1 || reps[0].Termination { t.Fatalf("an unrecorded attempt counted as ended: %+v", reps) } if p, _ := s.pendingSteps(ctx); len(p) != 1 || p[0].ns != UnrecordedStep(r.key()) { t.Fatalf("pending %+v", p) } }