| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "reflect" |
| 11 | "testing" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | func admissionFixture(t *testing.T) (*env, Scope, Handle, ActionID) { |
| 16 | e := newEnv(t) |
| 17 | _, sc := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 18 | h := e.claim(sc, "reproduce", "runner-a", "ws-1") |
| 19 | id, err := e.store.Intend(e.ctx, sc, h, IntentSpec{Key: "turn", Operation: OpProviderCall, Payload: []byte(`{"task":"implement"}`), Reserve: Usage{InputTokens: 10, OutputTokens: 10}}) |
| 20 | must(t, err) |
| 21 | return e, sc, h, id |
| 22 | } |
| 23 | func TestAdmitLostReplyRetry(t *testing.T) { |
| 24 | e, sc, h, id := admissionFixture(t) |
| 25 | first, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request-1") |
| 26 | must(t, err) |
| 27 | before, _ := e.store.Reservations(e.ctx, sc) |
| 28 | e.clock.Advance(time.Second) |
| 29 | again, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request-1") |
| 30 | must(t, err) |
| 31 | after, _ := e.store.Reservations(e.ctx, sc) |
| 32 | if !reflect.DeepEqual(first, again) || !reflect.DeepEqual(before, after) { |
| 33 | t.Fatal("retry changed ticket or charge") |
| 34 | } |
| 35 | var n int |
| 36 | must(t, e.store.db.QueryRow(`SELECT count(*) FROM events WHERE type='action.dispatching'`).Scan(&n)) |
| 37 | if n != 1 { |
| 38 | t.Fatal("retry duplicated event") |
| 39 | } |
| 40 | if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "different"); err == nil { |
| 41 | t.Fatal("changed request accepted") |
| 42 | } |
| 43 | h.Fence++ |
| 44 | if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "request-1"); err == nil { |
| 45 | t.Fatal("changed handle accepted") |
| 46 | } |
| 47 | } |
| 48 | func TestDispatchAdmissionExpires(t *testing.T) { |
| 49 | e, sc, h, id := admissionFixture(t) |
| 50 | ticket, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request") |
| 51 | must(t, err) |
| 52 | if ticket.ExpiresAt.Sub(e.clock.Now()) != 5*time.Second { |
| 53 | t.Fatal("wrong ticket lifetime") |
| 54 | } |
| 55 | e.clock.Advance(5 * time.Second) |
| 56 | if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "request"); err == nil { |
| 57 | t.Fatal("expired ticket replayed") |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | func TestAdmitLostReplyRetryDenied(t *testing.T) { |
| 62 | for _, kind := range []string{"cancelled", "revoked", "grant", "budget", "incarnation", "payload", "authority", "reservation"} { |
| 63 | t.Run(kind, func(t *testing.T) { |
| 64 | e, sc, h, id := admissionFixture(t) |
| 65 | _, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request") |
| 66 | must(t, err) |
| 67 | switch kind { |
| 68 | case "cancelled": |
| 69 | _, err = e.store.Cancel(e.ctx, sc, "owner", "cancel") |
| 70 | must(t, err) |
| 71 | case "revoked": |
| 72 | e.auth.Revoke(grant) |
| 73 | case "grant": |
| 74 | e.auth.Amend(grant) |
| 75 | case "budget": |
| 76 | _, err = e.store.db.Exec(`UPDATE jobs SET policy=json_set(policy,'$.job.input_tokens',9,'$.per_call.input_tokens',9)`) |
| 77 | must(t, err) |
| 78 | case "incarnation": |
| 79 | _, err = e.store.db.Exec(`UPDATE admission_tickets SET incarnation=incarnation+1`) |
| 80 | must(t, err) |
| 81 | case "payload": |
| 82 | _, err = e.store.db.Exec(`UPDATE actions SET payload='{}' WHERE id=?`, id) |
| 83 | must(t, err) |
| 84 | case "authority": |
| 85 | e.auth.SetUnavailable(true) |
| 86 | case "reservation": |
| 87 | _, err = e.store.db.Exec(`UPDATE reservations SET state='settled'`) |
| 88 | must(t, err) |
| 89 | } |
| 90 | if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "request"); err == nil { |
| 91 | t.Fatal("unsafe replay accepted", kind) |
| 92 | } |
| 93 | }) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | func TestAdmitLostReplyRetryCrashHelper(t *testing.T) { |
| 98 | path := os.Getenv("EQUIPO_ADMIT_CRASH") |
| 99 | if path == "" { |
| 100 | return |
| 101 | } |
| 102 | clock := NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)) |
| 103 | auth := NewFakeAuthority(clock, 5*time.Second) |
| 104 | auth.Issue(grant, Grant{Account: acctA, Operations: map[Operation]bool{OpJobContinue: true, OpAttemptContinue: true, OpProviderCall: true}}) |
| 105 | s, err := Open(context.Background(), path, Options{Clock: clock, Authority: auth, Adapters: map[Operation]Adapter{OpProviderCall: NewFakeProvider("fake", "model", nil)}}) |
| 106 | must(t, err) |
| 107 | _, err = s.Resume(context.Background()) |
| 108 | must(t, err) |
| 109 | job, err := s.CreateJob(context.Background(), softwareSpec(SoftwareSteps(false))) |
| 110 | must(t, err) |
| 111 | sc := Scope{Account: job.Account, Job: job.ID} |
| 112 | h, err := s.Claim(context.Background(), sc, "reproduce", "runner", "workspace") |
| 113 | must(t, err) |
| 114 | id, err := s.Intend(context.Background(), sc, h, IntentSpec{Key: "turn", Operation: OpProviderCall, Payload: []byte(`{}`), Reserve: Usage{InputTokens: 10, OutputTokens: 10}}) |
| 115 | must(t, err) |
| 116 | s.commitHook = func(stage string) error { |
| 117 | if stage == os.Getenv("EQUIPO_ADMIT_STAGE") { |
| 118 | os.Exit(73) |
| 119 | } |
| 120 | return nil |
| 121 | } |
| 122 | _, err = s.AdmitOnce(context.Background(), sc, h, id, "durable-request") |
| 123 | t.Fatalf("did not crash: %v", err) |
| 124 | } |
| 125 | func TestAdmitLostReplyRetryCrash(t *testing.T) { |
| 126 | for _, stage := range []string{"before_commit", "after_commit"} { |
| 127 | t.Run(stage, func(t *testing.T) { |
| 128 | path := filepath.Join(t.TempDir(), "crash.db") |
| 129 | exe, err := os.Executable() |
| 130 | must(t, err) |
| 131 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 132 | defer cancel() |
| 133 | cmd := exec.CommandContext(ctx, exe, "-test.run=^TestAdmitLostReplyRetryCrashHelper$") |
| 134 | cmd.Env = append(os.Environ(), "EQUIPO_ADMIT_CRASH="+path, "EQUIPO_ADMIT_STAGE="+stage) |
| 135 | output, err := cmd.CombinedOutput() |
| 136 | if status, ok := err.(*exec.ExitError); !ok || status.ExitCode() != 73 { |
| 137 | t.Fatalf("crash not reached: %v %s", err, output) |
| 138 | } |
| 139 | raw, err := sql.Open("sqlite", path) |
| 140 | must(t, err) |
| 141 | defer raw.Close() |
| 142 | var n int |
| 143 | must(t, raw.QueryRow("SELECT count(*) FROM admission_tickets").Scan(&n)) |
| 144 | if stage == "before_commit" { |
| 145 | if n != 0 { |
| 146 | t.Fatal("ticket escaped rollback") |
| 147 | } |
| 148 | return |
| 149 | } |
| 150 | if n != 1 { |
| 151 | t.Fatal("committed ticket missing") |
| 152 | } |
| 153 | var dispatch, expiry, request, state string |
| 154 | var inc int64 |
| 155 | must(t, raw.QueryRow("SELECT dispatch,expires_at,request_id,incarnation FROM admission_tickets").Scan(&dispatch, &expiry, &request, &inc)) |
| 156 | var d Dispatch |
| 157 | must(t, json.Unmarshal([]byte(dispatch), &d)) |
| 158 | must(t, raw.QueryRow("SELECT state FROM actions").Scan(&state)) |
| 159 | if d.Action != 1 || request != "durable-request" || parseTS(expiry).IsZero() || inc == 0 || state != "dispatching" { |
| 160 | t.Fatal("partial admission commit") |
| 161 | } |
| 162 | must(t, raw.QueryRow("SELECT count(*) FROM events WHERE type='action.dispatching'").Scan(&n)) |
| 163 | if n != 1 { |
| 164 | t.Fatal("dispatch event missing") |
| 165 | } |
| 166 | clock := NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)) |
| 167 | auth := NewFakeAuthority(clock, 5*time.Second) |
| 168 | auth.Issue(grant, Grant{Account: acctA, Operations: map[Operation]bool{OpJobContinue: true, OpAttemptContinue: true, OpProviderCall: true}}) |
| 169 | s, err := Open(ctx, path, Options{Clock: clock, Authority: auth}) |
| 170 | must(t, err) |
| 171 | defer s.Close() |
| 172 | if _, err = s.AdmitOnce(ctx, Scope{Account: acctA, Job: 1}, Handle{Attempt: 1, Fence: 1, Runner: "runner"}, 1, "durable-request"); err == nil { |
| 173 | t.Fatal("crash replay dispatched in new incarnation") |
| 174 | } |
| 175 | var saved string |
| 176 | must(t, raw.QueryRow("SELECT dispatch FROM admission_tickets").Scan(&saved)) |
| 177 | if saved != dispatch { |
| 178 | t.Fatal("reopen changed stored ticket") |
| 179 | } |
| 180 | }) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestAdmitLostReplyRetryPublicationExposure(t *testing.T) { |
| 185 | g := newGitEnv(t) |
| 186 | g.build() |
| 187 | g.review() |
| 188 | g.verify(true) |
| 189 | h := g.claimStep("publish") |
| 190 | id, err := g.store.Intend(g.ctx, g.scope, h, IntentSpec{Key: "publish", Operation: OpForgePublish, Payload: mustJSON(g.publication())}) |
| 191 | must(t, err) |
| 192 | _, err = g.store.AdmitOnce(g.ctx, g.scope, h, id, "publication") |
| 193 | must(t, err) |
| 194 | g.observed.Isolation.AcknowledgementIDs = append(g.observed.Isolation.AcknowledgementIDs, "new-exposure") |
| 195 | if _, err = g.store.AdmitOnce(g.ctx, g.scope, h, id, "publication"); err == nil { |
| 196 | t.Fatal("publication ticket replay ignored new runner exposure") |
| 197 | } |
| 198 | } |
| 199 | |