| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "strconv" |
| 8 | "sync/atomic" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 13 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 14 | ) |
| 15 | |
| 16 | type refusingCoordinatorAPI struct { |
| 17 | *coordinatorAPIStub |
| 18 | refusal error |
| 19 | contained, rejected int |
| 20 | pollError error |
| 21 | } |
| 22 | |
| 23 | func (a *refusingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| 24 | if op == "event" && q.Event.Kind == "turn.completed" && a.refusal != nil { |
| 25 | a.rejected++ |
| 26 | return a.refusal |
| 27 | } |
| 28 | if op == "containment" { |
| 29 | a.contained++ |
| 30 | } |
| 31 | if op == "poll" { |
| 32 | return a.pollError |
| 33 | } |
| 34 | return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) |
| 35 | } |
| 36 | func TestCoordinatorRecoveryRefusedKeepsServing(t *testing.T) { |
| 37 | for _, status := range []int{403, 409, 422} { |
| 38 | t.Run(strconv.Itoa(status), func(t *testing.T) { |
| 39 | ctx := context.Background() |
| 40 | s, api, launcher, c := coordinatorServiceFixture(t) |
| 41 | launch, _, err := s.OpenLaunch(ctx, c, nil) |
| 42 | mustJournal(t, err) |
| 43 | session := provider.Session{ID: "completed-session", AttemptKey: launch.AttemptKey, Provider: "claude", Family: "claude", AccountID: "account", Model: "model"} |
| 44 | mustJournal(t, s.Journal.BindSession(ctx, session)) |
| 45 | r := coordinatorState{Claim: c, Session: session} |
| 46 | mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, r)) |
| 47 | turn := provider.Turn{ID: c.Turn.ID, AdmissionID: c.Turn.ID, Prompt: "hello"} |
| 48 | mustJournal(t, s.Journal.BeginTurn(ctx, session, turn)) |
| 49 | mustJournal(t, s.Journal.consumeTurn(ctx, session.AttemptKey, session.ID, turn.Prompt)) |
| 50 | pump := EventPump{Journal: s.Journal, Contain: func(context.Context) error { return nil }} |
| 51 | mustJournal(t, pump.AppendDirect(ctx, session, provider.Event{SessionID: session.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)}, s.template(r))) |
| 52 | refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Reason: "coordinator.fenced", Status: status}} |
| 53 | s.API = refused |
| 54 | for restart := 0; restart < 2; restart++ { |
| 55 | path := s.Journal.path |
| 56 | mustJournal(t, s.Journal.Close()) |
| 57 | s.Journal, err = OpenJournal(ctx, path) |
| 58 | mustJournal(t, err) |
| 59 | defer s.Journal.Close() |
| 60 | runSpecialistAfterCoordinator(t, s) |
| 61 | } |
| 62 | if refused.contained != 1 || refused.rejected != 1 || launcher.starts != 0 { |
| 63 | t.Fatalf("refused recovery repeated or missed containment: %+v starts=%d", refused, launcher.starts) |
| 64 | } |
| 65 | var states []coordinatorState |
| 66 | mustJournal(t, s.Journal.readStates(ctx, "coordinator", &states)) |
| 67 | if len(states) != 1 || !states[0].Finished || !states[0].Refused { |
| 68 | t.Fatal("refusal not durably retired") |
| 69 | } |
| 70 | }) |
| 71 | } |
| 72 | } |
| 73 | func runSpecialistAfterCoordinator(t *testing.T, coordinator *CoordinatorService) { |
| 74 | t.Helper() |
| 75 | s, record, _, _ := cleanupFixture(t) |
| 76 | s.journal = coordinator.Journal |
| 77 | record.Phase = "contained" |
| 78 | mustJournal(t, s.save(context.Background(), record)) |
| 79 | s.workflow = &BugWorkflow{} |
| 80 | source := &resilientSource{attempt: true} |
| 81 | ran := false |
| 82 | service := Service{Supervisor: s, Source: source, Coordinator: coordinator, BeforeRun: func(RunClaim) { ran = true }} |
| 83 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 84 | defer cancel() |
| 85 | err := service.Run(ctx) |
| 86 | if !errors.Is(err, context.Canceled) || !ran { |
| 87 | t.Fatalf("coordinator stopped specialist work: ran=%v error=%v", ran, err) |
| 88 | } |
| 89 | } |
| 90 | func TestCoordinatorPollErrorKeepsServing(t *testing.T) { |
| 91 | s, api, _, _ := coordinatorServiceFixture(t) |
| 92 | s.API = &refusingCoordinatorAPI{coordinatorAPIStub: api, pollError: ErrTransient} |
| 93 | runSpecialistAfterCoordinator(t, s) |
| 94 | } |
| 95 | func TestCoordinatorCleanupRefusalReportsContainment(t *testing.T) { |
| 96 | s, api, _, c := coordinatorServiceFixture(t) |
| 97 | refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Reason: "coordinator.fenced", Status: 403}} |
| 98 | s.API = refused |
| 99 | _ = s.RunTurn(context.Background(), c) |
| 100 | if refused.contained != 1 { |
| 101 | t.Fatal("cleanup skipped containment after delivery refusal") |
| 102 | } |
| 103 | mustJournal(t, s.Recover(context.Background())) |
| 104 | if refused.contained != 1 { |
| 105 | t.Fatal("cleanup refusal retried on recovery") |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | type countingCoordinatorAPI struct { |
| 110 | *coordinatorAPIStub |
| 111 | renews, polls atomic.Int32 |
| 112 | } |
| 113 | |
| 114 | func (a *countingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| 115 | if op == "renew" { |
| 116 | a.renews.Add(1) |
| 117 | } |
| 118 | if op == "poll" { |
| 119 | a.polls.Add(1) |
| 120 | return nil |
| 121 | } |
| 122 | return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) |
| 123 | } |
| 124 | func TestCoordinatorRenewalCadence(t *testing.T) { |
| 125 | s, api, l, c := coordinatorServiceFixture(t) |
| 126 | counted := &countingCoordinatorAPI{coordinatorAPIStub: api} |
| 127 | s.API = counted |
| 128 | l.hold = true |
| 129 | l.started = make(chan struct{}) |
| 130 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 131 | defer cancel() |
| 132 | done := make(chan error, 1) |
| 133 | go func() { done <- s.RunTurn(ctx, c) }() |
| 134 | select { |
| 135 | case <-l.started: |
| 136 | case <-ctx.Done(): |
| 137 | t.Fatal("fixture did not start") |
| 138 | } |
| 139 | before := counted.renews.Load() |
| 140 | time.Sleep(1100 * time.Millisecond) |
| 141 | after := counted.renews.Load() |
| 142 | cancel() |
| 143 | <-done |
| 144 | if after != before { |
| 145 | t.Fatal("idle turn renewed too frequently", before, after) |
| 146 | } |
| 147 | } |
| 148 | func TestCoordinatorWaitingObserverChanges(t *testing.T) { |
| 149 | counted := &countingCoordinatorAPI{} |
| 150 | s := &Service{Coordinator: &CoordinatorService{API: counted}} |
| 151 | err := s.withCoordinatorWaiting(context.Background(), func() error { |
| 152 | time.Sleep(1200 * time.Millisecond) |
| 153 | if n := counted.polls.Load(); n != 1 { |
| 154 | t.Errorf("waiting observer polled without a state change: %d", n) |
| 155 | } |
| 156 | return nil |
| 157 | }) |
| 158 | mustJournal(t, err) |
| 159 | if n := counted.polls.Load(); n != 2 { |
| 160 | t.Fatal("release did not refresh waiting status", n) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | type containmentRetryAPI struct { |
| 165 | attempts int |
| 166 | } |
| 167 | |
| 168 | func (a *containmentRetryAPI) CoordinatorCall(_ context.Context, op string, _ runnerproto.CoordinatorRequest, _ any) error { |
| 169 | if op != "containment" { |
| 170 | return provider.ErrContract |
| 171 | } |
| 172 | a.attempts++ |
| 173 | if a.attempts == 1 { |
| 174 | return ErrTransient |
| 175 | } |
| 176 | return nil |
| 177 | } |
| 178 | func TestCoordinatorRefusalContainmentRetry(t *testing.T) { |
| 179 | s, _, _, c := coordinatorServiceFixture(t) |
| 180 | api := &containmentRetryAPI{} |
| 181 | s.API = api |
| 182 | state := coordinatorState{Claim: c} |
| 183 | proof := runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle} |
| 184 | refusal := &RefusalError{Reason: "coordinator.fenced", Status: 403} |
| 185 | err := s.finishContained(context.Background(), &state, proof, refusal) |
| 186 | if !errors.Is(err, ErrTransient) || fatalServiceError(err) || state.Finished { |
| 187 | t.Fatal("delivery refusal made transient containment failure fatal", err) |
| 188 | } |
| 189 | mustJournal(t, s.finishContained(context.Background(), &state, proof, refusal)) |
| 190 | if !state.Finished || !state.Refused { |
| 191 | t.Fatal("successful retry did not retire refused turn") |
| 192 | } |
| 193 | } |
| 194 | |