package operator_test import ( "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "strings" "testing" "testing/synctest" "time" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "github.com/liken-sh/liken/kubernetes/apiservertest" "tangled.org/guid.foo/simmer/api/v1alpha1" "tangled.org/guid.foo/simmer/cluster" "tangled.org/guid.foo/simmer/dataplane" "tangled.org/guid.foo/simmer/internal/memstore" "tangled.org/guid.foo/simmer/internal/world" "tangled.org/guid.foo/simmer/operator" ) // stream sends each payload to each subscriber as one event, then holds // the stream open. func stream(payloads ...string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for i, payload := range payloads { _, _ = fmt.Fprintf(w, "id: %d\ndata: {\"id\":\"%d\",\"timestamp\":\"2000-01-01T00:00:00Z\",\"payload\":%s}\n\n", i+1, i+1, payload) } w.(http.Flusher).Flush() <-r.Context().Done() }) } // wicket sends one firing alert in the namespace assistant. var wicket = stream(`{"status":"firing","labels":{"alertname":"DiskFull","namespace":"assistant"}}`) type running struct { w *world.World store *memstore.Store o *operator.Operator bell *operator.Bell } // ops is the Mandate ops in telemetry, whose purview is the alerts // that fire in assistant. func ops() *v1alpha1.Mandate { m := world.Mandate("telemetry", "ops", "upkeep") m.Spec.Purview = map[string][]string{"alerts": {"assistant"}} return m } // triage is the Duty of ops that triages each alert that fires. func triage() *v1alpha1.Duty { return world.When(ops(), "triage", "alerts", "firing") } // roomy is the Account personal with a reading that has room. func roomy() *v1alpha1.Account { account := world.Account("personal") account.Status.Usage = world.Reading(0.1, 0.01, time.Now().Add(84*time.Hour), time.Now()) return account } // start is a whole simmer: the Account personal with a reading that // has room, the Allowance upkeep, the Signal alerts, and the Mandate // ops with its Duty triage. func start(t *testing.T) *running { return startWith(t, roomy(), ops(), triage()) } // startWith is start with another Account personal, another Mandate, // and other Duties. func startWith(t *testing.T, account *v1alpha1.Account, m *v1alpha1.Mandate, duties ...*v1alpha1.Duty) *running { return startServing(t, account, m, world.Signal("alerts"), wicket, duties...) } // startServing is startWith with another Signal alerts and another // wicket. func startServing(t *testing.T, account *v1alpha1.Account, m *v1alpha1.Mandate, alerts *v1alpha1.Signal, events http.Handler, duties ...*v1alpha1.Duty) *running { r := &running{w: world.Start(t), store: memstore.New(), bell: operator.NewBell()} r.w.Put(cluster.Accounts, account) r.w.Put(cluster.Secrets, world.Secret(world.Namespace, "personal-token", "credential", "sk-ant-oat"), world.Secret(world.Namespace, "wicket-alerts", "subscribe", "s3cret")) r.w.Put(cluster.Allowances, world.Allowance("upkeep", "personal", 4)) r.w.Put(cluster.Signals, alerts) r.w.Put(cluster.Mandates, m) for _, d := range duties { r.w.Put(cluster.Duties, d) } time.Sleep(time.Second) synctest.Wait() settings := operator.Settings{WicketURL: apiservertest.Host, SessionImage: "claude:1", OperatorImage: "simmer:1", Namespace: world.Namespace, DataDir: t.TempDir(), DataplaneURL: "http://dp"} r.o = operator.New(r.store, settings, "v1.2.3", r.bell) r.o.Attach(r.w.Cluster, apiservertest.Start(t, events).Client()) t.Cleanup(r.o.Stop) return r } func (r *running) pass(t *testing.T) { t.Helper() if _, err := r.o.Pass(t.Context()); err != nil { t.Fatal(err) } time.Sleep(time.Second) synctest.Wait() } func (r *running) only(t *testing.T) v1alpha1.Session { t.Helper() sessions := world.List[v1alpha1.Session](r.w, cluster.Sessions) if len(sessions) != 1 { t.Fatalf("%d Sessions, want one", len(sessions)) } return sessions[0] } func (r *running) succeed(t *testing.T, job string) { t.Helper() held, ok := world.Get[cluster.Job](r.w, cluster.Jobs, "telemetry", job) if !ok { t.Fatalf("the Job %s does not exist", job) } held.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}} r.w.Put(cluster.Jobs, &held) synctest.Wait() } func TestAnAlertBecomesASessionThatTakesATurnAndFinishes(t *testing.T) { synctest.Test(t, func(t *testing.T) { r := start(t) r.pass(t) r.pass(t) s := r.only(t) job := s.Metadata.Name + "-1" _, _ = r.store.Take(dataplane.SessionRef{Namespace: "telemetry", Name: s.Metadata.Name}, 1) if s.Status.Phase != v1alpha1.PhaseRunning { t.Fatalf("the Session is %s, want Running", s.Status.Phase) } if err := r.o.Release(t.Context(), dataplane.SessionRef{Namespace: "telemetry", Name: s.Metadata.Name}, "alert/DiskFull/assistant"); err != nil { t.Fatal(err) } r.succeed(t, job) r.pass(t) s = r.only(t) if s.Status.Phase != v1alpha1.PhaseFinished || s.Status.Turns[0].Outcome != v1alpha1.OutcomeSucceeded { t.Errorf("status = %+v, want Finished after one Succeeded turn", s.Status) } _, copied := world.Get[cluster.Secret](r.w, cluster.Secrets, "telemetry", "simmer-account-personal") _, bound := world.Get[cluster.ClusterRoleBinding](r.w, cluster.ClusterRoleBindings, "", "simmer:telemetry:ops:simmer-session") if !copied || !bound { t.Errorf("credential copied = %v, simmer-session bound = %v; want both", copied, bound) } }) } func TestAStopInterruptsTheTurnAndItsDeleteResumesIt(t *testing.T) { synctest.Test(t, func(t *testing.T) { r := start(t) r.pass(t) r.pass(t) s := r.only(t) ref := dataplane.SessionRef{Namespace: "telemetry", Name: s.Metadata.Name} _, _ = r.store.Take(ref, 1) r.w.Put(cluster.Stops, world.Stop("stop-1", "a loop.")) synctest.Wait() r.pass(t) stopped := r.only(t) stop, _ := world.Get[v1alpha1.Stop](r.w, cluster.Stops, "", "stop-1") r.w.API.Delete(world.Kind(cluster.Stops), "", "stop-1") synctest.Wait() r.pass(t) r.pass(t) resumed := r.only(t) if stopped.Status.Turns[0].Outcome != v1alpha1.OutcomeInterrupted || stopped.Status.WaitingOn != v1alpha1.WaitingOnStop || stop.Status.InterruptedJobs != 1 { t.Errorf("while stopped: %+v and the Stop says %d interrupted; want the turn Interrupted, waiting on stop, and 1", stopped.Status, stop.Status.InterruptedJobs) } if resumed.Status.TurnCount != 2 || resumed.Status.Phase != v1alpha1.PhaseRunning { t.Errorf("after the Stop went: %+v, want a second turn running", resumed.Status) } if events, _ := r.store.Take(ref, 2); len(events) != 2 || events[1].Signal != "simmer" { t.Errorf("turn 2 took %+v, want the alert and the note that simmer started again", events) } }) } func TestATurnLearnsWhatItNeedsAndReportsUsage(t *testing.T) { synctest.Test(t, func(t *testing.T) { r := start(t) r.pass(t) r.pass(t) s := r.only(t) ref := dataplane.SessionRef{Namespace: "telemetry", Name: s.Metadata.Name} turn, err := r.o.Turn(t.Context(), ref) followErr := r.o.Follow(t.Context(), ref, "forge/issues/200") var info dataplane.RateLimitInfo info.UnifiedWindows.FiveHour = dataplane.RateLimitWindow{Utilization: 0.33, ResetsAt: time.Now().Add(time.Hour).Unix()} info.UnifiedWindows.SevenDay = dataplane.RateLimitWindow{Utilization: 0.02, ResetsAt: time.Now().Add(80 * time.Hour).Unix()} usageErr := r.o.SessionUsage(t.Context(), ref, info) synctest.Wait() if err != nil || turn.Number != 1 || turn.Skill != "triage" || turn.UID != s.Metadata.UID || turn.Resume { t.Errorf("turn = %+v, %v; want turn 1 of triage, as the Session's uid, not resumed", turn, err) } if keys := r.only(t).Status.Keys; followErr != nil || len(keys) != 2 { t.Errorf("keys = %v, %v; want the alert and the issue", keys, followErr) } account, _ := world.Get[v1alpha1.Account](r.w, cluster.Accounts, "", "personal") if usageErr != nil || account.Status.Usage.FiveHour.Utilization != 0.33 || account.Status.Usage.Source != v1alpha1.UsageSourceTurn { t.Errorf("usage = %+v, %v; want the turn's reading", account.Status.Usage, usageErr) } if _, err := r.o.Turn(t.Context(), dataplane.SessionRef{Namespace: "telemetry", Name: "nope"}); err != dataplane.ErrUnknownSession { t.Errorf("an unknown Session answered %v, want ErrUnknownSession", err) } }) } func TestEveryCounterIsPublishedAtZero(t *testing.T) { synctest.Test(t, func(t *testing.T) { r := start(t) r.w.Put(cluster.Signals, world.Signal("gitea")) synctest.Wait() r.pass(t) r.pass(t) recorder := httptest.NewRecorder() r.o.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/metrics", nil)) body, _ := io.ReadAll(recorder.Body) for _, series := range []string{ `simmer_build_info{version="v1.2.3"} 1`, `simmer_events_total{outcome="unowned",signal="gitea"} 0`, `simmer_turns_total{mandate="ops",namespace="telemetry",outcome="Failed"} 0`, `simmer_reconcile_errors_total{kind="Session"} 0`, `simmer_watch_restarts_total{kind="ProbeJob"} 0`, `simmer_watch_restarts_total{kind="Duty"} 0`, `simmer_watch_restarts_total{kind="CronJob"} 0`, `simmer_passes_total{cause="clock"} 0`, `simmer_passes_total{cause="Session"} 0`, `simmer_events_total{outcome="skipped",signal="gitea"} 0`, `simmer_stopped 0`, `simmer_allowance_holding{allowance="upkeep"} 0`, `simmer_account_usage_ratio{account="personal",window="five_hour"} 0.1`, `simmer_sessions{mandate="ops",namespace="telemetry",phase="Running"} 1`, `simmer_follow_ups{mandate="ops",namespace="telemetry"} 0`, `simmer_follow_ups_due_total{mandate="ops",namespace="telemetry"} 0`, `simmer_events_total{outcome="unreadable",signal="gitea"} 0`, `simmer_signal_subscription_ends_total{signal="alerts"} 0`, `simmer_dataplane_requests_total{code="500",route="PUT /v1/sessions/{namespace}/{name}/transcript"} 0`, `simmer_dataplane_requests_total{code="500",route="POST /v1/duties/{namespace}/{name}/start"} 0`, `simmer_account_ready{account="personal",reason="Reading"} 1`, `simmer_sessions_waiting{mandate="ops",namespace="telemetry",waiting_on="capacity"} 0`, `simmer_sessions_waiting{mandate="ops",namespace="telemetry",waiting_on="job"} 1`, `simmer_turn_duration_seconds_count{duty="triage",mandate="ops",namespace="telemetry"} 0`, `simmer_turn_wait_seconds_count{mandate="ops",namespace="telemetry"} 1`, `simmer_turn_start_delay_seconds_count{mandate="ops",namespace="telemetry"} 0`, } { if !strings.Contains(string(body), series) { t.Errorf("the scrape has no %s", series) } } }) } func TestTheSettingsComeFromTheEnvironment(t *testing.T) { env := map[string]string{ "SIMMER_WICKET_URL": "http://wicket", "SIMMER_SESSION_IMAGE": "claude:1", "SIMMER_NAMESPACE": "simmer", "SIMMER_POD_NAME": "simmer-operator-0", "SIMMER_DATA_DIR": "/data", "SIMMER_DATAPLANE_URL": "http://dp", } s, err := operator.FromEnv(func(name string) string { return env[name] }) got, _ := json.Marshal(s) if err != nil || s.MetricsAddress != ":9200" || s.DataplaneAddress != ":8443" || s.OperatorImage != "" || s.WicketTokenFile != "/var/run/secrets/wicket/token" { t.Errorf("settings = %s, %v; want the defaults and no operator image", got, err) } if _, err := operator.FromEnv(func(string) string { return "" }); err == nil { t.Error("an empty environment gave settings, want an error naming what is missing") } }