返回 DeepSeek-Reasonix
goal_driver_test.go
根目录 / internal / control / goal_driver_test.go
1 package control
2
3 import (
4 "context"
5 "errors"
6 "os"
7 "strings"
8 "sync"
9 "testing"
10 "time"
11
12 "reasonix/internal/agent"
13 "reasonix/internal/event"
14 goaldomain "reasonix/internal/goal"
15 "reasonix/internal/provider"
16 "reasonix/internal/session"
17 "reasonix/internal/tool"
18 )
19
20 func cleanupGoalDriverController(t *testing.T, c *Controller) {
21 t.Helper()
22 t.Cleanup(func() {
23 service, runtime, exclusive := c.v3Binding()
24 c.Close()
25 deadline := time.Now().Add(5 * time.Second)
26 for time.Now().Before(deadline) {
27 c.goalDriverMu.Lock()
28 settled := !c.goalDriverPending && c.goalDriverActive == nil
29 c.goalDriverMu.Unlock()
30 runtimeRetired := !exclusive || service == nil || runtime == nil || goalRuntimeRetired(c, service, runtime, settled)
31 if settled && !c.Running() && runtimeRetired {
32 return
33 }
34 time.Sleep(time.Millisecond)
35 }
36 t.Error("goal controller did not settle after close")
37 })
38 }
39
40 type lifecycleDriverRunner struct {
41 mu sync.Mutex
42 calls int
43 inputs []string
44 done chan struct{}
45 }
46
47 func (r *lifecycleDriverRunner) Run(ctx context.Context, input string) error {
48 r.mu.Lock()
49 r.calls++
50 call := r.calls
51 r.inputs = append(r.inputs, input)
52 r.mu.Unlock()
53 binding, ok := tool.GoalLifecycleFromContext(ctx)
54 if !ok {
55 return context.Canceled
56 }
57 switch call {
58 case 1:
59 if binding.Authority.Source != tool.GoalSourceDirectHuman {
60 return context.Canceled
61 }
62 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "finish the lifecycle"}, binding.Authority)
63 return err
64 case 2:
65 // A normal final response is not a lifecycle transition. Leaving the
66 // target active must cause another independently admitted top-level turn.
67 if binding.Authority.Source != tool.GoalSourceGoalRound {
68 return context.Canceled
69 }
70 return nil
71 case 3:
72 if binding.Authority.Source != tool.GoalSourceGoalRound {
73 return context.Canceled
74 }
75 view, err := binding.Owner.GetGoal(ctx)
76 if err != nil {
77 return err
78 }
79 _, err = binding.Owner.UpdateGoal(ctx, tool.GoalUpdateRequest{Ref: view.Ref(), Action: tool.GoalActionComplete}, binding.Authority)
80 close(r.done)
81 return err
82 default:
83 return context.Canceled
84 }
85 }
86
87 func TestGoalDriverContinuesAfterFinalAndCompletesThroughExactRoundAuthority(t *testing.T) {
88 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
89 if err != nil {
90 t.Fatal(err)
91 }
92 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
93 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-driver"})
94 if err != nil {
95 t.Fatal(err)
96 }
97 runner := &lifecycleDriverRunner{done: make(chan struct{})}
98 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
99 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
100 cleanupGoalDriverController(t, c)
101 c.Send("work until the whole target is finished")
102 select {
103 case <-runner.done:
104 case <-time.After(5 * time.Second):
105 t.Fatal("automatic goal round did not run")
106 }
107 deadline := time.Now().Add(5 * time.Second)
108 for (c.Running() || c.GoalStatus() != GoalStatusComplete) && time.Now().Before(deadline) {
109 time.Sleep(time.Millisecond)
110 }
111 if c.GoalStatus() != GoalStatusComplete {
112 t.Fatalf("goal status = %q", c.GoalStatus())
113 }
114 view, err := c.goalLifecycleView()
115 if err != nil || view == nil || view.RoundsStarted != 2 || view.Revision != 2 {
116 t.Fatalf("goal view = %+v, err = %v", view, err)
117 }
118 if got := c.GoalRuntime().WorkDurationMs; got <= 0 {
119 t.Fatalf("completed automatic rounds have work duration %d, want positive cumulative active time", got)
120 }
121 runner.mu.Lock()
122 defer runner.mu.Unlock()
123 if runner.calls != 3 || !strings.Contains(runner.inputs[1], `"round":1`) || !strings.Contains(runner.inputs[2], `"round":2`) || !strings.Contains(runner.inputs[1], "<goal-round>") {
124 t.Fatalf("calls/inputs = %d %#v", runner.calls, runner.inputs)
125 }
126 if _, err := runtime.Session().Flush(t.Context()); err != nil {
127 t.Fatal(err)
128 }
129 commits, err := runtime.Session().Handle().Read(t.Context(), 1, 100)
130 if err != nil {
131 t.Fatal(err)
132 }
133 foundAtomicAdmission := false
134 for _, commit := range commits.Commits {
135 hasStart, hasGoal := false, false
136 for _, item := range commit.Events {
137 hasStart = hasStart || item.Kind == "turn/start"
138 hasGoal = hasGoal || item.Kind == "goal/state"
139 }
140 foundAtomicAdmission = foundAtomicAdmission || hasStart && hasGoal
141 }
142 if !foundAtomicAdmission {
143 t.Fatal("automatic round did not atomically commit turn/start with goal/state")
144 }
145 }
146
147 type limitedGoalRunner struct {
148 mu sync.Mutex
149 calls int
150 }
151
152 func (r *limitedGoalRunner) Run(ctx context.Context, _ string) error {
153 r.mu.Lock()
154 r.calls++
155 call := r.calls
156 r.mu.Unlock()
157 binding, ok := tool.GoalLifecycleFromContext(ctx)
158 if !ok {
159 return context.Canceled
160 }
161 if call == 1 {
162 limit := uint64(1)
163 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "one automatic round", MaxGoalRounds: &limit}, binding.Authority)
164 return err
165 }
166 return nil
167 }
168
169 func TestGoalDriverTurnsExplicitRoundLimitIntoBlockedState(t *testing.T) {
170 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
171 if err != nil {
172 t.Fatal(err)
173 }
174 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
175 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-limit"})
176 if err != nil {
177 t.Fatal(err)
178 }
179 runner := &limitedGoalRunner{}
180 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
181 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
182 cleanupGoalDriverController(t, c)
183 c.Send("run exactly one automatic round")
184 deadline := time.Now().Add(5 * time.Second)
185 for time.Now().Before(deadline) {
186 view, viewErr := c.goalLifecycleView()
187 if viewErr != nil {
188 t.Fatal(viewErr)
189 }
190 if view != nil && view.Phase == goaldomain.PhaseBlocked {
191 if view.RoundsStarted != 1 || view.BlockedReason == nil || view.BlockedReason.Code != "round-limit" {
192 t.Fatalf("blocked view = %+v", view)
193 }
194 return
195 }
196 time.Sleep(time.Millisecond)
197 }
198 t.Fatal("round-limited goal did not enter blocked state")
199 }
200
201 func TestDuplicateGoalDriverKicksAdmitOnlyOneRound(t *testing.T) {
202 // Reservation identity is checked again after Flush and by guarded turn
203 // admission; this focused test exercises level-trigger collapse itself.
204 c := &Controller{}
205 c.closed = true
206 for range 20 {
207 c.kickGoalDriver()
208 }
209 c.goalDriverMu.Lock()
210 defer c.goalDriverMu.Unlock()
211 if c.goalDriverPending || c.goalDriverActive != nil {
212 t.Fatalf("closed driver accepted work: pending=%v active=%v", c.goalDriverPending, c.goalDriverActive)
213 }
214 }
215
216 type gatedGoalRunner struct {
217 mu sync.Mutex
218 calls int
219 started chan struct{}
220 release chan struct{}
221 }
222
223 func (r *gatedGoalRunner) Run(ctx context.Context, _ string) error {
224 r.mu.Lock()
225 r.calls++
226 call := r.calls
227 r.mu.Unlock()
228 binding, ok := tool.GoalLifecycleFromContext(ctx)
229 if !ok {
230 return context.Canceled
231 }
232 if call == 1 {
233 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "deduplicate idle notifications"}, binding.Authority)
234 return err
235 }
236 if call == 2 {
237 close(r.started)
238 select {
239 case <-r.release:
240 case <-ctx.Done():
241 return ctx.Err()
242 }
243 view, err := binding.Owner.GetGoal(ctx)
244 if err != nil {
245 return err
246 }
247 _, err = binding.Owner.UpdateGoal(ctx, tool.GoalUpdateRequest{Ref: view.Ref(), Action: tool.GoalActionComplete}, binding.Authority)
248 return err
249 }
250 return context.Canceled
251 }
252
253 func TestConcurrentIdleKicksCannotAdmitParallelGoalRounds(t *testing.T) {
254 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
255 if err != nil {
256 t.Fatal(err)
257 }
258 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
259 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-dedup"})
260 if err != nil {
261 t.Fatal(err)
262 }
263 runner := &gatedGoalRunner{started: make(chan struct{}), release: make(chan struct{})}
264 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
265 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
266 cleanupGoalDriverController(t, c)
267 c.Send("start a deduplicated target")
268 select {
269 case <-runner.started:
270 case <-time.After(5 * time.Second):
271 t.Fatal("automatic round did not start")
272 }
273 var kicks sync.WaitGroup
274 for range 32 {
275 kicks.Go(func() {
276 c.kickGoalDriver()
277 })
278 }
279 kicks.Wait()
280 runner.mu.Lock()
281 calls := runner.calls
282 runner.mu.Unlock()
283 if calls != 2 {
284 t.Fatalf("parallel idle kicks admitted %d calls, want initial + one goal round", calls)
285 }
286 close(runner.release)
287 deadline := time.Now().Add(5 * time.Second)
288 for time.Now().Before(deadline) {
289 view, _ := c.goalLifecycleView()
290 if view != nil && view.Phase == goaldomain.PhaseComplete {
291 return
292 }
293 time.Sleep(time.Millisecond)
294 }
295 t.Fatal("deduplicated goal round did not finish")
296 }
297
298 type cancelGoalRunner struct {
299 started chan struct{}
300 }
301
302 func (r *cancelGoalRunner) Run(ctx context.Context, _ string) error {
303 binding, ok := tool.GoalLifecycleFromContext(ctx)
304 if !ok {
305 return context.Canceled
306 }
307 if binding.Authority.Source == tool.GoalSourceDirectHuman {
308 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "pause the running target"}, binding.Authority)
309 return err
310 }
311 close(r.started)
312 <-ctx.Done()
313 return ctx.Err()
314 }
315
316 func TestPausingRunningGoalRoundCancelsActivityAndPersistsPaused(t *testing.T) {
317 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
318 if err != nil {
319 t.Fatal(err)
320 }
321 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
322 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-cancel"})
323 if err != nil {
324 t.Fatal(err)
325 }
326 runner := &cancelGoalRunner{started: make(chan struct{})}
327 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
328 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
329 cleanupGoalDriverController(t, c)
330 c.Send("start then pause")
331 select {
332 case <-runner.started:
333 case <-time.After(5 * time.Second):
334 t.Fatal("automatic goal round did not start")
335 }
336 if !c.PauseGoal() {
337 t.Fatal("PauseGoal rejected an active goal round")
338 }
339 deadline := time.Now().Add(5 * time.Second)
340 for c.Running() && time.Now().Before(deadline) {
341 time.Sleep(time.Millisecond)
342 }
343 view, err := c.goalLifecycleView()
344 if err != nil || view == nil || view.Phase != goaldomain.PhasePaused || view.Activation != goaldomain.ActivationDisarmed || view.RoundsStarted != 1 {
345 t.Fatalf("paused view = %+v, err = %v", view, err)
346 }
347 }
348
349 type completeThenCancelGoalRunner struct {
350 completed chan struct{}
351 }
352
353 func (r *completeThenCancelGoalRunner) Run(ctx context.Context, _ string) error {
354 binding, ok := tool.GoalLifecycleFromContext(ctx)
355 if !ok {
356 return context.Canceled
357 }
358 if binding.Authority.Source == tool.GoalSourceDirectHuman {
359 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "complete before cancellation"}, binding.Authority)
360 return err
361 }
362 view, err := binding.Owner.GetGoal(ctx)
363 if err != nil {
364 return err
365 }
366 if _, err := binding.Owner.UpdateGoal(ctx, tool.GoalUpdateRequest{Ref: view.Ref(), Action: tool.GoalActionComplete}, binding.Authority); err != nil {
367 return err
368 }
369 close(r.completed)
370 <-ctx.Done()
371 return ctx.Err()
372 }
373
374 func TestCancellationAfterAcceptedCompleteDoesNotRewriteGoalToPaused(t *testing.T) {
375 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
376 if err != nil {
377 t.Fatal(err)
378 }
379 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
380 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-complete-then-cancel"})
381 if err != nil {
382 t.Fatal(err)
383 }
384 runner := &completeThenCancelGoalRunner{completed: make(chan struct{})}
385 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
386 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
387 cleanupGoalDriverController(t, c)
388 c.Send("start and finish the target")
389 select {
390 case <-runner.completed:
391 case <-time.After(5 * time.Second):
392 t.Fatal("automatic goal round did not complete")
393 }
394 c.Cancel()
395 deadline := time.Now().Add(5 * time.Second)
396 for c.Running() && time.Now().Before(deadline) {
397 time.Sleep(time.Millisecond)
398 }
399 view, err := c.goalLifecycleView()
400 if err != nil || view == nil || view.Phase != goaldomain.PhaseComplete || view.StopReason != "complete" {
401 t.Fatalf("completed goal after cancellation = %+v, err = %v", view, err)
402 }
403 }
404
405 type unlimitedGoalRunner struct {
406 mu sync.Mutex
407 calls uint64
408 autoLimit uint64
409 done chan struct{}
410 }
411
412 func (r *unlimitedGoalRunner) Run(ctx context.Context, _ string) error {
413 r.mu.Lock()
414 r.calls++
415 r.mu.Unlock()
416 binding, ok := tool.GoalLifecycleFromContext(ctx)
417 if !ok {
418 return context.Canceled
419 }
420 if binding.Authority.Source == tool.GoalSourceDirectHuman {
421 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "run beyond the old hidden ceiling"}, binding.Authority)
422 return err
423 }
424 if binding.Authority.Round == r.autoLimit {
425 view, err := binding.Owner.GetGoal(ctx)
426 if err != nil {
427 return err
428 }
429 _, err = binding.Owner.UpdateGoal(ctx, tool.GoalUpdateRequest{Ref: view.Ref(), Action: tool.GoalActionComplete}, binding.Authority)
430 close(r.done)
431 return err
432 }
433 return nil
434 }
435
436 func TestUnlimitedGoalDriverRunsBeyondHarnessDefaultCeiling(t *testing.T) {
437 service := goalRoundTestService(t)
438 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-unlimited"})
439 if err != nil {
440 t.Fatal(err)
441 }
442 runner := &unlimitedGoalRunner{autoLimit: 257, done: make(chan struct{})}
443 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
444 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
445 cleanupGoalDriverController(t, c)
446 c.Send("exercise the unlimited goal driver")
447 select {
448 case <-runner.done:
449 // This asserts the admission count, not disk throughput. The enclosing
450 // test command supplies the watchdog for a genuinely stalled driver.
451 case <-t.Context().Done():
452 t.Fatal("unlimited goal did not cross 256 admitted automatic rounds")
453 }
454 view, err := c.goalLifecycleView()
455 if err != nil || view == nil || view.Phase != goaldomain.PhaseComplete || view.RoundsStarted != 257 || view.MaxGoalRounds != nil {
456 t.Fatalf("unlimited goal view = %+v, err = %v", view, err)
457 }
458 waitForGoalDriverIdle(t, c, runtime)
459 }
460
461 func waitForGoalDriverIdle(t *testing.T, c *Controller, runtime *session.Runtime) {
462 t.Helper()
463 deadline := time.Now().Add(5 * time.Second)
464 for time.Now().Before(deadline) {
465 c.goalDriverMu.Lock()
466 settled := !c.goalDriverPending && c.goalDriverActive == nil
467 c.goalDriverMu.Unlock()
468 if settled && !c.Running() && runtime.Snapshot().Phase == session.RuntimeIdle {
469 return
470 }
471 time.Sleep(time.Millisecond)
472 }
473 t.Fatal("goal driver did not return to idle after terminal update")
474 }
475
476 type budgetedGoalRunner struct {
477 usage event.Sink
478 calls int
479 }
480
481 func (r *budgetedGoalRunner) Run(ctx context.Context, _ string) error {
482 r.calls++
483 binding, ok := tool.GoalLifecycleFromContext(ctx)
484 if !ok {
485 return context.Canceled
486 }
487 if binding.Authority.Source == tool.GoalSourceDirectHuman {
488 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "respect the host resource budget"}, binding.Authority)
489 return err
490 }
491 r.usage.Emit(event.Event{Kind: event.Usage, UsageSource: event.UsageSourceExecutor,
492 Usage: &provider.Usage{PromptTokens: 80, CompletionTokens: 40, TotalTokens: 120, RequestCount: 1}})
493 return nil
494 }
495
496 func TestGoalDriverBlocksAtExplicitHostTokenBudget(t *testing.T) {
497 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
498 if err != nil {
499 t.Fatal(err)
500 }
501 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
502 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-budget"})
503 if err != nil {
504 t.Fatal(err)
505 }
506 runner := &budgetedGoalRunner{}
507 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
508 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, GoalTokenBudget: 100,
509 SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
510 runner.usage = c.goalUsageTee
511 cleanupGoalDriverController(t, c)
512 c.Send("run within a fixed token budget")
513 deadline := time.Now().Add(5 * time.Second)
514 for time.Now().Before(deadline) {
515 view, _ := c.goalLifecycleView()
516 if view != nil && view.Phase == goaldomain.PhaseBlocked {
517 if view.BlockedReason == nil || view.BlockedReason.Code != "resource-budget" || view.RoundsStarted != 1 || runner.calls != 2 {
518 t.Fatalf("blocked view/calls = %+v / %d", view, runner.calls)
519 }
520 runtimeView := c.GoalRuntime()
521 if runtimeView.TokensUsed != 120 || runtimeView.TokensLimit != 100 || runtimeView.RequestsUsed != 1 {
522 t.Fatalf("resource runtime = %+v", runtimeView)
523 }
524 return
525 }
526 time.Sleep(time.Millisecond)
527 }
528 t.Fatal("goal did not stop at the explicit host token budget")
529 }
530
531 type modelErrorGoalRunner struct {
532 calls int
533 }
534
535 func (r *modelErrorGoalRunner) Run(ctx context.Context, _ string) error {
536 r.calls++
537 binding, ok := tool.GoalLifecycleFromContext(ctx)
538 if !ok {
539 return context.Canceled
540 }
541 if binding.Authority.Source == tool.GoalSourceDirectHuman {
542 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "stop safely on provider errors"}, binding.Authority)
543 return err
544 }
545 return errors.New("provider failed")
546 }
547
548 func TestGoalRoundModelErrorDisarmsWithoutCompleting(t *testing.T) {
549 service, err := session.NewService("desktop", session.NewFilesystemPersistence(t.TempDir()))
550 if err != nil {
551 t.Fatal(err)
552 }
553 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
554 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-model-error"})
555 if err != nil {
556 t.Fatal(err)
557 }
558 runner := &modelErrorGoalRunner{}
559 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
560 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
561 cleanupGoalDriverController(t, c)
562 c.Send("exercise model failure")
563 deadline := time.Now().Add(5 * time.Second)
564 for time.Now().Before(deadline) {
565 view, _ := c.goalLifecycleView()
566 if view != nil && view.Activation == goaldomain.ActivationDisarmed && view.StopReason == "model-error" {
567 if view.Phase != goaldomain.PhaseActive || view.RoundsStarted != 1 || runner.calls != 2 {
568 t.Fatalf("error view/calls = %+v / %d", view, runner.calls)
569 }
570 return
571 }
572 time.Sleep(time.Millisecond)
573 }
574 t.Fatal("model error did not disarm the active goal")
575 }
576
577 type failingFlushPersistence struct {
578 session *session.Session
579 }
580
581 func (p failingFlushPersistence) Create(session.CreateOptions) (*session.Session, error) {
582 return p.session, nil
583 }
584 func (p failingFlushPersistence) Open(string, session.AccessMode) (*session.Session, error) {
585 return nil, session.ErrSessionNotFound
586 }
587 func (p failingFlushPersistence) Stat(context.Context, string) (session.SessionInfo, error) {
588 return session.SessionInfo{}, session.ErrSessionNotFound
589 }
590 func (p failingFlushPersistence) List(context.Context, string, int) (session.SessionPage, error) {
591 return session.SessionPage{}, nil
592 }
593
594 func TestGoalDriverFlushFailureStartsNoAutomaticModelCall(t *testing.T) {
595 store, err := session.CreateWithOptions(t.TempDir()+"/goal-flush", "goal-flush", session.OpenOptions{
596 Sync: func(*os.File) error { return errors.New("injected sync failure") },
597 })
598 if err != nil {
599 t.Fatal(err)
600 }
601 service, err := session.NewService("desktop", failingFlushPersistence{session: store})
602 if err != nil {
603 t.Fatal(err)
604 }
605 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
606 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-flush"})
607 if err != nil {
608 t.Fatal(err)
609 }
610 runner := &modelErrorGoalRunner{}
611 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
612 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
613 cleanupGoalDriverController(t, c)
614 c.Send("create before a failed checkpoint")
615 deadline := time.Now().Add(5 * time.Second)
616 for time.Now().Before(deadline) {
617 view, _ := c.goalLifecycleView()
618 if view != nil && view.StopReason == "persistence-error" {
619 if runner.calls != 1 || view.RoundsStarted != 0 || view.Phase != goaldomain.PhaseActive || view.Activation != goaldomain.ActivationDisarmed {
620 t.Fatalf("persistence failure view/calls = %+v / %d", view, runner.calls)
621 }
622 return
623 }
624 time.Sleep(time.Millisecond)
625 }
626 t.Fatal("failed durability checkpoint did not stop automatic scheduling")
627 }
628
629 type userWinsRunner struct {
630 mu sync.Mutex
631 sources []tool.GoalSource
632 }
633
634 func (r *userWinsRunner) Run(ctx context.Context, _ string) error {
635 binding, ok := tool.GoalLifecycleFromContext(ctx)
636 if !ok {
637 return context.Canceled
638 }
639 r.mu.Lock()
640 r.sources = append(r.sources, binding.Authority.Source)
641 call := len(r.sources)
642 r.mu.Unlock()
643 if call == 1 {
644 _, err := binding.Owner.CreateGoal(ctx, goaldomain.CreateRequest{Objective: "let queued user input win"}, binding.Authority)
645 return err
646 }
647 view, err := binding.Owner.GetGoal(ctx)
648 if err != nil {
649 return err
650 }
651 _, err = binding.Owner.UpdateGoal(ctx, tool.GoalUpdateRequest{Ref: view.Ref(), Action: tool.GoalActionComplete}, binding.Authority)
652 return err
653 }
654
655 func TestUserInputArrivingDuringGoalFlushWinsAdmission(t *testing.T) {
656 flushStarted := make(chan struct{})
657 releaseFlush := make(chan struct{})
658 var once sync.Once
659 store, err := session.CreateWithOptions(t.TempDir()+"/goal-user-wins", "goal-user-wins", session.OpenOptions{
660 Sync: func(*os.File) error {
661 once.Do(func() { close(flushStarted) })
662 <-releaseFlush
663 return nil
664 },
665 })
666 if err != nil {
667 t.Fatal(err)
668 }
669 service, err := session.NewService("desktop", failingFlushPersistence{session: store})
670 if err != nil {
671 t.Fatal(err)
672 }
673 t.Cleanup(func() { _ = service.CloseAll(context.Background()) })
674 runtime, err := service.Create(t.Context(), session.CreateOptions{SessionID: "goal-user-wins"})
675 if err != nil {
676 t.Fatal(err)
677 }
678 runner := &userWinsRunner{}
679 exec := agent.New(nil, tool.NewRegistry(), agent.NewSession("system"), agent.Options{}, event.Discard)
680 c := newOwnedTestController(t, Options{Runner: runner, Executor: exec, Sink: event.Discard, SessionService: service, SessionRuntime: runtime, ExclusiveSession: true})
681 cleanupGoalDriverController(t, c)
682 c.Send("create the target")
683 select {
684 case <-flushStarted:
685 case <-time.After(5 * time.Second):
686 t.Fatal("goal driver did not reach the durability checkpoint")
687 }
688 c.Send("finish it from my newer message")
689 close(releaseFlush)
690 deadline := time.Now().Add(5 * time.Second)
691 for time.Now().Before(deadline) {
692 view, _ := c.goalLifecycleView()
693 if view != nil && view.Phase == goaldomain.PhaseComplete {
694 runner.mu.Lock()
695 sources := append([]tool.GoalSource(nil), runner.sources...)
696 runner.mu.Unlock()
697 if len(sources) != 2 || sources[0] != tool.GoalSourceDirectHuman || sources[1] != tool.GoalSourceDirectHuman || view.RoundsStarted != 0 {
698 t.Fatalf("sources/view = %v / %+v", sources, view)
699 }
700 return
701 }
702 time.Sleep(time.Millisecond)
703 }
704 t.Fatal("queued user turn did not win goal-round admission")
705 }
706
706 lines GO