| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "sync" |
| 9 | "sync/atomic" |
| 10 | "testing" |
| 11 | ) |
| 12 | |
| 13 | func TestAccountQuotesCannotBeChangedByJobs(t *testing.T) { |
| 14 | e := newEnv(t) |
| 15 | parent, _ := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 16 | for _, child := range []bool{false, true} { |
| 17 | for _, change := range []func(*Policy){ |
| 18 | func(p *Policy) { p.Rates = Rates{Version: 1} }, |
| 19 | func(p *Policy) { p.PerCall.InputTokens++ }, |
| 20 | } { |
| 21 | spec := softwareSpec(SoftwareSteps(false)) |
| 22 | if child { |
| 23 | spec.Parent = parent.ID |
| 24 | } |
| 25 | change(&spec.Policy) |
| 26 | _, err := e.store.CreateJob(e.ctx, spec) |
| 27 | wantCode(t, err, CodeConflict) |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | type controlledAdapter struct { |
| 33 | class ReplayClass |
| 34 | execute func(context.Context, Dispatch) (Receipt, error) |
| 35 | reconciles atomic.Int64 |
| 36 | } |
| 37 | |
| 38 | func (a *controlledAdapter) Classify(Operation) (ReplayClass, error) { return a.class, nil } |
| 39 | func (a *controlledAdapter) Execute(ctx context.Context, d Dispatch) (Receipt, error) { |
| 40 | return a.execute(ctx, d) |
| 41 | } |
| 42 | func (a *controlledAdapter) Reconcile(context.Context, Dispatch) (ReconcileResult, error) { |
| 43 | a.reconciles.Add(1) |
| 44 | return ReconcileResult{Definitive: true}, nil |
| 45 | } |
| 46 | |
| 47 | func TestEveryReplayClassRetainsUnknownUsage(t *testing.T) { |
| 48 | for _, class := range []ReplayClass{ReplayReadOnly, ReplayIdempotent, ReplayReconcilable, ReplayUnsafe} { |
| 49 | t.Run(string(class), func(t *testing.T) { |
| 50 | e := newEnv(t) |
| 51 | ad := &controlledAdapter{class: class, execute: func(context.Context, Dispatch) (Receipt, error) { |
| 52 | return Receipt{}, errors.New("lost reply") |
| 53 | }} |
| 54 | e.store.adapters[OpProviderCall] = ad |
| 55 | _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 56 | h := e.claim(scope, "reproduce", "r", "ws") |
| 57 | id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| 58 | must(t, err) |
| 59 | _, err = e.store.Dispatch(e.ctx, scope, id) |
| 60 | wantCode(t, err, CodeUncertain) |
| 61 | _, err = e.store.Reconcile(e.ctx, scope, id) |
| 62 | wantCode(t, err, CodeUncertain) |
| 63 | _, err = e.store.Dispatch(e.ctx, scope, id) |
| 64 | wantCode(t, err, CodeState) |
| 65 | _, err = e.store.Cancel(e.ctx, scope, "operator", "stop") |
| 66 | must(t, err) |
| 67 | rows, err := e.store.Reservations(e.ctx, scope) |
| 68 | must(t, err) |
| 69 | if len(rows) != 1 || rows[0].State != ReservationSettled || rows[0].Settled != rows[0].Reserved { |
| 70 | t.Fatalf("unknown usage released: %+v", rows) |
| 71 | } |
| 72 | }) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | func TestLiveDispatchCannotBeReconciledOrResumed(t *testing.T) { |
| 77 | e := newEnv(t) |
| 78 | entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) |
| 79 | var releaseOnce sync.Once |
| 80 | finish := func() { releaseOnce.Do(func() { close(release) }) } |
| 81 | var dispatchErr error |
| 82 | ad := &controlledAdapter{class: ReplayReconcilable, execute: func(context.Context, Dispatch) (Receipt, error) { |
| 83 | close(entered) |
| 84 | <-release |
| 85 | return Receipt{ID: "one-effect", Outcome: OutcomeSuccess, Usage: &Usage{Calls: 1, InputTokens: 1, CostMicros: 1003}}, nil |
| 86 | }} |
| 87 | e.store.adapters[OpProviderCall] = ad |
| 88 | _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 89 | h := e.claim(scope, "reproduce", "r", "ws") |
| 90 | id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| 91 | must(t, err) |
| 92 | go func() { _, dispatchErr = e.store.Dispatch(e.ctx, scope, id); close(done) }() |
| 93 | t.Cleanup(func() { finish(); <-done }) |
| 94 | <-entered |
| 95 | _, err = e.store.Reconcile(e.ctx, scope, id) |
| 96 | wantCode(t, err, CodeState) |
| 97 | _, err = e.store.Resume(e.ctx) |
| 98 | wantCode(t, err, CodeState) |
| 99 | if ad.reconciles.Load() != 0 { |
| 100 | t.Fatal("queried a potentially live operation") |
| 101 | } |
| 102 | finish() |
| 103 | <-done |
| 104 | must(t, dispatchErr) |
| 105 | } |
| 106 | |
| 107 | func TestCancelledCallerStillRecordsLostOutcome(t *testing.T) { |
| 108 | e := newEnv(t) |
| 109 | ctx, cancel := context.WithCancel(e.ctx) |
| 110 | defer cancel() |
| 111 | e.store.adapters[OpProviderCall] = &controlledAdapter{class: ReplayUnsafe, execute: func(context.Context, Dispatch) (Receipt, error) { |
| 112 | cancel() |
| 113 | return Receipt{}, context.Canceled |
| 114 | }} |
| 115 | _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 116 | h := e.claim(scope, "reproduce", "r", "ws") |
| 117 | id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| 118 | must(t, err) |
| 119 | _, err = e.store.Dispatch(ctx, scope, id) |
| 120 | wantCode(t, err, CodeUncertain) |
| 121 | a, err := e.store.GetAction(e.ctx, scope, id) |
| 122 | must(t, err) |
| 123 | if a.State != ActionUncertain { |
| 124 | t.Fatalf("action remained %s", a.State) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func TestAuditedUnknownUsageDoesNotQuarantineOtherJobs(t *testing.T) { |
| 129 | e := newEnv(t) |
| 130 | _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 131 | h := e.claim(scope, "reproduce", "r", "ws") |
| 132 | id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| 133 | must(t, err) |
| 134 | _, err = e.store.Admit(e.ctx, scope, id) |
| 135 | must(t, err) |
| 136 | must(t, e.store.Lost(e.ctx, scope, id, "lost reply")) |
| 137 | e.crash() |
| 138 | e.openNoResume() |
| 139 | rr, err := e.store.Resume(e.ctx) |
| 140 | must(t, err) |
| 141 | if !rr.Quarantine || rr.Resumed { |
| 142 | t.Fatalf("unexpected recovery: %+v", rr) |
| 143 | } |
| 144 | rows, err := e.store.Reservations(e.ctx, scope) |
| 145 | must(t, err) |
| 146 | _, err = e.store.SettleAudited(e.ctx, scope, rows[0].ID, "operator", "charge the full reservation; outcome remains unknown") |
| 147 | must(t, err) |
| 148 | rr, err = e.store.Resume(e.ctx) |
| 149 | must(t, err) |
| 150 | if !rr.Resumed { |
| 151 | t.Fatalf("audit did not release unrelated work: %+v", rr) |
| 152 | } |
| 153 | a, _ := e.store.GetAction(e.ctx, scope, id) |
| 154 | if a.State != ActionUncertain { |
| 155 | t.Fatal("audit fabricated a successful result") |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | func TestUncontainedAttemptsKeepTheirConcurrencySlot(t *testing.T) { |
| 160 | for _, expired := range []bool{false, true} { |
| 161 | t.Run(itoa(map[bool]int{false: 0, true: 1}[expired]), func(t *testing.T) { |
| 162 | e := newEnv(t) |
| 163 | spec := softwareSpec([]StepSpec{{Key: "one", Capability: CapReproduce, Version: 1}, {Key: "two", Capability: CapReproduce, Version: 1}}) |
| 164 | spec.Policy.MaxConcurrentAttempts = 1 |
| 165 | _, scope := e.createJob(spec) |
| 166 | h := e.claim(scope, "one", "r1", "ws1") |
| 167 | if expired { |
| 168 | e.clock.Advance(spec.Policy.lease() + 1) |
| 169 | e.crash() |
| 170 | e.openNoResume() |
| 171 | rr, err := e.store.Resume(e.ctx) |
| 172 | must(t, err) |
| 173 | if len(rr.Expired) != 1 || rr.Expired[0] != h.Attempt { |
| 174 | t.Fatalf("expired attempt not recovered: %+v", rr) |
| 175 | } |
| 176 | } else { |
| 177 | must(t, e.store.Complete(e.ctx, scope, h, AttemptResult{Outcome: OutcomeSuccess})) |
| 178 | } |
| 179 | _, err := e.store.Claim(e.ctx, scope, "two", "r2", "ws2") |
| 180 | wantCode(t, err, CodeQuota) |
| 181 | must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| 182 | _, err = e.store.Claim(e.ctx, scope, "two", "r2", "ws2") |
| 183 | must(t, err) |
| 184 | }) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | func TestReviewerCannotPublish(t *testing.T) { |
| 189 | e := newEnv(t) |
| 190 | _, scope := e.createJob(softwareSpec([]StepSpec{{Key: "review", Capability: CapReview, Version: 1}})) |
| 191 | h := e.claim(scope, "review", "reviewer", "review-workspace") |
| 192 | for _, op := range []Operation{OpForgePublish, OpTrackerPublish} { |
| 193 | _, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: string(op), Operation: op, Payload: []byte(`{}`)}) |
| 194 | wantCode(t, err, CodeScope) |
| 195 | } |
| 196 | rows, err := e.store.Reservations(e.ctx, scope) |
| 197 | must(t, err) |
| 198 | if len(rows) != 0 { |
| 199 | t.Fatal("refused publication consumed a reservation") |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | func TestConcludeWaitsForChildren(t *testing.T) { |
| 204 | e := newEnv(t) |
| 205 | parent, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 206 | spec := softwareSpec(SoftwareSteps(false)) |
| 207 | spec.Parent = parent.ID |
| 208 | e.createJob(spec) |
| 209 | _, err := e.store.Conclude(e.ctx, scope, "operator") |
| 210 | wantCode(t, err, CodeState) |
| 211 | if e.job(scope).State.Terminal() { |
| 212 | t.Fatal("parent concluded with unfinished children") |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | func TestConcludeRevokesUnusedIntents(t *testing.T) { |
| 217 | e := newEnv(t) |
| 218 | steps := append(SoftwareSteps(false), StepSpec{Key: "optional", Capability: CapReproduce, Version: 1}) |
| 219 | spec := softwareSpec(steps) |
| 220 | _, scope := e.createJob(spec) |
| 221 | w := e.workflow(scope) |
| 222 | repro, _, err := w.Reproduce(e.ctx, []byte(FixtureBaseSource)) |
| 223 | must(t, err) |
| 224 | cand, err := w.Implement(e.ctx, "implement", "ws-implement-1") |
| 225 | must(t, err) |
| 226 | _, err = w.ReviewCandidate(e.ctx, "ws-review-1", cand) |
| 227 | must(t, err) |
| 228 | _, err = w.Verify(e.ctx, repro, cand) |
| 229 | must(t, err) |
| 230 | _, _, err = w.Publish(e.ctx, cand) |
| 231 | must(t, err) |
| 232 | h := e.claim(scope, "optional", "runner", "ws-optional") |
| 233 | id, err := e.store.Intend(e.ctx, scope, h, intent("unused", Usage{InputTokens: 10, OutputTokens: 10})) |
| 234 | must(t, err) |
| 235 | e.clock.Advance(spec.Policy.lease() + 1) |
| 236 | must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| 237 | rep, err := w.Conclude(e.ctx) |
| 238 | must(t, err) |
| 239 | if !rep.Satisfied { |
| 240 | t.Fatalf("unexpected evidence: %+v", rep) |
| 241 | } |
| 242 | a, err := e.store.GetAction(e.ctx, scope, id) |
| 243 | must(t, err) |
| 244 | if a.State != ActionRevoked { |
| 245 | t.Fatalf("success left an unused intent: %+v", a) |
| 246 | } |
| 247 | ledger, err := e.store.Ledger(e.ctx, scope) |
| 248 | must(t, err) |
| 249 | if ledger.Reserved != (Usage{}) { |
| 250 | t.Fatalf("success kept an unused reservation: %+v", ledger) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | func TestSameIncarnationSnapshotCannotRepeatAnIntent(t *testing.T) { |
| 255 | e := newEnv(t) |
| 256 | _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 257 | h := e.claim(scope, "reproduce", "r", "ws") |
| 258 | id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 100, OutputTokens: 100})) |
| 259 | must(t, err) |
| 260 | backup := e.snapshot() |
| 261 | _, err = e.store.Dispatch(e.ctx, scope, id) |
| 262 | must(t, err) |
| 263 | calls := e.impl.Calls() |
| 264 | must(t, e.store.Close()) |
| 265 | e.store = nil |
| 266 | raw, err := os.ReadFile(backup) |
| 267 | must(t, err) |
| 268 | must(t, os.WriteFile(e.path, raw, 0o600)) // preserve the newer external marker |
| 269 | e.openNoResume() |
| 270 | st, err := e.store.Status(e.ctx) |
| 271 | must(t, err) |
| 272 | if !st.Quarantine { |
| 273 | t.Fatal("older snapshot from same incarnation was accepted") |
| 274 | } |
| 275 | a, err := e.store.GetAction(e.ctx, scope, id) |
| 276 | must(t, err) |
| 277 | if a.State != ActionUncertain { |
| 278 | t.Fatalf("restored intent was trusted as %s", a.State) |
| 279 | } |
| 280 | rr, err := e.store.Resume(e.ctx) |
| 281 | must(t, err) |
| 282 | if rr.Resumed || !rr.Quarantine { |
| 283 | t.Fatalf("restored history resumed: %+v", rr) |
| 284 | } |
| 285 | _, err = e.store.Dispatch(e.ctx, scope, id) |
| 286 | if err == nil || e.impl.Calls() != calls { |
| 287 | t.Fatal("restored intent executed again") |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func TestRestoreWithoutRecordedActionsStillNeedsOperator(t *testing.T) { |
| 292 | e := newEnv(t) |
| 293 | backup := e.snapshot() |
| 294 | e.createJob(softwareSpec(SoftwareSteps(false))) |
| 295 | must(t, e.store.Close()) |
| 296 | e.store = nil |
| 297 | raw, err := os.ReadFile(backup) |
| 298 | must(t, err) |
| 299 | must(t, os.WriteFile(e.path, raw, 0o600)) |
| 300 | e.openNoResume() |
| 301 | rr, err := e.store.Resume(e.ctx) |
| 302 | must(t, err) |
| 303 | if rr.Resumed || !rr.Quarantine { |
| 304 | t.Fatal("missing post-snapshot work was assumed absent") |
| 305 | } |
| 306 | _, err = e.store.CreateJob(e.ctx, softwareSpec(SoftwareSteps(false))) |
| 307 | wantCode(t, err, CodeAdmissionPaused) |
| 308 | } |
| 309 | |
| 310 | func TestVersionOneMigrationPreservesJobsAndQuarantinesHistory(t *testing.T) { |
| 311 | e := newEnv(t) |
| 312 | _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| 313 | must(t, e.store.Close()) |
| 314 | e.store = nil |
| 315 | db, err := sql.Open("sqlite", e.path) |
| 316 | must(t, err) |
| 317 | dropRecoverySchema(t, db) |
| 318 | for _, q := range []string{ |
| 319 | `ALTER TABLE service DROP COLUMN revision`, |
| 320 | `ALTER TABLE service DROP COLUMN restore_uncertain`, |
| 321 | `ALTER TABLE actions DROP COLUMN admitted_incarnation`, |
| 322 | `UPDATE service SET schema_version=1 WHERE id=1`, |
| 323 | } { |
| 324 | _, err := db.Exec(q) |
| 325 | must(t, err) |
| 326 | } |
| 327 | must(t, db.Close()) |
| 328 | must(t, os.WriteFile(e.path+".incarnation", []byte("incarnation=1\nclean=true\n"), 0o600)) |
| 329 | e.openNoResume() |
| 330 | _, err = e.store.GetJob(e.ctx, scope) |
| 331 | must(t, err) |
| 332 | st, err := e.store.Status(e.ctx) |
| 333 | must(t, err) |
| 334 | if st.SchemaVersion != SchemaVersion || !st.Quarantine { |
| 335 | t.Fatalf("migration status: %+v", st) |
| 336 | } |
| 337 | } |
| 338 | |