| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 14 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 17 | ) |
| 18 | |
| 19 | type coordinatorAPIStub struct { |
| 20 | events []string |
| 21 | delivery bool |
| 22 | c runnerproto.CoordinatorClaim |
| 23 | crash string |
| 24 | polled bool |
| 25 | } |
| 26 | type waitingCoordinatorAPI struct { |
| 27 | polled chan struct{} |
| 28 | claims int |
| 29 | } |
| 30 | |
| 31 | func (a *waitingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, _ runnerproto.CoordinatorRequest, _ any) error { |
| 32 | if op != "poll" { |
| 33 | a.claims++ |
| 34 | return provider.ErrContract |
| 35 | } |
| 36 | select { |
| 37 | case a.polled <- struct{}{}: |
| 38 | default: |
| 39 | } |
| 40 | return nil |
| 41 | } |
| 42 | func TestCoordinatorConnectionWaitingService(t *testing.T) { |
| 43 | api := &waitingCoordinatorAPI{polled: make(chan struct{}, 1)} |
| 44 | service := &Service{Coordinator: &CoordinatorService{API: api}} |
| 45 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 46 | defer cancel() |
| 47 | if err := service.withCoordinatorWaiting(ctx, func() error { |
| 48 | select { |
| 49 | case <-api.polled: |
| 50 | return nil |
| 51 | case <-ctx.Done(): |
| 52 | return ctx.Err() |
| 53 | } |
| 54 | }); err != nil { |
| 55 | t.Fatal("specialist prevented waiting status", err) |
| 56 | } |
| 57 | if api.claims != 0 { |
| 58 | t.Fatal("waiting observer dispatched coordinator") |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | func (a *coordinatorAPIStub) CoordinatorCall(_ context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| 63 | switch op { |
| 64 | case "poll": |
| 65 | if !a.polled { |
| 66 | *out.(*[]runnerproto.CoordinatorTurn) = []runnerproto.CoordinatorTurn{a.c.Turn} |
| 67 | a.polled = true |
| 68 | } |
| 69 | case "claim", "recover": |
| 70 | *out.(*runnerproto.CoordinatorClaim) = a.c |
| 71 | case "renew": |
| 72 | *out.(*time.Time) = time.Now().Add(time.Minute) |
| 73 | case "event": |
| 74 | if q.Event.Kind == "coordinator.delivery" && a.delivery { |
| 75 | return nil |
| 76 | } |
| 77 | a.events = append(a.events, q.Event.Kind) |
| 78 | if q.Event.Kind == "coordinator.delivery" { |
| 79 | if len(a.events) < 2 || a.events[len(a.events)-2] != "turn.completed" { |
| 80 | return errors.New("delivery before receipt") |
| 81 | } |
| 82 | a.delivery = true |
| 83 | if a.crash == "ack" { |
| 84 | a.crash = "" |
| 85 | return ErrTransient |
| 86 | } |
| 87 | } |
| 88 | case "tool", "tool_result": |
| 89 | *out.(*runnerproto.CoordinatorToolResult) = runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{"tool":"post_message"}`)} |
| 90 | case "containment": |
| 91 | default: |
| 92 | return fmt.Errorf("unexpected op %s", op) |
| 93 | } |
| 94 | return nil |
| 95 | } |
| 96 | |
| 97 | type coordinatorFixtureLauncher struct { |
| 98 | j *Journal |
| 99 | launch provider.Launch |
| 100 | session provider.Session |
| 101 | proxy *ToolProxy |
| 102 | events chan provider.Event |
| 103 | starts int |
| 104 | hold bool |
| 105 | started chan struct{} |
| 106 | crash string |
| 107 | } |
| 108 | |
| 109 | func (l *coordinatorFixtureLauncher) Preflight(_ context.Context, b provider.Binding, _ provider.Policy) (provider.Identity, error) { |
| 110 | return b.Expected, nil |
| 111 | } |
| 112 | func (l *coordinatorFixtureLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) { |
| 113 | l.launch = v |
| 114 | l.session = provider.Session{ID: v.AttemptKey + "-session", AttemptKey: v.AttemptKey, Provider: v.Selection.Provider, AccountID: v.Selection.AccountID, Family: v.Selection.Family, Model: v.Selection.Model} |
| 115 | l.events = make(chan provider.Event, 4) |
| 116 | return l.session, l.j.BindSession(ctx, l.session) |
| 117 | } |
| 118 | func (l *coordinatorFixtureLauncher) Events(context.Context, provider.Session) (<-chan provider.Event, error) { |
| 119 | return l.events, nil |
| 120 | } |
| 121 | func (l *coordinatorFixtureLauncher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error { |
| 122 | if l.crash == "before-intent" { |
| 123 | return provider.ErrUncertain |
| 124 | } |
| 125 | if err := l.j.BeginTurn(ctx, s, t); err != nil { |
| 126 | return err |
| 127 | } |
| 128 | if l.crash == "intent" { |
| 129 | return provider.ErrUncertain |
| 130 | } |
| 131 | if err := l.j.consumeTurn(ctx, s.AttemptKey, s.ID, t.Prompt); err != nil { |
| 132 | return err |
| 133 | } |
| 134 | l.starts++ |
| 135 | if l.crash == "stdin" { |
| 136 | return provider.ErrUncertain |
| 137 | } |
| 138 | _, err := l.proxy.CallCoordinatorTool(ctx, runnerproto.CoordinatorToolCall{RequestID: "post", Name: "post_message", Arguments: json.RawMessage(`{"body":"answer","source_refs":[]}`)}) |
| 139 | if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | if l.crash == "tool" { |
| 143 | return provider.ErrUncertain |
| 144 | } |
| 145 | if l.hold { |
| 146 | if l.started != nil { |
| 147 | close(l.started) |
| 148 | } |
| 149 | return nil |
| 150 | } |
| 151 | l.events <- provider.Event{Sequence: 1, SessionID: s.ID, TurnID: t.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)} |
| 152 | return nil |
| 153 | } |
| 154 | func (l *coordinatorFixtureLauncher) Respond(context.Context, provider.Session, provider.Answer) error { |
| 155 | return nil |
| 156 | } |
| 157 | func (l *coordinatorFixtureLauncher) Interrupt(context.Context, provider.Session) error { return nil } |
| 158 | func (l *coordinatorFixtureLauncher) Close(context.Context, provider.Session) error { return nil } |
| 159 | |
| 160 | func coordinatorServiceFixture(t *testing.T) (*CoordinatorService, *coordinatorAPIStub, *coordinatorFixtureLauncher, runnerproto.CoordinatorClaim) { |
| 161 | t.Helper() |
| 162 | ctx := context.Background() |
| 163 | j, err := OpenJournal(ctx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 164 | mustJournal(t, err) |
| 165 | t.Cleanup(func() { j.Close() }) |
| 166 | c := runnerproto.CoordinatorClaim{Binding: runnerproto.CoordinatorBinding{ID: "binding", Person: "person", Generation: 1}, Turn: runnerproto.CoordinatorTurn{ID: "turn", Revision: 1, Generation: 1}, Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, LeaseDeadline: time.Now().Add(time.Minute), AttemptDeadline: time.Now().Add(time.Minute)} |
| 167 | c.Brief.Selection = runnerproto.Selection{Provider: "claude", Family: "claude", AccountID: "account", Model: "model", Isolation: team.IsolationSnapshot{Status: "confined"}} |
| 168 | c.Context, err = runnerproto.BoundCoordinatorContext(runnerproto.CoordinatorContext{ConversationID: "conversation", Revision: 1, Recent: []runnerproto.MessageRef{{ID: "message", AuthorKind: "person", Body: "hello", Sequence: 1, Revision: 1}}}) |
| 169 | mustJournal(t, err) |
| 170 | c.Turn.ContextHash = c.Context.Hash |
| 171 | c.Admission = team.AdmissionTicket{Scope: c.Scope, Handle: c.Handle, Dispatch: team.Dispatch{Action: 1}, ExpiresAt: time.Now().Add(5 * time.Second), Incarnation: 1} |
| 172 | a := &coordinatorAPIStub{c: c} |
| 173 | l := &coordinatorFixtureLauncher{j: j} |
| 174 | s := &CoordinatorService{Journal: j, API: a, Launchers: map[string]provider.Launcher{"claude": l}} |
| 175 | s.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
| 176 | _, err := s.Journal.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1") |
| 177 | return runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle, CheckedAt: time.Now()}, err |
| 178 | } |
| 179 | s.OpenLaunch = func(ctx context.Context, c runnerproto.CoordinatorClaim, p *ToolProxy) (provider.Launch, func() error, error) { |
| 180 | l.proxy = p |
| 181 | v := provider.Launch{AttemptKey: c.Turn.ID, Binding: provider.Binding{Provider: "claude", AccountID: "account", Expected: provider.Identity{ProviderVersion: "2.1.312"}}, Selection: provider.Selection{Provider: "claude", Family: "claude", AccountID: "account", Model: "model"}, Policy: provider.Policy{Hash: "policy", Manifest: json.RawMessage(`{"Action":"coordinate"}`)}} |
| 182 | v.Policy.ManifestHash = team.ContentDigest(v.Policy.Manifest) |
| 183 | err := s.Journal.recordDirectLaunch(ctx, v, containment.Record{ID: c.Turn.ID, AttemptKey: v.AttemptKey, ManifestHash: "namespace", PolicyHash: v.Policy.Hash}) |
| 184 | return v, func() error { return nil }, err |
| 185 | } |
| 186 | return s, a, l, c |
| 187 | } |
| 188 | func TestCoordinatorSessionService(t *testing.T) { |
| 189 | s, a, l, c := coordinatorServiceFixture(t) |
| 190 | mustJournal(t, s.Poll(context.Background())) |
| 191 | if !a.delivery || l.starts != 1 { |
| 192 | t.Fatal("service did not deliver admitted turn", a.events) |
| 193 | } |
| 194 | var n int |
| 195 | mustJournal(t, s.Journal.db.QueryRow("SELECT count(*) FROM coordinator_tools").Scan(&n)) |
| 196 | if n != 0 { |
| 197 | t.Fatal("delivery ACK did not retire tool journal") |
| 198 | } |
| 199 | if err := s.RunTurn(context.Background(), c); !errors.Is(err, provider.ErrUncertain) { |
| 200 | t.Fatal("saved turn redispatched", err) |
| 201 | } |
| 202 | } |
| 203 | func TestCoordinatorSessionProductionWiring(t *testing.T) { |
| 204 | c := directRuntimeFixture(t) |
| 205 | r, err := openRuntime(context.Background(), c) |
| 206 | mustJournal(t, err) |
| 207 | defer r.Close() |
| 208 | mustJournal(t, r.wire(context.Background())) |
| 209 | if r.service.Coordinator == nil || r.service.Coordinator.Journal != r.journal || r.service.Coordinator.OpenLaunch == nil || len(r.service.Coordinator.Launchers) != 2 { |
| 210 | t.Fatal("production service omitted coordinator") |
| 211 | } |
| 212 | } |
| 213 | func TestCoordinatorCrashNeverRedispatches(t *testing.T) { |
| 214 | for _, phase := range []string{"before-intent", "intent", "stdin", "tool", "ack"} { |
| 215 | t.Run(phase, func(t *testing.T) { |
| 216 | s, a, l, c := coordinatorServiceFixture(t) |
| 217 | if phase == "ack" { |
| 218 | a.crash = phase |
| 219 | } else { |
| 220 | l.crash = phase |
| 221 | } |
| 222 | _ = s.RunTurn(context.Background(), c) |
| 223 | before := l.starts |
| 224 | path := s.Journal.path |
| 225 | mustJournal(t, s.Journal.Close()) |
| 226 | j, err := OpenJournal(context.Background(), path) |
| 227 | mustJournal(t, err) |
| 228 | defer j.Close() |
| 229 | s.Journal = j |
| 230 | l.j = j |
| 231 | // Finished cleanup is already contained; a runner restart must still refuse dispatch. |
| 232 | mustJournal(t, s.Recover(context.Background())) |
| 233 | if err = s.RunTurn(context.Background(), c); err == nil || l.starts != before { |
| 234 | t.Fatal("uncertain turn resent") |
| 235 | } |
| 236 | if phase != "ack" && a.delivery { |
| 237 | t.Fatal("partial turn reported delivered") |
| 238 | } |
| 239 | }) |
| 240 | } |
| 241 | } |
| 242 | func TestCoordinatorUsageOnce(t *testing.T) { |
| 243 | ctx := context.Background() |
| 244 | j, l, s, _ := directFixture(t, "codex") |
| 245 | path := j.path |
| 246 | for i := 0; i < 3; i++ { |
| 247 | if i > 0 { |
| 248 | mustJournal(t, j.Close()) |
| 249 | var err error |
| 250 | j, err = OpenJournal(ctx, path) |
| 251 | mustJournal(t, err) |
| 252 | defer j.Close() |
| 253 | l.AttemptKey = fmt.Sprint(i) |
| 254 | s.AttemptKey = l.AttemptKey |
| 255 | s.ID = fmt.Sprint(i) |
| 256 | mustJournal(t, j.recordDirectLaunch(ctx, l, containment.Record{ID: s.ID, AttemptKey: l.AttemptKey, ManifestHash: "manifest", PolicyHash: l.Policy.Hash})) |
| 257 | } |
| 258 | turn := directTurn() |
| 259 | turn.AdmissionID = fmt.Sprint(i) |
| 260 | mustJournal(t, j.BeginTurn(ctx, s, turn)) |
| 261 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, turn.Prompt)) |
| 262 | if i < 2 { |
| 263 | ev := codexUsage(turn.ID, 100, 20) |
| 264 | ev.SessionID = s.ID |
| 265 | _, err := j.ObserveDirect(ctx, s, ev) |
| 266 | mustJournal(t, err) |
| 267 | } |
| 268 | ev := directComplete(turn.ID) |
| 269 | ev.SessionID = s.ID |
| 270 | u, err := j.ObserveDirect(ctx, s, ev) |
| 271 | mustJournal(t, err) |
| 272 | again, err := j.ObserveDirect(ctx, s, ev) |
| 273 | mustJournal(t, err) |
| 274 | if i < 2 && (u == nil || u.InputTokens != 100 || again == nil || *u != *again) { |
| 275 | t.Fatal("usage reused another session baseline", u) |
| 276 | } |
| 277 | if i == 2 && (u != nil || again != nil) { |
| 278 | t.Fatal("missing usage became zero") |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | func TestCoordinatorContextDurableIntent(t *testing.T) { |
| 283 | j, l, s, _ := directFixture(t, "claude") |
| 284 | l.Policy.Manifest = json.RawMessage(`{"Action":"coordinate"}`) |
| 285 | l.Policy.ManifestHash = team.ContentDigest(l.Policy.Manifest) |
| 286 | _, err := j.db.Exec("UPDATE direct_attempts SET launch=? WHERE attempt=?", marshal(l), l.AttemptKey) |
| 287 | mustJournal(t, err) |
| 288 | for _, prompt := range []string{strings.Repeat("x", (48<<10)+1), strings.Repeat("\x00", 48<<10)} { |
| 289 | turn := directTurn() |
| 290 | turn.Prompt = prompt |
| 291 | if err = j.BeginTurn(context.Background(), s, turn); err == nil { |
| 292 | t.Fatal("durable intent bypassed prompt cap") |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | func TestCoordinatorContextDispatch(t *testing.T) { |
| 297 | j, l, s, _ := directFixture(t, "claude") |
| 298 | l.Policy.Manifest = json.RawMessage(`{"Action":"coordinate"}`) |
| 299 | l.Policy.ManifestHash = team.ContentDigest(l.Policy.Manifest) |
| 300 | _, err := j.db.Exec("UPDATE direct_attempts SET launch=? WHERE attempt=?", marshal(l), l.AttemptKey) |
| 301 | mustJournal(t, err) |
| 302 | prompt := strings.Repeat("x", (48<<10)+1) |
| 303 | _, err = j.db.Exec("INSERT INTO direct_turns(turn_key,attempt,session,turn,admission,prompt_hash,state) VALUES('key',?,?,'turn','admission',?,'intent')", s.AttemptKey, s.ID, runnerproto.EventHash(prompt)) |
| 304 | mustJournal(t, err) |
| 305 | if err = j.consumeTurn(context.Background(), s.AttemptKey, s.ID, prompt); err == nil { |
| 306 | t.Fatal("dispatch bypassed coordinator prompt cap") |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | func TestCoordinatorCrashRecordedBoundaries(t *testing.T) { |
| 311 | for _, phase := range []string{"claim", "intent", "stdin", "tool-commit", "frame", "completed-frame", "server-ack"} { |
| 312 | t.Run(phase, func(t *testing.T) { |
| 313 | ctx := context.Background() |
| 314 | s, a, l, c := coordinatorServiceFixture(t) |
| 315 | launch, _, err := s.OpenLaunch(ctx, c, nil) |
| 316 | mustJournal(t, err) |
| 317 | session := provider.Session{ID: "session", AttemptKey: launch.AttemptKey, Provider: "claude", Family: "claude", AccountID: "account", Model: "model"} |
| 318 | mustJournal(t, s.Journal.BindSession(ctx, session)) |
| 319 | r := coordinatorState{Claim: c, Session: session} |
| 320 | mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, r)) |
| 321 | if phase != "claim" { |
| 322 | turn := provider.Turn{ID: c.Turn.ID, AdmissionID: c.Turn.ID, Prompt: "hello"} |
| 323 | mustJournal(t, s.Journal.BeginTurn(ctx, session, turn)) |
| 324 | if phase != "intent" { |
| 325 | mustJournal(t, s.Journal.consumeTurn(ctx, session.AttemptKey, session.ID, turn.Prompt)) |
| 326 | } |
| 327 | } |
| 328 | if phase == "tool-commit" || phase == "frame" || phase == "completed-frame" || phase == "server-ack" { |
| 329 | call := runnerproto.CoordinatorToolCall{RequestID: "post", Name: "post_message", Arguments: json.RawMessage(`{"body":"answer","source_refs":[]}`)} |
| 330 | mustJournal(t, s.Journal.submitCoordinatorTool(ctx, c, session, call)) |
| 331 | // The instance committed, but no response reached the local tool journal. |
| 332 | } |
| 333 | if phase == "frame" { |
| 334 | mustJournal(t, s.Journal.AppendFrame(ctx, launch.AttemptKey, c.Turn.ID, 1, json.RawMessage(`{"type":"result","session_id":"session"}`))) |
| 335 | } |
| 336 | if phase == "completed-frame" || phase == "server-ack" { |
| 337 | pump := EventPump{Journal: s.Journal, Contain: func(context.Context) error { return nil }} |
| 338 | mustJournal(t, pump.AppendDirect(ctx, session, provider.Event{SessionID: session.ID, TurnID: c.Turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)}, s.template(r))) |
| 339 | } |
| 340 | if phase == "server-ack" { |
| 341 | mustJournal(t, s.reconcileTools(ctx, r)) |
| 342 | a.crash = "ack" |
| 343 | if err = s.finishDelivery(ctx, r); err == nil { |
| 344 | t.Fatal("lost server ACK not injected") |
| 345 | } |
| 346 | } |
| 347 | path := s.Journal.path |
| 348 | mustJournal(t, s.Journal.Close()) |
| 349 | j, err := OpenJournal(ctx, path) |
| 350 | mustJournal(t, err) |
| 351 | defer j.Close() |
| 352 | s.Journal = j |
| 353 | l.j = j |
| 354 | mustJournal(t, s.Recover(ctx)) |
| 355 | mustJournal(t, s.Recover(ctx)) |
| 356 | if l.starts != 0 { |
| 357 | t.Fatal("crash recovery redispatched prompt") |
| 358 | } |
| 359 | want := phase == "completed-frame" || phase == "server-ack" |
| 360 | if a.delivery != want { |
| 361 | t.Fatalf("recovery outcome %s: delivered %v", phase, a.delivery) |
| 362 | } |
| 363 | pending, err := j.Pending(ctx, 128) |
| 364 | mustJournal(t, err) |
| 365 | if len(pending) != 0 { |
| 366 | t.Fatal("coordinator events leaked to task uploader") |
| 367 | } |
| 368 | }) |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | func TestCoordinatorStopContains(t *testing.T) { |
| 373 | s, _, l, c := coordinatorServiceFixture(t) |
| 374 | l.crash = "stdin" |
| 375 | released := false |
| 376 | contained := false |
| 377 | open := s.OpenLaunch |
| 378 | s.OpenLaunch = func(ctx context.Context, c runnerproto.CoordinatorClaim, p *ToolProxy) (provider.Launch, func() error, error) { |
| 379 | v, _, err := open(ctx, c, p) |
| 380 | return v, func() error { |
| 381 | if !contained { |
| 382 | t.Error("account lease released before every namespace stopped") |
| 383 | } |
| 384 | released = true |
| 385 | return nil |
| 386 | }, err |
| 387 | } |
| 388 | contain := s.Contain |
| 389 | s.Contain = func(context.Context, runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
| 390 | return runnerproto.ContainmentProof{}, provider.ErrContainment |
| 391 | } |
| 392 | if err := s.RunTurn(context.Background(), c); err == nil || released { |
| 393 | t.Fatal("unknown namespace released account lease") |
| 394 | } |
| 395 | s.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
| 396 | contained = true |
| 397 | return contain(ctx, c) |
| 398 | } |
| 399 | mustJournal(t, s.Recover(context.Background())) |
| 400 | if !released { |
| 401 | t.Fatal("contained turn retained account lease") |
| 402 | } |
| 403 | if err := s.Journal.currentDirectTurn(context.Background(), l.session, c.Turn.ID); err == nil { |
| 404 | t.Fatal("late answer accepted after stop") |
| 405 | } |
| 406 | var usage []byte |
| 407 | mustJournal(t, s.Journal.db.QueryRow("SELECT usage FROM direct_turns WHERE turn=?", c.Turn.ID).Scan(&usage)) |
| 408 | if len(usage) != 0 { |
| 409 | t.Fatal("unknown usage became known on stop") |
| 410 | } |
| 411 | } |
| 412 | |