package thin import ( "context" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // Engineering is told its time limit, and to run targeted tests rather // than the repository's full gate (the Checks step runs that): the // stopped-jobs audit's example 2 spent 17 of its 20 minutes in make ci. func TestStepPromptStatesLimit(t *testing.T) { for _, c := range []struct { max time.Duration says string }{{0, "20 minutes"}, {35 * time.Minute, "35 minutes"}} { e := &Engineer{MaxStep: c.max} for name, prompt := range map[string]string{"step": e.stepPrompt(stepRow{}, false, claude.LinuxWorkspaceRoot), "fix": e.fixPrompt(stepRow{}, claude.LinuxWorkspaceRoot), "rebase": e.rebasePrompt(stepRow{}, nil, claude.LinuxWorkspaceRoot)} { if !strings.Contains(prompt, c.says) { t.Errorf("%s prompt at %v does not state %q:\n%s", name, c.max, c.says, prompt) } if !strings.Contains(prompt, "Run targeted tests; the Checks step runs the full gate") || strings.Contains(prompt, "documented gates") { t.Errorf("%s prompt still asks for the full gate:\n%s", name, prompt) } } } } // A step that runs out of time after changing the tree keeps its work: // Equipo commits and pushes it to the task branch as for a finished step, // and reports it done with the reason step_timeout, so the instance runs // checks on it and knows it is unfinished. One that changed nothing // fails step_timeout as before. func TestTimeoutKeepsChanges(t *testing.T) { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() r.e.MaxStep = 3 * time.Second r.e.Spoken = func() int { return wire.ProtocolUnfinishedWork } remote := r.e.Forge.(*hubForge).dir // The rig's remote names a task branch at HEAD; a hub names main. gitOut(t, remote, "--git-dir="+remote, "symbolic-ref", "HEAD", "refs/heads/main") rep := r.engineering("tk1", "e1", "edit:README.md|teh|the sleep:60000") if rep.State != wire.StepDone || rep.Reason != "step_timeout" || !rep.Pushed || rep.CandidateSHA == "" || !rep.Termination { t.Fatalf("timed out with changes: %+v", rep) } if got := gitOut(t, remote, "--git-dir="+remote, "rev-parse", "refs/heads/equipo/tk1-fix"); got != rep.CandidateSHA { t.Fatalf("branch at %q, want the reported candidate %q", got, rep.CandidateSHA) } if msg := gitOut(t, remote, "--git-dir="+remote, "log", "-1", "--format=%B", rep.CandidateSHA); !strings.Contains(msg, "ran out of time") { t.Fatalf("commit not marked unfinished: %q", msg) } // Its own rig: a metered step that timed out leaves its spend unknown, // which holds the connection's next step. r = newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() r.e.MaxStep = 3 * time.Second r.e.Spoken = func() int { return wire.ProtocolUnfinishedWork } rep = r.engineering("tk2", "e2", "nothing to do sleep:60000") if rep.State != wire.StepFailed || rep.Reason != "step_timeout" || rep.Pushed || rep.CandidateSHA != "" { t.Fatalf("timed out with nothing: %+v", rep) } } // An instance that does not know unfinished work (below // ProtocolUnfinishedWork), or none connected, would take the pushed work // for finished: the step fails step_timeout as before and pushes nothing. func TestTimeoutKeepsNothingForAnOlderInstance(t *testing.T) { for _, spoken := range []int{0, wire.ProtocolStuckTasks, wire.ProtocolChangeFiles} { r := newPiRig(t, fakePiInstall(t), bigBudget) r.urgent() r.e.MaxStep = 3 * time.Second r.e.Spoken = func() int { return spoken } remote := r.e.Forge.(*hubForge).dir gitOut(t, remote, "--git-dir="+remote, "symbolic-ref", "HEAD", "refs/heads/main") rep := r.engineering("tk1", "e1", "edit:README.md|teh|the sleep:60000") if rep.State != wire.StepFailed || rep.Reason != "step_timeout" || rep.Pushed || rep.CandidateSHA != "" { t.Fatalf("protocol %d: %+v", spoken, rep) } } } // EQUIPO_RUNNER_MAX_STEP sets Engineering's step limit, a Go duration of // 5 to 60 minutes (the stall sweep takes back a step running 90); any // other value, or none, leaves the default 20. func TestMaxStepFromEnv(t *testing.T) { for value, want := range map[string]time.Duration{ "": DefaultMaxStep, "40m": 40 * time.Minute, "5m": 5 * time.Minute, "1h": time.Hour, "4m59s": DefaultMaxStep, "61m": DefaultMaxStep, "-30m": DefaultMaxStep, "forty": DefaultMaxStep, "40": DefaultMaxStep, } { o := OptionsFromEnv(func(k string) string { if k == "EQUIPO_RUNNER_MAX_STEP" { return value } return "" }) if o.MaxStep != want { t.Errorf("EQUIPO_RUNNER_MAX_STEP=%q: %v, want %v", value, o.MaxStep, want) } } } // A runner that stopped after committing a timed-out step's work, before // the push, pushes it on recovery and still reports it unfinished. func TestTimeoutKeptAcrossRestart(t *testing.T) { e, f, r, _ := hubRig(t) r.Specialist, r.StepID, r.Branch, r.Person = wire.SpecialistEngineering, "s2", "equipo/tk1-another-fix", "p@x" base := gitOut(t, f.dir, "rev-parse", "main") gitDir := e.tree(r, base).GitDir gitOut(t, filepath.Dir(f.dir), "clone", "-q", "--bare", f.dir, gitDir) tree := gitOut(t, filepath.Dir(f.dir), "--git-dir="+gitDir, "rev-parse", base+"^{tree}") r.Base, r.Candidate = base, gitOut(t, filepath.Dir(f.dir), "--git-dir="+gitDir, "commit-tree", tree, "-p", base, "-m", "unfinished") for phase, reason := range map[string]string{phaseCommittedUnfinished: "step_timeout", phaseCommittedNoShell: wire.ReasonShellUnavailable, phaseCommitted: ""} { r.Phase = phase rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepDone || !rep.Pushed || rep.Reason != reason || rep.CandidateSHA != r.Candidate { t.Fatalf("%s: %+v", phase, rep) } } } // The person's Retry of a timed-out step whose push failed publishes the // same commit as its attempt finished it: still unfinished (or still a // round without a working shell). func TestRepublishKeepsHowTheStepFinished(t *testing.T) { for phase, reason := range map[string]string{phaseCommittedUnfinished: "step_timeout", phaseCommittedNoShell: wire.ReasonShellUnavailable, phaseCommitted: ""} { e, f, r, _ := hubRig(t) ctx := context.Background() r.Specialist, r.StepID, r.Branch, r.Person = wire.SpecialistEngineering, "s2", "equipo/tk1-another-fix", "p@x" base := gitOut(t, f.dir, "rev-parse", "main") gitDir := e.tree(r, base).GitDir gitOut(t, filepath.Dir(f.dir), "clone", "-q", "--bare", f.dir, gitDir) tree := gitOut(t, filepath.Dir(f.dir), "--git-dir="+gitDir, "rev-parse", base+"^{tree}") cand := gitOut(t, filepath.Dir(f.dir), "--git-dir="+gitDir, "commit-tree", tree, "-p", base, "-m", "unfinished") if err := e.O.State.AcceptDispatch(ctx, "d1", r.DispatchCommand); err != nil { t.Fatal(err) } if _, err := e.O.State.db.Exec("UPDATE steps SET phase=?, state=?, final_state=?, final_reason='push_failed' WHERE step_id=? AND attempt=1", phase, runDone, wire.StepFailed, r.StepID); err != nil { t.Fatal(err) } again := r again.Attempt, again.FromAttempt, again.Republish, again.BaseSHA, again.CandidateSHA = 2, 1, true, base, cand if err := e.O.State.AcceptDispatch(ctx, "d2", again.DispatchCommand); err != nil { t.Fatal(err) } rep := e.Exec(ctx, again, func(wire.StepReport) {}) if rep.State != wire.StepDone || !rep.Pushed || rep.Reason != reason || rep.CandidateSHA != cand { t.Fatalf("%q: %+v", phase, rep) } if got, _ := e.O.State.stepPhase(ctx, r.StepID, 2); got != phase { t.Fatalf("%q: republish left phase %q", phase, got) } } } // A timed-out step's commit that could not be pushed stops step_timeout, // not push_failed: it is tried afresh, never republished, so no runner // (an older one included) can publish it as finished work. func TestUnfinishedPushFailureIsATimeout(t *testing.T) { rep := wire.StepReport{State: wire.StepFailed, Reason: "push_failed", LogTail: "git: refused"} if got := withCommitReason(rep, phaseCommittedUnfinished); got.State != wire.StepFailed || got.Reason != "step_timeout" || got.LogTail != rep.LogTail { t.Fatalf("unfinished: %+v", got) } for _, phase := range []string{phaseCommitted, phaseCommittedNoShell} { if got := withCommitReason(rep, phase); got.Reason != "push_failed" { t.Fatalf("%s: %+v", phase, got) } } conflict := wire.StepReport{State: wire.StepFailed, Reason: "push_conflict"} if got := withCommitReason(conflict, phaseCommittedUnfinished); got.Reason != "step_timeout" { t.Fatalf("conflict: %+v", got) } } // Unfinished work is queued as the step failing step_timeout, which an // older runner replaying the outbox (rolled back) and an older instance // both read safely; the sender says it is done, pushed, to an instance // at ProtocolUnfinishedWork only. A plain timeout stays a timeout. func TestUnfinishedReportQueuedSafely(t *testing.T) { e, _, r, _ := hubRig(t) ctx := context.Background() s := e.O.State cand := strings.Repeat("2", 40) r.Specialist, r.StepID = wire.SpecialistEngineering, "s9" other := r other.StepID, other.TaskID = "s10", "tk2" r.StepID = "s9" for _, d := range []stepRow{r, other} { if err := s.AcceptDispatch(ctx, "d-"+d.StepID, d.DispatchCommand); err != nil { t.Fatal(err) } } if err := s.setStepPhase(ctx, r, phaseCommittedUnfinished, "", cand); err != nil { t.Fatal(err) } if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: r.TaskID, StepID: "s9", Attempt: 1, State: wire.StepDone, Reason: "step_timeout", CandidateSHA: cand, Pushed: true, Termination: true, Findings: []wire.Finding{}}); err != nil { t.Fatal(err) } if err := s.ReportStep(ctx, other, wire.StepReport{TaskID: other.TaskID, StepID: "s10", Attempt: 1, State: wire.StepFailed, Reason: "step_timeout", Termination: true, Findings: []wire.Finding{}}); err != nil { t.Fatal(err) } frames, _, err := s.Unacked(ctx, 0) if err != nil || len(frames) != 2 { t.Fatalf("queued %d: %v", len(frames), err) } read := func(f wire.Frame) *wire.StepReport { body, err := f.Decode() if err != nil { t.Fatal(err) } return body.(*wire.StepReport) } for _, f := range frames { if v := read(f); v.State != wire.StepFailed || v.Reason != "step_timeout" || v.Pushed || v.CandidateSHA != "" { t.Fatalf("queued as %+v", v) } } for _, c := range []struct { protocol int step string done bool }{{wire.ProtocolUnfinishedWork, "s9", true}, {wire.ProtocolChangeFiles, "s9", false}, {wire.ProtocolUnfinishedWork, "s10", false}} { for _, f := range frames { if read(f).StepID != c.step { continue } sent, err := s.unfinishedReport(ctx, f, c.protocol, false) if err != nil { t.Fatal(err) } v := read(sent) if done := v.State == wire.StepDone && v.Pushed && v.CandidateSHA == cand && v.Reason == "step_timeout"; done != c.done || !c.done && v.State != wire.StepFailed { t.Fatalf("%s at %d: %+v", c.step, c.protocol, v) } } } }