package runner import ( "context" "encoding/json" "errors" "strconv" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type refusingCoordinatorAPI struct { *coordinatorAPIStub refusal error contained, rejected int pollError error } func (a *refusingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { if op == "event" && q.Event.Kind == "turn.completed" && a.refusal != nil { a.rejected++ return a.refusal } if op == "containment" { a.contained++ } if op == "poll" { return a.pollError } return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) } func TestCoordinatorRecoveryRefusedKeepsServing(t *testing.T) { for _, status := range []int{403, 409, 422} { t.Run(strconv.Itoa(status), func(t *testing.T) { ctx := context.Background() s, api, launcher, c := coordinatorServiceFixture(t) launch, _, err := s.OpenLaunch(ctx, c, nil) mustJournal(t, err) session := provider.Session{ID: "completed-session", AttemptKey: launch.AttemptKey, Provider: "claude", Family: "claude", AccountID: "account", Model: "model"} mustJournal(t, s.Journal.BindSession(ctx, session)) r := coordinatorState{Claim: c, Session: session} mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, r)) turn := provider.Turn{ID: c.Turn.ID, AdmissionID: c.Turn.ID, Prompt: "hello"} mustJournal(t, s.Journal.BeginTurn(ctx, session, turn)) mustJournal(t, s.Journal.consumeTurn(ctx, session.AttemptKey, session.ID, turn.Prompt)) pump := EventPump{Journal: s.Journal, Contain: func(context.Context) error { return nil }} mustJournal(t, pump.AppendDirect(ctx, session, provider.Event{SessionID: session.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)}, s.template(r))) refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Reason: "coordinator.fenced", Status: status}} s.API = refused for restart := 0; restart < 2; restart++ { path := s.Journal.path mustJournal(t, s.Journal.Close()) s.Journal, err = OpenJournal(ctx, path) mustJournal(t, err) defer s.Journal.Close() runSpecialistAfterCoordinator(t, s) } if refused.contained != 1 || refused.rejected != 1 || launcher.starts != 0 { t.Fatalf("refused recovery repeated or missed containment: %+v starts=%d", refused, launcher.starts) } var states []coordinatorState mustJournal(t, s.Journal.readStates(ctx, "coordinator", &states)) if len(states) != 1 || !states[0].Finished || !states[0].Refused { t.Fatal("refusal not durably retired") } }) } } func runSpecialistAfterCoordinator(t *testing.T, coordinator *CoordinatorService) { t.Helper() s, record, _, _ := cleanupFixture(t) s.journal = coordinator.Journal record.Phase = "contained" mustJournal(t, s.save(context.Background(), record)) s.workflow = &BugWorkflow{} source := &resilientSource{attempt: true} ran := false service := Service{Supervisor: s, Source: source, Coordinator: coordinator, BeforeRun: func(RunClaim) { ran = true }} ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() err := service.Run(ctx) if !errors.Is(err, context.Canceled) || !ran { t.Fatalf("coordinator stopped specialist work: ran=%v error=%v", ran, err) } } func TestCoordinatorPollErrorKeepsServing(t *testing.T) { s, api, _, _ := coordinatorServiceFixture(t) s.API = &refusingCoordinatorAPI{coordinatorAPIStub: api, pollError: ErrTransient} runSpecialistAfterCoordinator(t, s) } func TestCoordinatorCleanupRefusalReportsContainment(t *testing.T) { s, api, _, c := coordinatorServiceFixture(t) refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Reason: "coordinator.fenced", Status: 403}} s.API = refused _ = s.RunTurn(context.Background(), c) if refused.contained != 1 { t.Fatal("cleanup skipped containment after delivery refusal") } mustJournal(t, s.Recover(context.Background())) if refused.contained != 1 { t.Fatal("cleanup refusal retried on recovery") } } type countingCoordinatorAPI struct { *coordinatorAPIStub renews, polls atomic.Int32 } func (a *countingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { if op == "renew" { a.renews.Add(1) } if op == "poll" { a.polls.Add(1) return nil } return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) } func TestCoordinatorRenewalCadence(t *testing.T) { s, api, l, c := coordinatorServiceFixture(t) counted := &countingCoordinatorAPI{coordinatorAPIStub: api} s.API = counted l.hold = true l.started = make(chan struct{}) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() done := make(chan error, 1) go func() { done <- s.RunTurn(ctx, c) }() select { case <-l.started: case <-ctx.Done(): t.Fatal("fixture did not start") } before := counted.renews.Load() time.Sleep(1100 * time.Millisecond) after := counted.renews.Load() cancel() <-done if after != before { t.Fatal("idle turn renewed too frequently", before, after) } } func TestCoordinatorWaitingObserverChanges(t *testing.T) { counted := &countingCoordinatorAPI{} s := &Service{Coordinator: &CoordinatorService{API: counted}} err := s.withCoordinatorWaiting(context.Background(), func() error { time.Sleep(1200 * time.Millisecond) if n := counted.polls.Load(); n != 1 { t.Errorf("waiting observer polled without a state change: %d", n) } return nil }) mustJournal(t, err) if n := counted.polls.Load(); n != 2 { t.Fatal("release did not refresh waiting status", n) } } type containmentRetryAPI struct { attempts int } func (a *containmentRetryAPI) CoordinatorCall(_ context.Context, op string, _ runnerproto.CoordinatorRequest, _ any) error { if op != "containment" { return provider.ErrContract } a.attempts++ if a.attempts == 1 { return ErrTransient } return nil } func TestCoordinatorRefusalContainmentRetry(t *testing.T) { s, _, _, c := coordinatorServiceFixture(t) api := &containmentRetryAPI{} s.API = api state := coordinatorState{Claim: c} proof := runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle} refusal := &RefusalError{Reason: "coordinator.fenced", Status: 403} err := s.finishContained(context.Background(), &state, proof, refusal) if !errors.Is(err, ErrTransient) || fatalServiceError(err) || state.Finished { t.Fatal("delivery refusal made transient containment failure fatal", err) } mustJournal(t, s.finishContained(context.Background(), &state, proof, refusal)) if !state.Finished || !state.Refused { t.Fatal("successful retry did not retire refused turn") } }