package host import ( "context" "reflect" "strings" "sync" "testing" "time" "github.com/carlosframework/platform/internal/activator" "github.com/carlosframework/platform/internal/applog" "github.com/carlosframework/platform/internal/provision" "github.com/carlosframework/platform/internal/release" "github.com/carlosframework/platform/internal/runs" ) // eventLog records what a worker hands its EventSink. type eventLog struct { mu sync.Mutex events []loggedEvent } type loggedEvent struct{ acct, app, host, level, msg string } func (l *eventLog) App(acct, app, host, line string) {} func (l *eventLog) Event(acct, app, host, level, msg string) { l.mu.Lock() defer l.mu.Unlock() l.events = append(l.events, loggedEvent{acct, app, host, level, msg}) } func (l *eventLog) all() []loggedEvent { l.mu.Lock() defer l.mu.Unlock() return append([]loggedEvent(nil), l.events...) } func TestRunEndedLineSaysHowTheRunEnded(t *testing.T) { start := time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC) end := start.Add(90*time.Second + 400*time.Millisecond) ran := func(r runs.Result) runs.Result { r.Started, r.Ended = start, end; return r } cases := []struct { res runs.Result started bool want string }{ {ran(runs.Result{}), true, "run r1 ended with exit 0 after 1m30s"}, {ran(runs.Result{Exit: 3}), true, "run r1 ended with exit 3 after 1m30s"}, {ran(runs.Result{Signal: "9"}), true, "run r1 was ended by signal 9 after 1m30s"}, {ran(runs.Result{TimedOut: true}), true, "run r1 timed out after 1m30s"}, {runs.Result{TimedOut: true, Ended: end}, false, "run r1 timed out before it started"}, {ran(runs.Result{Cancelled: true, Exit: 143}), true, "run r1 was cancelled after 1m30s"}, {runs.Result{Cancelled: true, Ended: end}, false, "run r1 was cancelled before it started"}, {ran(runs.Result{Interrupted: activator.StopRestart}), true, "run r1 was interrupted: the instance was restarted. it may have done part of its work"}, {runs.Result{Interrupted: runs.InterruptedAgentRestart, Ended: end}, true, "run r1 was interrupted: the box's agent restarted. it may have done part of its work"}, {runs.Result{Interrupted: activator.StopRestart, Ended: end}, false, "run r1 did not start: the instance was restarted"}, {runs.Result{Interrupted: runs.InterruptedStartFailed, Ended: end}, false, "run r1 was interrupted: the box could not start the command. it may have done part of its work"}, {runs.Result{Refused: runs.RefusedFlat}, false, "run r1 did not start: the box is not on the nested layout yet"}, {runs.Result{Refused: runs.RefusedClaim}, false, "run r1 did not start: the box has host claims armed"}, {runs.Result{Refused: runs.RefusedWake, Detail: "wake failed: restore"}, false, "run r1 did not start: the instance did not wake. wake failed: restore"}, {runs.Result{Refused: runs.RefusedIncarnation}, false, "run r1 did not start: the instance was deleted and created again after the run was requested"}, {runs.Result{Refused: runs.RefusedImport}, false, "run r1 did not start: the instance is an import that is not committed yet"}, {runs.Result{Refused: "something-new"}, false, "run r1 did not start: something-new"}, } for _, c := range cases { if got := runEndedLine("r1", c.res, c.started); got != c.want { t.Errorf("%+v (started %v):\n got %q\nwant %q", c.res, c.started, got, c.want) } } } // The start line names the run and who asked for it, and never the // command's arguments: they can carry what a log reader should not see. func TestRunStartedLineCarriesNoArguments(t *testing.T) { req := runs.Request{ID: "r1", By: "member@example.com", Argv: []string{"import", "--token", "s3cret"}} got := runStartedLine(req) if got != "run r1 started by member@example.com" { t.Fatalf("got %q", got) } for _, a := range req.Argv { if strings.Contains(got, a) { t.Fatalf("%q carries the argument %q", got, a) } } } // A run closed out after an agent restart is logged as interrupted once, // however many passes still read it as picked. func TestRunClosedOutAfterAnAgentRestartIsLoggedOnce(t *testing.T) { s := release.NewDirStore(t.TempDir()) _, id := queueRun(t, s, time.Now().Add(time.Minute)) got, err := provision.SetRecordRun(context.Background(), s, "bab", "shop", runHost, provision.RunPick(id, "box-1", "boot-old", time.Now().Add(time.Hour))) if err != nil { t.Fatal(err) } var l execLog var events eventLog w := testWorker(s, runOwnedRoute(runHost), "box-1", "boot-new", &l) w.events = &events // got is the stale read a second pass would also have noted. w.consider(context.Background(), *got) w.consider(context.Background(), *got) want := []loggedEvent{{"bab", "shop", runHost, applog.LevelInfo, "run " + id + " was interrupted: the box's agent restarted. it may have done part of its work"}} if ev := events.all(); !reflect.DeepEqual(ev, want) { t.Fatalf("events %+v, want %+v", ev, want) } } // A restart after the command's own result landed, but before its done // CAS did, closes the run out without a second ending: the boot that ran // the command logged it (Astra review, finding 2). func TestRunClosedOutAfterItsOwnResultLogsNothing(t *testing.T) { s := release.NewDirStore(t.TempDir()) _, id := queueRun(t, s, time.Now().Add(time.Minute)) got, err := provision.SetRecordRun(context.Background(), s, "bab", "shop", runHost, provision.RunPick(id, "box-1", "boot-old", time.Now().Add(time.Hour))) if err != nil { t.Fatal(err) } if err := runs.WriteResult(context.Background(), s, "bab", "shop", id, runs.Result{Exit: 0, Box: "box-1", Ended: time.Now().UTC()}); err != nil { t.Fatal(err) } var l execLog var events eventLog w := testWorker(s, runOwnedRoute(runHost), "box-1", "boot-new", &l) w.events = &events w.consider(context.Background(), *got) if ev := events.all(); len(ev) != 0 { t.Fatalf("events %+v, want none", ev) } if r := currentRun(t, s); r.State != provision.RunDone { t.Fatalf("run %+v, want done", r) } if res, _ := runs.ReadResult(context.Background(), s, "bab", "shop", id); res == nil || res.Interrupted != "" { t.Fatalf("result %+v, want the command's own", res) } } // A stale pass after the run was acknowledged (its result deleted, the // record cleared) recreates a result, but its done CAS fails, so it logs // no second ending (Astra round 2, finding 2). func TestRunClosedOutByAStalePassAfterTheAckLogsNothing(t *testing.T) { s := release.NewDirStore(t.TempDir()) _, id := queueRun(t, s, time.Now().Add(time.Minute)) got, err := provision.SetRecordRun(context.Background(), s, "bab", "shop", runHost, provision.RunPick(id, "box-1", "boot-old", time.Now().Add(time.Hour))) if err != nil { t.Fatal(err) } var l execLog var events eventLog w := testWorker(s, runOwnedRoute(runHost), "box-1", "boot-new", &l) w.events = &events w.consider(context.Background(), *got) // The CLI acknowledges the run: the record is cleared and the result // deleted, as handleAPIRunAck does. if _, err := provision.SetRecordRun(context.Background(), s, "bab", "shop", runHost, provision.RunClear(id)); err != nil { t.Fatal(err) } if err := runs.DeleteRun(context.Background(), s, "bab", "shop", id); err != nil { t.Fatal(err) } w.consider(context.Background(), *got) if ev := events.all(); len(ev) != 1 { t.Fatalf("events %+v, want the first pass's ending only", ev) } } // A done CAS whose answer was lost loses the line rather than risk a // second one: run lines are at most once, and result.json is the record. func TestRunClosedOutWithALostDoneAnswerIsNotLoggedTwice(t *testing.T) { dir := release.NewDirStore(t.TempDir()) _, id := queueRun(t, dir, time.Now().Add(time.Minute)) got, err := provision.SetRecordRun(context.Background(), dir, "bab", "shop", runHost, provision.RunPick(id, "box-1", "boot-old", time.Now().Add(time.Hour))) if err != nil { t.Fatal(err) } var l execLog var events eventLog w := testWorker(&lostAnswer{Store: dir, land: true}, runOwnedRoute(runHost), "box-1", "boot-new", &l) w.events = &events w.consider(context.Background(), *got) w.consider(context.Background(), *got) if r := currentRun(t, dir); r.State != provision.RunDone { t.Fatalf("run %+v, want done (the CAS landed)", r) } if ev := events.all(); len(ev) != 0 { t.Fatalf("events %+v, want none: the done answer was lost", ev) } if res, _ := runs.ReadResult(context.Background(), dir, "bab", "shop", id); res == nil || res.Interrupted != runs.InterruptedAgentRestart { t.Fatalf("result %+v, want the interrupted result", res) } } // A worker with no sink, as on a box with no log store, still runs. func TestRunEventWithoutASinkIsANoop(t *testing.T) { w := &runsWorker{} w.runEvent(provision.Record{Account: "bab", App: "shop", Host: runHost}, "run r1 started by member@example.com") }