| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "sync" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "reasonix/internal/agent" |
| 11 | "reasonix/internal/event" |
| 12 | goaldomain "reasonix/internal/goal" |
| 13 | "reasonix/internal/session" |
| 14 | "reasonix/internal/tool" |
| 15 | ) |
| 16 | |
| 17 | func goalWorkController(t *testing.T) (*Controller, *session.Runtime) { |
| 18 | t.Helper() |
| 19 | service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir())) |
| 20 | if err != nil { |
| 21 | t.Fatal(err) |
| 22 | } |
| 23 | t.Cleanup(func() { _ = service.CloseAll(context.Background()) }) |
| 24 | runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-work"}) |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard) |
| 29 | c := newOwnedTestController(t, Options{Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true}) |
| 30 | t.Cleanup(func() { setGoalWorkPhase(c, session.RuntimeIdle); c.Close() }) |
| 31 | setGoalWorkPhase(c, session.RuntimeRunning) |
| 32 | _, err = c.applyHostGoalMutation(t.Context(), "test-create", func(machine *goaldomain.Machine) (*goaldomain.View, error) { |
| 33 | view, err := machine.Create(goaldomain.CreateRequest{Objective: "finish work"}) |
| 34 | return &view, err |
| 35 | }) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | return c, runtime |
| 40 | } |
| 41 | |
| 42 | func setGoalWorkPhase(c *Controller, phase session.RuntimePhase) { |
| 43 | c.mu.Lock() |
| 44 | c.turns.phase = phase |
| 45 | c.noteExecutionLocked(phase, "test-work") |
| 46 | c.mu.Unlock() |
| 47 | } |
| 48 | |
| 49 | func TestGoalWorkAccumulatesOnceAcrossPauseResumeAndDurableRestore(t *testing.T) { |
| 50 | c, runtime := goalWorkController(t) |
| 51 | first := c.beginGoalWork() |
| 52 | if first == nil { |
| 53 | t.Fatal("active user-triggered work was not measured") |
| 54 | } |
| 55 | _, err := c.applyHostGoalMutation(t.Context(), "test-pause", func(machine *goaldomain.Machine) (*goaldomain.View, error) { |
| 56 | view, err := machine.Pause(machine.Get().Ref()) |
| 57 | return &view, err |
| 58 | }) |
| 59 | if err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | var wg sync.WaitGroup |
| 63 | for range 8 { |
| 64 | wg.Go(func() { |
| 65 | if err := c.finishGoalWork(first, first.started.Add(1200*time.Millisecond)); err != nil { |
| 66 | t.Error(err) |
| 67 | } |
| 68 | }) |
| 69 | } |
| 70 | wg.Wait() |
| 71 | if got := c.GoalRuntime().WorkDurationMs; got != 1200 { |
| 72 | t.Fatalf("paused work = %d", got) |
| 73 | } |
| 74 | if span := c.beginGoalWork(); span != nil { |
| 75 | t.Fatal("paused goal started a work clock") |
| 76 | } |
| 77 | _, err = c.applyHostGoalMutation(t.Context(), "test-resume", func(machine *goaldomain.Machine) (*goaldomain.View, error) { |
| 78 | view, err := machine.Resume(machine.Get().Ref(), true) |
| 79 | return &view, err |
| 80 | }) |
| 81 | if err != nil { |
| 82 | t.Fatal(err) |
| 83 | } |
| 84 | second := c.beginGoalWork() |
| 85 | if second == nil { |
| 86 | t.Fatal("resumed goal did not start work") |
| 87 | } |
| 88 | // Separate Run clocks exclude an arbitrarily long gap between executions. |
| 89 | second.started = first.started.Add(48 * time.Hour) |
| 90 | _, err = c.applyHostGoalMutation(t.Context(), "test-complete", func(machine *goaldomain.Machine) (*goaldomain.View, error) { |
| 91 | view, err := machine.Complete(machine.Get().Ref()) |
| 92 | return &view, err |
| 93 | }) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | if err := c.finishGoalWork(second, second.started.Add(2300*time.Millisecond)); err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | if got := c.GoalRuntime().WorkDurationMs; got != 3500 { |
| 101 | t.Fatalf("completed work = %d", got) |
| 102 | } |
| 103 | if _, err := runtime.Session().Flush(t.Context()); err != nil { |
| 104 | t.Fatal(err) |
| 105 | } |
| 106 | commits, err := runtime.Session().Handle().Read(t.Context(), 1, 100) |
| 107 | if err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | var restored *goaldomain.Machine |
| 111 | for _, commit := range commits.Commits { |
| 112 | for _, item := range commit.Events { |
| 113 | if item.Kind == "goal/state" { |
| 114 | restored, err = goalLifecycleFromProjection(item.Payload, runtime.Ref().SessionID, time.Time{}) |
| 115 | if err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | if restored == nil || restored.Get().WorkDurationMs != 3500 || restored.Get().Activation != goaldomain.ActivationDisarmed { |
| 122 | t.Fatalf("durable restored goal = %+v", restored) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | func TestGoalWorkRejectsRetiredActivityAndReplacement(t *testing.T) { |
| 127 | for _, transition := range []string{"replace", "clear", "activity", "recovery", "epoch", "runtime"} { |
| 128 | t.Run(transition, func(t *testing.T) { |
| 129 | c, runtime := goalWorkController(t) |
| 130 | work := c.beginGoalWork() |
| 131 | switch transition { |
| 132 | case "replace", "clear": |
| 133 | _, err := c.applyHostGoalMutation(t.Context(), "test-replace", func(machine *goaldomain.Machine) (*goaldomain.View, error) { |
| 134 | if transition == "clear" { |
| 135 | return nil, machine.Clear(machine.Get().Ref()) |
| 136 | } |
| 137 | view, err := machine.Replace(goaldomain.CreateRequest{Objective: "replacement"}) |
| 138 | return &view, err |
| 139 | }) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | case "activity": |
| 144 | work.token++ |
| 145 | case "epoch": |
| 146 | work.epoch = "retired-epoch" |
| 147 | case "runtime": |
| 148 | work.runtime = nil |
| 149 | case "recovery": |
| 150 | runtime.RequireRecovery("cancel watchdog") |
| 151 | } |
| 152 | if err := c.finishGoalWork(work, work.started.Add(time.Second)); err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | if got := c.GoalRuntime().WorkDurationMs; got != 0 { |
| 156 | t.Fatalf("stale work = %d", got) |
| 157 | } |
| 158 | }) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | type goalWorkErrorRunner struct{ err error } |
| 163 | |
| 164 | func (r goalWorkErrorRunner) Run(context.Context, string) error { return r.err } |
| 165 | |
| 166 | func TestGoalWorkRecordsCancelledAndFailedRuns(t *testing.T) { |
| 167 | for _, runErr := range []error{context.Canceled, errors.New("provider failed")} { |
| 168 | t.Run(runErr.Error(), func(t *testing.T) { |
| 169 | c, _ := goalWorkController(t) |
| 170 | c.runner = goalWorkErrorRunner{err: runErr} |
| 171 | if err := c.runModelTurn(t.Context(), "work"); !errors.Is(err, runErr) { |
| 172 | t.Fatalf("run error = %v", err) |
| 173 | } |
| 174 | if got := c.GoalRuntime().WorkDurationMs; got <= 0 { |
| 175 | t.Fatalf("failed run work = %d", got) |
| 176 | } |
| 177 | }) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | func TestGoalWorkLegacyProjectionPreservesDuration(t *testing.T) { |
| 182 | machine, err := goalLifecycleFromProjection([]byte(`{"goal":"legacy","status":"stopped","turnsUsed":2,"workDurationMs":12345}`), "legacy", time.Time{}) |
| 183 | if err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | if got := machine.Get().WorkDurationMs; got != 12345 { |
| 187 | t.Fatalf("legacy duration = %d", got) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | func TestGoalWorkPersistenceFailureDoesNotPublishDuration(t *testing.T) { |
| 192 | c, runtime := goalWorkController(t) |
| 193 | work := c.beginGoalWork() |
| 194 | if err := runtime.Session().Handle().Close(t.Context()); err != nil { |
| 195 | t.Fatal(err) |
| 196 | } |
| 197 | if err := c.finishGoalWork(work, work.started.Add(time.Second)); err == nil { |
| 198 | t.Fatal("failed append was hidden") |
| 199 | } |
| 200 | if got := c.GoalRuntime().WorkDurationMs; got != 0 { |
| 201 | t.Fatalf("uncommitted work published: %d", got) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | func TestGoalWorkDoesNotCountIdleOrDisarmedGoals(t *testing.T) { |
| 206 | c, _ := goalWorkController(t) |
| 207 | setGoalWorkPhase(c, session.RuntimeIdle) |
| 208 | if work := c.beginGoalWork(); work != nil { |
| 209 | t.Fatal("idle runtime started a clock") |
| 210 | } |
| 211 | setGoalWorkPhase(c, session.RuntimeRunning) |
| 212 | c.disarmGoalLifecycle("cold-restore") |
| 213 | if work := c.beginGoalWork(); work != nil { |
| 214 | t.Fatal("disarmed goal started a clock") |
| 215 | } |
| 216 | } |
| 217 |