oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "database/sql"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "net/http/httptest"
12 "os"
13 "path/filepath"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/runnerproto"
20 "gorm.io/gorm"
21
22 "amadan.net/oficina/equipo/internal/equipo"
23 "amadan.net/oficina/equipo/internal/equipo/team"
24)
25
26type runnerFixture struct {
27 connectionFixture
28 x *equipo.Execution
29 a equipo.Assignment
30 claim equipo.ClaimResponse
31}
32
33func runnerFixtureNew(t *testing.T, claim bool, supervised ...bool) runnerFixture {
34 t.Helper()
35 f := bugFixture(t)
36 task := bugTask(t, f)
37 task, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
38 executionMust(t, err)
39 var path string
40 executionMust(t, f.d.Writer().QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&path))
41 attach := f.s.AttachExecution
42 if len(supervised) > 0 && supervised[0] {
43 attach = f.s.AttachSupervisedExecution
44 }
45 x, err := attach(connectionContext, filepath.Clean(path), team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock), Provenance: func(ctx context.Context, tx *sql.Tx, _ team.Scope, h team.Handle) (team.Provenance, error) {
46 var raw string
47 if err := tx.QueryRowContext(ctx, "SELECT selection FROM runner_assignments WHERE attempt_id=?", h.Attempt).Scan(&raw); err != nil {
48 return team.Provenance{}, err
49 }
50 var sel equipo.Selection
51 if err := json.Unmarshal([]byte(raw), &sel); err != nil {
52 return team.Provenance{}, err
53 }
54 return team.Provenance{Provider: sel.Provider, ModelFamily: sel.Family, Producer: "observed", Context: fmt.Sprint(h.Attempt)}, nil
55 }, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("claude", "sonnet", nil)}})
56 executionMust(t, err)
57 t.Cleanup(func() { x.Core.Close() })
58 _, err = x.Core.Resume(connectionContext)
59 executionMust(t, err)
60 _, err = f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
61 executionMust(t, err)
62 executionMust(t, x.Sync(connectionContext))
63 aa, err := x.Poll(connectionContext, f.principal, "")
64 executionMust(t, err)
65 if len(aa) != 1 {
66 t.Fatalf("assignments %v", aa)
67 }
68 out := runnerFixture{connectionFixture: f, x: x, a: aa[0]}
69 if claim {
70 out.claim, err = x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: aa[0].ID, Revision: aa[0].Revision, RequestID: "claim"})
71 executionMust(t, err)
72 }
73 return out
74}
75func (f runnerFixture) request() equipo.RunnerRequest {
76 return equipo.RunnerRequest{Version: 2, AssignmentID: f.a.ID, Scope: f.claim.Scope, Handle: f.claim.Handle, RequestID: "request"}
77}
78func TestRunnerCannotClaimOthersWork(t *testing.T) {
79 f := runnerFixtureNew(t, false)
80 for _, field := range []string{"person", "runner", "credential"} {
81 t.Run(field, func(t *testing.T) {
82 p := f.principal
83 switch field {
84 case "person":
85 p.Person = "other@example.com"
86 case "runner":
87 p.RunnerID = "other"
88 case "credential":
89 p.CredentialID = "other"
90 }
91 if _, err := f.x.Claim(connectionContext, p, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
92 t.Fatal("foreign claim accepted")
93 }
94 })
95 }
96}
97func TestRunnerFenceEveryMutation(t *testing.T) {
98 f := runnerFixtureNew(t, true)
99 for _, op := range []string{"publication_ready", "publication_authorize", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
100 t.Run(op, func(t *testing.T) {
101 q := f.request()
102 q.Handle.Fence++
103 if _, err := f.x.Mutate(connectionContext, f.principal, op, q); err == nil {
104 t.Fatal("wrong fence accepted", op)
105 }
106 })
107 }
108}
109func TestRunnerLongPollRechecksRoster(t *testing.T) {
110 f := runnerFixtureNew(t, false)
111 ctx, cancel := context.WithTimeout(connectionContext, time.Second)
112 defer cancel()
113 done := make(chan error, 1)
114 go func() { _, err := f.x.Poll(ctx, f.principal, f.a.ID); done <- err }()
115 time.Sleep(30 * time.Millisecond)
116 executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
117 if err := <-done; err == nil {
118 t.Fatal("revoked poll succeeded")
119 }
120}
121func TestSpecialistConcurrency(t *testing.T) {
122 f := runnerFixtureNew(t, true)
123 var n int
124 executionMust(t, f.d.Writer().QueryRow(`SELECT count(*) FROM attempts WHERE containment='pending'`).Scan(&n))
125 if n != 1 {
126 t.Fatal("missing claim")
127 }
128 if _, err := f.s.SelectConnection(connectionContext, ownerAddress, f.project.ID, "engineering", ""); err == nil {
129 t.Fatal("specialist slot not occupied")
130 }
131 if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "other"}); err == nil {
132 t.Fatal("second handle issued")
133 }
134}
135func TestRevokedCleanupCannotRefund(t *testing.T) {
136 f := runnerFixtureNew(t, true)
137 f.x.SetRunnerValidators(equipo.RunnerValidators{Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
138 t.Fatal("cleanup reached trusted receipt validator")
139 return team.Receipt{}, nil
140 }})
141 q := f.request()
142 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"implement"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
143 result, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
144 executionMust(t, err)
145 id := result.(team.ActionID)
146 q.Intent = nil
147 q.ActionID = id
148 q.RequestID = "admit"
149 _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
150 executionMust(t, err)
151 executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
152 q.RequestID = "receipt"
153 q.Receipt = &team.Receipt{ID: "forged", Outcome: team.OutcomeSuccess, Usage: &team.Usage{}}
154 _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "receipts", q)
155 executionMust(t, err)
156 reservations, err := f.x.Core.Reservations(connectionContext, q.Scope)
157 executionMust(t, err)
158 if len(reservations) != 1 || reservations[0].State != team.ReservationOpen {
159 t.Fatal("cleanup refunded charge")
160 }
161 if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "intend", q); err == nil {
162 t.Fatal("cleanup admitted work")
163 }
164}
165func TestTaintedRunnerProvenance(t *testing.T) {
166 f := runnerFixtureNew(t, true)
167 if f.claim.Brief.Selection.Isolation.RunnerTainted {
168 t.Fatal("new certified work inherited an exception")
169 }
170 seedHistoricalTaskIsolation(t, f.connectionFixture, f.a.TaskID)
171 executionMust(t, f.x.Sync(connectionContext))
172 var raw string
173 executionMust(t, f.d.Writer().QueryRow(`SELECT isolation FROM runner_assignments WHERE id=?`, f.a.ID).Scan(&raw))
174 var iso team.IsolationSnapshot
175 executionMust(t, json.Unmarshal([]byte(raw), &iso))
176 if !iso.RunnerTainted {
177 t.Fatal("historical taint missing")
178 }
179}
180func TestDirectContainmentRotatesTokens(t *testing.T) {
181 f := runnerFixtureNew(t, true)
182 oldBearer := runnerBearerFor(t, f)
183 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
184 q := f.request()
185 q.RequestID = "stop"
186 _, err := f.x.Mutate(connectionContext, f.principal, "stop", q)
187 executionMust(t, err)
188 q.RequestID = "contained"
189 result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
190 executionMust(t, err)
191 rotation := result.(equipo.CredentialRotation)
192 if _, err := f.s.AuthenticateRunner(connectionContext, oldBearer); err == nil {
193 t.Fatal("old bearer survived containment")
194 }
195 if rotation.Bearer.Token == "" || len(rotation.CleanupTokens) != 1 {
196 t.Fatal("missing replacement credentials")
197 }
198 if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "receipts", q); err == nil {
199 t.Fatal("old cleanup token retained general cleanup authority")
200 }
201 if _, err = f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token); err != nil {
202 t.Fatal(err)
203 }
204 if _, err = f.x.Mutate(connectionContext, f.principal, "renew", q); err == nil {
205 t.Fatal("old bearer principal survived")
206 }
207}
208
209func runnerBearerFor(t *testing.T, f runnerFixture) string {
210 t.Helper()
211 token := strings.Repeat("A", 43)
212 // Test credentials are seeded by hash; no real machine is enrolled.
213 sum := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + token))
214 mustSQL(t, f.d, "UPDATE runner_credentials SET token_hash=? WHERE id=?", fmt.Sprintf("%x", sum), f.principal.CredentialID)
215 return token
216}
217func runnerHTTP(t *testing.T, f runnerFixture, op, token string, value any) int {
218 t.Helper()
219 raw, err := runnerproto.Marshal(value)
220 executionMust(t, err)
221 req := httptest.NewRequest("POST", "/"+op, bytes.NewReader(raw))
222 req.Header.Set("Authorization", "Bearer "+token)
223 req.Header.Set("Content-Type", "application/json")
224 w := httptest.NewRecorder()
225 f.s.RunnerHandler().ServeHTTP(w, req)
226 return w.Code
227}
228func TestRunnerFenceHTTPBindings(t *testing.T) {
229 f := runnerFixtureNew(t, true)
230 token := runnerBearerFor(t, f)
231 f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
232 for _, op := range []string{"publication_ready", "publication_authorize", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
233 for _, field := range []string{"scope", "job", "attempt", "runner", "fence", "assignment", "version"} {
234 t.Run(op+"/"+field, func(t *testing.T) {
235 q := f.request()
236 q.Event = fixtureEventRequest(t, f, q)
237 switch field {
238 case "scope":
239 q.Scope.Account = "other"
240 case "job":
241 q.Scope.Job++
242 case "attempt":
243 q.Handle.Attempt++
244 case "runner":
245 q.Handle.Runner = "other"
246 case "fence":
247 q.Handle.Fence++
248 case "assignment":
249 q.AssignmentID = "other"
250 case "version":
251 q.Version = 1
252 }
253 q.Event = fixtureEventRequest(t, f, q)
254 if status := runnerHTTP(t, f, op, token, q); status < 400 {
255 t.Fatal("HTTP binding accepted", status)
256 }
257 })
258 }
259 }
260 q := f.request()
261 q.Event = fixtureEventRequest(t, f, q)
262 if status := runnerHTTP(t, f, "events", token, q); status != 200 {
263 t.Fatal("valid event denied", status)
264 }
265 if status := runnerHTTP(t, f, "renew", token, q); status != 200 {
266 t.Fatal("valid renew denied", status)
267 }
268 raw, err := runnerproto.Marshal(q)
269 executionMust(t, err)
270 req := httptest.NewRequest("POST", "/events", bytes.NewReader(raw))
271 req.Header.Set("Authorization", "Bearer "+token)
272 req.Header.Set("Cookie", "session=browser")
273 req.Header.Set("Content-Type", "application/json")
274 response := httptest.NewRecorder()
275 f.s.RunnerHandler().ServeHTTP(response, req)
276 if response.Code != 403 {
277 t.Fatal("runner accepted browser cookie", response.Code)
278 }
279 for _, op := range []string{"connections", "heartbeat"} {
280 if status := runnerHTTP(t, f, op, token, runnerproto.HeartbeatRequest{Version: 2}); status < 400 {
281 t.Fatal("version accepted", op)
282 }
283 }
284}
285func TestRunnerClaimRetryAndRace(t *testing.T) {
286 f := runnerFixtureNew(t, false)
287 q := equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
288 var wg sync.WaitGroup
289 results := make(chan equipo.ClaimResponse, 2)
290 for i := 0; i < 2; i++ {
291 wg.Add(1)
292 go func() {
293 defer wg.Done()
294 r, err := f.x.Claim(connectionContext, f.principal, q)
295 if err == nil {
296 results <- r
297 }
298 }()
299 }
300 wg.Wait()
301 close(results)
302 var attempt team.AttemptID
303 for r := range results {
304 if attempt != 0 && attempt != r.Handle.Attempt {
305 t.Fatal("race issued two handles")
306 }
307 attempt = r.Handle.Attempt
308 }
309 if attempt == 0 || scalar(t, f.d, "SELECT count(*) FROM attempts") != 1 {
310 t.Fatal("claim race lost or duplicated attempt")
311 }
312 before := scalar(t, f.d, "SELECT count(*) FROM events")
313 r, err := f.x.Claim(connectionContext, f.principal, q)
314 executionMust(t, err)
315 if r.Handle.Attempt != attempt || scalar(t, f.d, "SELECT count(*) FROM events") != before {
316 t.Fatal("claim recovery added effects")
317 }
318}
319func TestIsolationAcknowledgementLapsesRunnerTickets(t *testing.T) {
320 for _, change := range []string{"removed", "provider", "launcher", "configuration"} {
321 t.Run(change, func(t *testing.T) {
322 f := runnerFixtureNew(t, true)
323 q := f.request()
324 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
325 id, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
326 executionMust(t, err)
327 q.Intent = nil
328 q.ActionID = id.(team.ActionID)
329 q.RequestID = "admit"
330 _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
331 executionMust(t, err)
332 switch change {
333 case "removed":
334 mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
335 case "demoted":
336 mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", ownerAddress)
337 default:
338 reports := append([]equipo.ConnectionReport(nil), f.reports...)
339 switch change {
340 case "provider":
341 reports[1].ProviderVersion = "next"
342 case "launcher":
343 reports[1].LauncherVersion = "next"
344 case "configuration":
345 reports[1].IsolationConfigHash = strings.Repeat("c", 64)
346 }
347 executionMust(t, f.s.ReportConnections(connectionContext, f.principal, reports))
348 }
349 if _, err = f.x.Mutate(connectionContext, f.principal, "admit", q); err == nil {
350 t.Fatal("stale admission accepted", change)
351 }
352 if _, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
353 t.Fatal("stale claim accepted", change)
354 }
355 })
356 }
357}
358func TestRunnerAuthorityDatabaseFailure(t *testing.T) {
359 f := runnerFixtureNew(t, false)
360 executionMust(t, f.d.G.Callback().Query().Before("gorm:query").Register("task8_failure", func(tx *gorm.DB) {
361 if tx.Statement.Table == "members" {
362 tx.AddError(errors.New("injected lookup error"))
363 }
364 }))
365 defer f.d.G.Callback().Query().Remove("task8_failure")
366 if out, err := f.x.Poll(connectionContext, f.principal, ""); err == nil || len(out) != 0 {
367 t.Fatal("database error became assignment")
368 }
369 if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
370 t.Fatal("database error became claim")
371 }
372}
373func TestDirectContainmentRotatesTokensFailure(t *testing.T) {
374 f := runnerFixtureNew(t, true)
375 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
376 q := f.request()
377 q.RequestID = "stop"
378 _, err := f.x.Mutate(connectionContext, f.principal, "stop", q)
379 executionMust(t, err)
380 q.RequestID = "contained"
381 executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("rotation_fail", func(tx *gorm.DB) {
382 if tx.Statement.Table == "runner_credentials" {
383 tx.AddError(errors.New("rotation unavailable"))
384 }
385 }))
386 if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
387 t.Fatal("rotation failure hidden")
388 }
389 executionMust(t, f.d.G.Callback().Create().Remove("rotation_fail"))
390 var state string
391 executionMust(t, f.d.Writer().QueryRow("SELECT state FROM runner_rotations WHERE runner_id=?", f.principal.RunnerID).Scan(&state))
392 if state != "containing" {
393 t.Fatal("failed rotation reopened admission", state)
394 }
395 if _, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
396 t.Fatal("failed rotation admitted claim")
397 }
398 result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
399 executionMust(t, err)
400 rotation := result.(equipo.CredentialRotation)
401 p, err := f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token)
402 executionMust(t, err)
403 executionMust(t, f.x.AcknowledgeRotation(connectionContext, p, q.RequestID))
404 before := scalar(t, f.d, "SELECT count(*) FROM runner_credentials")
405 _, err = f.x.Cleanup(connectionContext, rotation.CleanupTokens[f.a.ID], "contained", q)
406 executionMust(t, err)
407 if scalar(t, f.d, "SELECT count(*) FROM runner_credentials") != before {
408 t.Fatal("containment retry rotated twice")
409 }
410}
411
412func runnerSecond(t *testing.T, f runnerFixture) equipo.Assignment {
413 t.Helper()
414 task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "another bug", "request-2")
415 executionMust(t, err)
416 task, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f.connectionFixture))
417 executionMust(t, err)
418 _, err = f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
419 executionMust(t, err)
420 executionMust(t, f.x.Sync(connectionContext))
421 aa, err := f.x.Poll(connectionContext, f.principal, "")
422 executionMust(t, err)
423 for _, a := range aa {
424 if a.ID != f.a.ID {
425 return a
426 }
427 }
428 t.Fatal("second assignment missing")
429 return equipo.Assignment{}
430}
431func TestSpecialistConcurrencyAcrossJobs(t *testing.T) {
432 f := runnerFixtureNew(t, false)
433 second := runnerSecond(t, f)
434 var wg sync.WaitGroup
435 won := make(chan bool, 2)
436 for _, a := range []equipo.Assignment{f.a, second} {
437 wg.Add(1)
438 go func() {
439 defer wg.Done()
440 _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: a.ID, Revision: a.Revision, RequestID: "claim"})
441 won <- err == nil
442 }()
443 }
444 wg.Wait()
445 close(won)
446 n := 0
447 for ok := range won {
448 if ok {
449 n++
450 }
451 }
452 if n != 1 {
453 t.Fatal("specialist concurrency exceeded one", n)
454 }
455 if scalar(t, f.d, "SELECT count(*) FROM attempts WHERE containment='pending'") != 1 {
456 t.Fatal("two jobs claimed specialist")
457 }
458}
459func runnerConcurrent(t *testing.T) (runnerFixture, runnerFixture) {
460 t.Helper()
461 f := runnerFixtureNew(t, false)
462 second := runnerSecond(t, f)
463 // Seed two active assignments to exercise exposure and rotation across jobs.
464 mustSQL(t, f.d, "UPDATE specialists SET max_concurrent=2 WHERE key='engineering'")
465 var err error
466 f.claim, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"})
467 executionMust(t, err)
468 g := f
469 g.a = second
470 g.claim, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: second.ID, Revision: second.Revision, RequestID: "claim"})
471 executionMust(t, err)
472 return f, g
473}
474func TestTaintedRunnerProvenanceAlreadyRunning(t *testing.T) {
475 f, g := runnerConcurrent(t)
476 confined := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{connectionTuple(f.reports[0])}}
477 iso, _ := json.Marshal(confined)
478 mustSQL(t, f.d, "DELETE FROM isolation_acknowledgements")
479 mustSQL(t, f.d, "UPDATE runner_assignments SET isolation=?", string(iso))
480 f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
481 for _, fixture := range []runnerFixture{f, g} {
482 q := fixture.request()
483 q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro"), Provenance: team.Provenance{Isolation: confined}}
484 // Seed evidence, then restore a historical taint snapshot without granting authority.
485 art, err := f.x.Core.Register(connectionContext, q.Scope, q.Handle, *q.Artifact)
486 executionMust(t, err)
487 if art.Provenance.Isolation.RunnerTainted {
488 t.Fatal("seed was already tainted")
489 }
490 }
491 historical := team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"historical"}}
492 mustSQL(t, f.d, "UPDATE runner_assignments SET isolation=?", string(flowJSON(historical)))
493 rows, err := f.d.Writer().Query("SELECT id,provenance FROM artifacts")
494 executionMust(t, err)
495 type savedArtifact struct {
496 id int64
497 provenance team.Provenance
498 }
499 var savedArtifacts []savedArtifact
500 for rows.Next() {
501 var id int64
502 var raw []byte
503 executionMust(t, rows.Scan(&id, &raw))
504 var provenance team.Provenance
505 executionMust(t, json.Unmarshal(raw, &provenance))
506 provenance.Isolation = historical
507 savedArtifacts = append(savedArtifacts, savedArtifact{id, provenance})
508 }
509 executionMust(t, rows.Close())
510 for _, item := range savedArtifacts {
511 mustSQL(t, f.d, "UPDATE artifacts SET provenance=? WHERE id=?", string(flowJSON(item.provenance)), item.id)
512 }
513 for _, fixture := range []runnerFixture{f, g} {
514 artifacts, err := f.x.Core.Artifacts(connectionContext, fixture.claim.Scope)
515 executionMust(t, err)
516 if len(artifacts) != 1 || !artifacts[0].Provenance.Isolation.RunnerTainted {
517 t.Fatal("already registered evidence lost taint")
518 }
519 var saved string
520 executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", fixture.a.ID).Scan(&saved))
521 var snapshot team.IsolationSnapshot
522 executionMust(t, json.Unmarshal([]byte(saved), &snapshot))
523 if !snapshot.RunnerTainted {
524 t.Fatal("already running step lost taint")
525 }
526 q := fixture.request()
527 q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro"), Provenance: team.Provenance{Isolation: confined}}
528 value, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q)
529 executionMust(t, err)
530 if !value.(team.Artifact).Provenance.Isolation.RunnerTainted {
531 t.Fatal("submitted confined provenance won")
532 }
533 }
534 executionMust(t, setDirectAvailable(f.s, f.principal, f.reports, false))
535 artifacts, err := f.x.Core.Artifacts(connectionContext, f.claim.Scope)
536 executionMust(t, err)
537 if !artifacts[0].Provenance.Isolation.RunnerTainted {
538 t.Fatal("ack expiry erased historical exposure")
539 }
540}
541func TestDirectContainmentRotatesTokensConcurrent(t *testing.T) {
542 for _, revoked := range []bool{false, true} {
543 t.Run(fmt.Sprint(revoked), func(t *testing.T) {
544 f, g := runnerConcurrent(t)
545 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
546 if revoked {
547 executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
548 }
549 q := f.request()
550 q.RequestID = "contained"
551 result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
552 executionMust(t, err)
553 rotation := result.(equipo.CredentialRotation)
554 if len(rotation.CleanupTokens) != 2 {
555 t.Fatal("concurrent cleanup token not replaced")
556 }
557 if revoked && rotation.Bearer.Token != "" {
558 t.Fatal("revoked runner revived")
559 }
560 if _, err = f.x.Cleanup(connectionContext, g.claim.CleanupToken, "contained", g.request()); err == nil {
561 t.Fatal("concurrent old cleanup survived")
562 }
563 if !revoked {
564 principal, err := f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token)
565 executionMust(t, err)
566 active := g.request()
567 active.Intent = &team.IntentSpec{Key: "after-rotation", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
568 if _, err := f.x.Mutate(connectionContext, principal, "intend", active); err == nil {
569 t.Fatal("rotation admitted before durable acknowledgement")
570 }
571 executionMust(t, f.x.AcknowledgeRotation(connectionContext, principal, q.RequestID))
572 _, err = f.x.Mutate(connectionContext, principal, "intend", active)
573 executionMust(t, err)
574 }
575 q2 := g.request()
576 q2.RequestID = "second-contained"
577 result, err = f.x.Cleanup(connectionContext, rotation.CleanupTokens[g.a.ID], "contained", q2)
578 executionMust(t, err)
579 next := result.(equipo.CredentialRotation)
580 if revoked && next.Bearer.Token != "" {
581 t.Fatal("second containment revived runner")
582 }
583 before := scalar(t, f.d, "SELECT count(*) FROM runner_credentials")
584 q2.RequestID = "different-retry"
585 _, err = f.x.Cleanup(connectionContext, next.CleanupTokens[g.a.ID], "contained", q2)
586 executionMust(t, err)
587 if scalar(t, f.d, "SELECT count(*) FROM runner_credentials") != before {
588 t.Fatal("same attempt rotated twice")
589 }
590 if scalar(t, f.d, "SELECT count(*) FROM time_reservations WHERE state='settled' AND elapsed_unknown=1 AND settled_seconds=reserved_seconds") != 2 {
591 t.Fatal("containment refunded time")
592 }
593 })
594 }
595}
596
597func TestRunnerEndpointSuccess(t *testing.T) {
598 for _, op := range []string{"artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
599 t.Run(op, func(t *testing.T) {
600 f := runnerFixtureNew(t, true)
601 token := runnerBearerFor(t, f)
602 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
603 q := f.request()
604 switch op {
605 case "artifacts":
606 q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro")}
607 case "intend":
608 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
609 case "admit", "receipts", "lost":
610 in := q
611 in.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
612 id, err := f.x.Mutate(connectionContext, f.principal, "intend", in)
613 executionMust(t, err)
614 q.ActionID = id.(team.ActionID)
615 if op != "admit" {
616 _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
617 executionMust(t, err)
618 q.RequestID = "report"
619 q.Receipt = &team.Receipt{ID: "observation", Outcome: team.OutcomeSuccess}
620 }
621 case "complete":
622 q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure}
623 case "release":
624 q.Reason = team.WaitRunnerUnavailable
625 }
626 if status := runnerHTTP(t, f, op, token, q); status != 200 {
627 t.Fatal("valid endpoint refused", status)
628 }
629 })
630 }
631}
632func TestRunnerWireAndJournal(t *testing.T) {
633 q := equipo.RunnerRequest{Version: 2, AssignmentID: "assignment", RequestID: "request", Scope: team.Scope{Account: "account", Job: 1}, Handle: team.Handle{Attempt: 2, Fence: 3, Runner: "runner"}, Intent: &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1}}}
634 raw, err := runnerproto.Marshal(q)
635 executionMust(t, err)
636 if bytes.Contains(raw, []byte("InputTokens")) || !bytes.Contains(raw, []byte("input_tokens")) {
637 t.Fatal("wire is not snake case")
638 }
639 var round equipo.RunnerRequest
640 executionMust(t, runnerproto.DecodeLimit(bytes.NewReader(raw), &round, 65536))
641 if round.Intent.Reserve.InputTokens != 1 {
642 t.Fatal("wire lost reservation")
643 }
644 for _, bad := range []string{`{"version":1,"version":1}`, `{"Version":1}`, `{"version":2,"unknown":true}`} {
645 if runnerproto.DecodeLimit(strings.NewReader(bad), &round, 65536) == nil {
646 t.Fatal("invalid JSON accepted", bad)
647 }
648 }
649 now := time.Now().UTC()
650 ticket := team.AdmissionTicket{Scope: q.Scope, Handle: q.Handle, Dispatch: team.Dispatch{Action: 1}, Incarnation: 3, ExpiresAt: now.Add(5 * time.Second)}
651 dir := t.TempDir()
652 q.Intent = nil
653 q.ActionID = 1
654 executionMust(t, runnerproto.JournalAdmission(dir, q))
655 executionMust(t, runnerproto.JournalAdmission(dir, q))
656 changed := q
657 changed.Handle.Fence++
658 if runnerproto.JournalAdmission(dir, changed) == nil {
659 t.Fatal("journal accepted changed request binding")
660 }
661 executionMust(t, runnerproto.ConsumeTicket(dir, "request", ticket, now, 3))
662 q.RequestID = "different"
663 executionMust(t, runnerproto.JournalAdmission(dir, q))
664 if runnerproto.ConsumeTicket(dir, "different", ticket, now, 3) == nil {
665 t.Fatal("same ticket consumed twice")
666 }
667 ticket.Dispatch.Action = 2
668 q.ActionID = 2
669 q.RequestID = "late"
670 executionMust(t, runnerproto.JournalAdmission(dir, q))
671 if runnerproto.ConsumeTicket(dir, "late", ticket, now.Add(5*time.Second), 3) == nil {
672 t.Fatal("stale ticket consumed")
673 }
674 q.RequestID = "other"
675 executionMust(t, runnerproto.JournalAdmission(dir, q))
676 if runnerproto.ConsumeTicket(dir, "other", ticket, now, 4) == nil {
677 t.Fatal("wrong incarnation consumed")
678 }
679 path := filepath.Join(dir, "credentials.json")
680 executionMust(t, runnerproto.JournalCredentials(path, map[string]string{"bearer": "replacement"}))
681 info, err := os.Stat(path)
682 executionMust(t, err)
683 if info.Mode().Perm() != 0600 {
684 t.Fatal("journal permissions")
685 }
686}
687
688func TestRunnerPrepareOutbox(t *testing.T) {
689 f := bugFixture(t)
690 task := bugTask(t, f)
691 var path string
692 executionMust(t, f.d.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path))
693 x, err := f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)})
694 executionMust(t, err)
695 t.Cleanup(func() { x.Core.Close() })
696 _, err = x.Core.Resume(connectionContext)
697 executionMust(t, err)
698 executionMust(t, x.Sync(connectionContext))
699 aa, err := x.Poll(connectionContext, f.principal, "")
700 executionMust(t, err)
701 if len(aa) != 1 || aa[0].Kind != "prepare" {
702 t.Fatal("preparation assignment missing")
703 }
704 claim, err := x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: aa[0].ID, Revision: aa[0].Revision, RequestID: "claim"})
705 executionMust(t, err)
706 rf := runnerFixture{connectionFixture: f, x: x, a: aa[0], claim: claim}
707 token := runnerBearerFor(t, rf)
708 x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Prepare: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (equipo.PreparedBug, error) {
709 return bugPrepared(f), nil
710 }})
711 if status := runnerHTTP(t, rf, "prepare", token, rf.request()); status != 200 {
712 t.Fatal("prepare HTTP failed", status)
713 }
714 executionMust(t, x.Sync(connectionContext))
715 if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 {
716 t.Fatal("prepared outbox linked before containment")
717 }
718 q := rf.request()
719 q.RequestID = "contained"
720 _, err = x.Cleanup(connectionContext, claim.CleanupToken, "contained", q)
721 executionMust(t, err)
722 executionMust(t, x.Sync(connectionContext))
723 task, err = f.s.Task(connectionContext, ownerActor, task.ID)
724 executionMust(t, err)
725 if task.JobID == 0 || task.State != "queued" {
726 t.Fatal("prepared outbox not linked")
727 }
728 executionMust(t, x.Sync(connectionContext))
729 if scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 {
730 t.Fatal("preparation retry duplicated job")
731 }
732}
733func TestRunnerBoundsAndArtifactScope(t *testing.T) {
734 f := runnerFixtureNew(t, true)
735 f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
736 q := f.request()
737 q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro")}
738 value, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q)
739 executionMust(t, err)
740 art := value.(team.Artifact)
741 token := runnerBearerFor(t, f)
742 url := fmt.Sprintf("/artifacts/%s/%d?version=1&request_id=read&account=%s&job=%d&attempt=%d&fence=%d", f.a.ID, art.ID, q.Scope.Account, q.Scope.Job, q.Handle.Attempt, q.Handle.Fence)
743 for _, bad := range []bool{false, true} {
744 u := url
745 if bad {
746 u = strings.Replace(u, "account="+string(q.Scope.Account), "account=other", 1)
747 }
748 r := httptest.NewRequest("GET", u, nil)
749 r.Header.Set("Authorization", "Bearer "+token)
750 w := httptest.NewRecorder()
751 f.s.RunnerHandler().ServeHTTP(w, r)
752 if (!bad && w.Code != 200) || (bad && w.Code < 400) {
753 t.Fatal("artifact scope", bad, w.Code)
754 }
755 }
756 for _, op := range []string{"events", "artifacts", "intend"} {
757 t.Run(op, func(t *testing.T) {
758 q := f.request()
759 switch op {
760 case "events":
761 q.Event = json.RawMessage(`{"text":"` + strings.Repeat("a", runnerproto.MaxEventBytes) + `"}`)
762 case "artifacts":
763 q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: bytes.Repeat([]byte("a"), runnerproto.MaxArtifactBytes+1)}
764 case "intend":
765 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{"text":"` + strings.Repeat("a", runnerproto.MaxActionBytes) + `"}`)}
766 }
767 if _, err := f.x.Mutate(connectionContext, f.principal, op, q); err == nil {
768 t.Fatal("oversized payload accepted")
769 }
770 })
771 }
772}
773func TestRunnerClaimAtomicRollback(t *testing.T) {
774 f := runnerFixtureNew(t, false)
775 executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("claim_fail", func(tx *gorm.DB) {
776 if tx.Statement.Table == "audit_events" {
777 if event, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && event.Kind == "runner.claim" {
778 tx.AddError(errors.New("claim audit unavailable"))
779 }
780 }
781 }))
782 q := equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
783 if response, err := f.x.Claim(connectionContext, f.principal, q); err == nil || response.CleanupToken != "" {
784 t.Fatal("failed claim returned authority")
785 }
786 executionMust(t, f.d.G.Callback().Create().Remove("claim_fail"))
787 if scalar(t, f.d, "SELECT count(*) FROM attempts") != 0 || scalar(t, f.d, "SELECT count(*) FROM runner_cleanups") != 0 {
788 t.Fatal("claim partially committed")
789 }
790 _, err := f.x.Claim(connectionContext, f.principal, q)
791 executionMust(t, err)
792}
793
794func TestRunnerSelectionGuards(t *testing.T) {
795 for _, kind := range []string{"connection_revision", "connection_person", "connection_runner", "account", "stale", "specialist", "choice", "paused"} {
796 t.Run(kind, func(t *testing.T) {
797 f := runnerFixtureNew(t, false)
798 switch kind {
799 case "connection_revision":
800 mustSQL(t, f.d, "UPDATE connections SET revision=revision+1 WHERE id=?", f.a.Selection.ConnectionID)
801 case "connection_person":
802 mustSQL(t, f.d, "UPDATE connections SET person='other@example.com' WHERE id=?", f.a.Selection.ConnectionID)
803 case "connection_runner":
804 code, key := beginDevice(t, f.s)
805 approveDevice(t, f.s, code, ownerAddress)
806 credential := claimDevice(t, f.s, code, key)
807 mustSQL(t, f.d, "UPDATE connections SET runner_id=? WHERE id=?", credential.RunnerID, f.a.Selection.ConnectionID)
808 case "account":
809 sel := f.a.Selection
810 sel.AccountID = "other"
811 raw, _ := json.Marshal(sel)
812 mustSQL(t, f.d, "UPDATE runner_assignments SET selection=? WHERE id=?", string(raw), f.a.ID)
813 case "stale":
814 f.clock.Advance(90 * time.Second)
815 case "specialist":
816 mustSQL(t, f.d, "UPDATE specialists SET revision=revision+1 WHERE key='engineering'")
817 case "choice":
818 mustSQL(t, f.d, "UPDATE connection_choices SET connection_ids_json='[]'")
819 case "paused":
820 executionMust(t, f.x.Write(connectionContext, func(tx *gorm.DB) error { return tx.Exec("UPDATE service SET admission_paused=1").Error }))
821 }
822 if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
823 t.Fatal("claim guard bypassed", kind)
824 }
825 })
826 }
827}
828func TestRevokedCleanupBindingGuards(t *testing.T) {
829 for _, field := range []string{"audience", "expiry", "instance", "machine", "person", "attempt", "fence"} {
830 t.Run(field, func(t *testing.T) {
831 f := runnerFixtureNew(t, true)
832 q := f.request()
833 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`)}
834 id, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
835 executionMust(t, err)
836 q.Intent = nil
837 q.ActionID = id.(team.ActionID)
838 q.Receipt = &team.Receipt{ID: "observation", Outcome: team.OutcomeSuccess}
839 switch field {
840 case "audience":
841 mustSQL(t, f.d, "UPDATE runner_cleanups SET audience='other'")
842 case "expiry":
843 mustSQL(t, f.d, "UPDATE runner_cleanups SET expires_at=?", f.clock.Now().Add(-time.Second))
844 case "instance":
845 mustSQL(t, f.d, "UPDATE runner_cleanups SET instance_id='other'")
846 case "machine":
847 mustSQL(t, f.d, "UPDATE runner_cleanups SET machine_key_hash='other'")
848 case "person":
849 mustSQL(t, f.d, "UPDATE runner_cleanups SET person='other'")
850 case "attempt":
851 mustSQL(t, f.d, "UPDATE runner_cleanups SET attempt_id=attempt_id+1")
852 case "fence":
853 mustSQL(t, f.d, "UPDATE runner_cleanups SET fence=fence+1")
854 }
855 if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "receipts", q); err == nil {
856 t.Fatal("cleanup binding bypassed", field)
857 }
858 })
859 }
860}
861
862func TestDirectContainmentProofRequired(t *testing.T) {
863 f := runnerFixtureNew(t, true)
864 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return equipo.ErrForbidden }})
865 q := f.request()
866 if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
867 t.Fatal("unverified containment accepted")
868 }
869 if scalar(t, f.d, "SELECT count(*) FROM attempts WHERE containment='contained'") != 0 {
870 t.Fatal("invalid proof freed capacity")
871 }
872}
873
874func TestSpecialistConcurrencyReview(t *testing.T) {
875 f := runnerFixtureNew(t, true)
876 mustSQL(t, f.d, "UPDATE steps SET capability='verify' WHERE id=(SELECT step_id FROM attempts WHERE id=?)", f.claim.Handle.Attempt)
877 if _, err := f.s.SelectConnection(connectionContext, ownerAddress, f.project.ID, "review", "claude"); err == nil {
878 t.Fatal("verification did not occupy review specialist")
879 }
880}
881
882func TestRunnerAssignmentRetryPreservesCleanup(t *testing.T) {
883 f := runnerFixtureNew(t, true)
884 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
885 q := f.request()
886 q.Intent = &team.IntentSpec{Key: "old-turn", Operation: team.OpProviderCall, Payload: []byte(`{}`)}
887 id, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
888 executionMust(t, err)
889 q.Intent = nil
890 q.ActionID = id.(team.ActionID)
891 q.RequestID = "release"
892 q.Reason = team.WaitRunnerUnavailable
893 _, err = f.x.Mutate(connectionContext, f.principal, "release", q)
894 executionMust(t, err)
895 q.RequestID = "contained"
896 result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
897 executionMust(t, err)
898 rotation := result.(equipo.CredentialRotation)
899 principal, err := f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token)
900 executionMust(t, err)
901 executionMust(t, f.x.AcknowledgeRotation(connectionContext, principal, q.RequestID))
902 executionMust(t, f.x.Sync(connectionContext))
903 ctx, cancel := context.WithTimeout(connectionContext, 100*time.Millisecond)
904 defer cancel()
905 aa, err := f.x.Poll(ctx, principal, f.a.ID)
906 if err != nil || len(aa) != 1 {
907 t.Fatal("contained retry assignment missing", err)
908 }
909 if aa[0].ID == f.a.ID || aa[0].Revision <= f.a.Revision {
910 t.Fatal("retry reused assignment binding")
911 }
912 _, err = f.x.Claim(connectionContext, principal, equipo.ClaimRequest{Version: 2, AssignmentID: aa[0].ID, Revision: aa[0].Revision, RequestID: "new-claim"})
913 executionMust(t, err)
914 q.RequestID = "late"
915 q.Receipt = &team.Receipt{ID: "old-observation", Outcome: team.OutcomeSuccess}
916 _, err = f.x.Cleanup(connectionContext, rotation.CleanupTokens[f.a.ID], "receipts", q)
917 executionMust(t, err)
918}
919func TestRunnerClaimRevision(t *testing.T) {
920 f := runnerFixtureNew(t, false)
921 if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 2, AssignmentID: f.a.ID, Revision: f.a.Revision + 1, RequestID: "claim"}); err == nil {
922 t.Fatal("stale assignment revision claimed")
923 }
924 if scalar(t, f.d, "SELECT count(*) FROM attempts") != 0 {
925 t.Fatal("stale claim created attempt")
926 }
927}
928func TestRunnerHeartbeatAndValidatedReceipt(t *testing.T) {
929 f := runnerFixtureNew(t, true)
930 token := runnerBearerFor(t, f)
931 reports, err := runnerproto.Marshal(f.reports)
932 executionMust(t, err)
933 for _, op := range []string{"heartbeat", "connections"} {
934 if status := runnerHTTP(t, f, op, token, runnerproto.HeartbeatRequest{Version: 2, RequestID: op, Reports: reports}); status != 200 {
935 t.Fatal("valid machine report denied", op, status)
936 }
937 }
938 q := f.request()
939 q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`)}
940 result, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
941 executionMust(t, err)
942 q.Intent = nil
943 q.ActionID = result.(team.ActionID)
944 q.RequestID = "admit"
945 _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
946 executionMust(t, err)
947 f.x.SetRunnerValidators(equipo.RunnerValidators{Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
948 return team.Receipt{ID: "verified", Outcome: team.OutcomeSuccess}, nil
949 }})
950 q.RequestID = "receipt"
951 q.Receipt = &team.Receipt{ID: "reported", Outcome: team.OutcomeSuccess}
952 if status := runnerHTTP(t, f, "receipts", token, q); status != 200 {
953 t.Fatal("validated receipt refused", status)
954 }
955 action, err := f.x.Core.GetAction(connectionContext, q.Scope, q.ActionID)
956 executionMust(t, err)
957 if action.Receipt == nil || action.Receipt.ID != "verified" {
958 t.Fatal("reported receipt bypassed validator")
959 }
960}
961
962func TestRevokedCleanupContainmentPreservesIntentCharge(t *testing.T) {
963 f := runnerFixtureNew(t, true)
964 f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
965 q := f.request()
966 q.Intent = &team.IntentSpec{Key: "reserved", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
967 _, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
968 executionMust(t, err)
969 q.Intent = nil
970 q.RequestID = "contained"
971 _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
972 executionMust(t, err)
973 reservations, err := f.x.Core.Reservations(connectionContext, q.Scope)
974 executionMust(t, err)
975 if len(reservations) != 1 || reservations[0].State != team.ReservationOpen {
976 t.Fatal("cleanup containment refunded an intent reservation")
977 }
978}
979