package runner
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
// A TASK THE ENGINE NO LONGER HAS STOPS, AND ITS SLOT IS FREED (#493).
//
// A forge redeploy closes every runner's connect stream; the engine
// releases those claims and hands the tasks out again. The runner went
// on running the released job to its end, heartbeating it every few
// seconds into 404 task-gone for hours, with its only slot taken, and
// the result it finally reported was discarded. The first task-gone
// answer to a heartbeat now ends the job and the heartbeats, and the
// runner takes the next task.
//
// A bare 404 is not that answer: a forge that is starting says it for
// every repository, and a job must not be killed by a deploy.
func TestATaskTheEngineNoLongerHasStops(t *testing.T) {
cases := []struct {
name string
reasoned bool
wantRan bool
}{
{"task gone", true, false},
{"bare 404 from a starting forge", false, true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
marks := t.TempDir()
ran := filepath.Join(marks, "ran")
job, _ := json.Marshal(Job{Steps: []JobStep{{Run: "sleep 3; touch " + ran}}})
lost := task("lost", "c1")
lost.Metadata = map[string]string{JobKey: string(job)}
next := task("next", "c2")
nextJob, _ := json.Marshal(Job{Steps: []JobStep{{Run: "true"}}})
next.Metadata = map[string]string{JobKey: string(nextJob)}
br := &fakeBridge{queue: map[string][]polled{"t-job": {lost, next}}, resolved: map[string]map[string]any{},
logs: map[string]string{}, gone: map[string]bool{"lost": c.reasoned}}
srv := httptest.NewServer(br.handler())
defer srv.Close()
r, err := New(Config{
Bridge: srv.URL, Token: "WT", Tasks: []string{"t-job"}, MaxTasks: 1,
WorkDir: t.TempDir(), Checkout: appCheckout{}, Heartbeat: 100 * time.Millisecond,
ResolveRetry: []time.Duration{10 * time.Millisecond},
Logf: func(string, ...any) {},
})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
done := make(chan struct{})
go func() { r.Run(ctx); close(done) }()
start := time.Now()
var nextAt time.Duration
for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
br.mu.Lock()
_, finished := br.resolved["next"]
br.mu.Unlock()
if finished {
nextAt = time.Since(start)
break
}
}
// Heartbeats sent for the lost task after the next one ended.
br.mu.Lock()
beatsBefore := heartbeats(br.actions, "lost")
br.mu.Unlock()
time.Sleep(400 * time.Millisecond)
br.mu.Lock()
beatsAfter := heartbeats(br.actions, "lost")
_, nextDone := br.resolved["next"]
br.mu.Unlock()
cancel()
<-done
if !nextDone {
t.Fatalf("FAIL: the runner never took the next task")
}
_, statErr := os.Stat(ran)
if gotRan := statErr == nil; gotRan != c.wantRan {
t.Errorf("FAIL: the lost job ran to its end = %v, want %v", gotRan, c.wantRan)
}
if !c.reasoned {
if beatsBefore < 3 {
t.Errorf("FAIL: %d heartbeats over a 3s job under bare 404s; want them to go on", beatsBefore)
}
} else {
if nextAt > 2*time.Second {
t.Errorf("FAIL: the next task finished after %s; want the slot freed within a few heartbeats", nextAt.Round(10*time.Millisecond))
}
if beatsBefore > 1 {
t.Errorf("FAIL: %d heartbeats for a task the engine said was gone; want at most 1", beatsBefore)
}
if beatsAfter != beatsBefore {
t.Errorf("FAIL: heartbeats for the gone task went on: %d then %d", beatsBefore, beatsAfter)
}
}
if !t.Failed() {
t.Log("ok")
}
})
}
}
func heartbeats(actions []string, id string) int {
n := 0
for _, a := range actions {
if a == id+" heartbeat" {
n++
}
}
return n
}