| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner" |
| 15 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 16 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // schedRig is a runner's state with the person's connections (Claude |
| 21 | // and Codex subscriptions, and a metered TensorX) and a step engine |
| 22 | // whose step function admits through the scheduler the way Engineering, |
| 23 | // Review and Research do: held, it reports its hold; admitted on a |
| 24 | // metered connection, the admission commits with the guard's claim. |
| 25 | type schedRig struct { |
| 26 | t *testing.T |
| 27 | ctx context.Context |
| 28 | state *State |
| 29 | conns *Conns |
| 30 | steps *StepEngine |
| 31 | mu sync.Mutex |
| 32 | // ran are the admitted attempts: step/attempt -> connection. |
| 33 | ran map[string]string |
| 34 | // fail makes an attempt on a connection refuse on quota once. |
| 35 | fail map[string]bool |
| 36 | // execs counts the step function's runs per step. |
| 37 | execs map[string]int |
| 38 | } |
| 39 | |
| 40 | func newSchedRig(t *testing.T, subs ...string) *schedRig { |
| 41 | t.Helper() |
| 42 | root := t.TempDir() |
| 43 | os.MkdirAll(filepath.Join(root, "state"), 0700) |
| 44 | state, err := OpenState(context.Background(), filepath.Join(root, "state")) |
| 45 | if err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | t.Cleanup(func() { state.Close() }) |
| 49 | var bs []map[string]any |
| 50 | for _, id := range subs { |
| 51 | provider := id[:len(id)-2] |
| 52 | bs = append(bs, map[string]any{"id": id, "local_id": id, "label": id, "person_id": connPerson, "provider": provider, "family": provider, "model": "m", "account_id": id + "@example.com", "provider_home": filepath.Join(root, id), "kind": "subscription", "expected_identity": map[string]string{"account_id": id + "@example.com", "home_id": "h-" + id, "provider_version": "1"}}) |
| 53 | } |
| 54 | raw, _ := json.Marshal(bs) |
| 55 | bindings := filepath.Join(root, "bindings.json") |
| 56 | if err := os.WriteFile(bindings, raw, 0600); err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | conns := &Conns{Runner: runner.Config{AccountBindingsPath: bindings, ClaudePath: "/bin/true", CodexPath: "/bin/true"}, State: state} |
| 60 | conns.Meter = &metered.Meter{DB: state.db} |
| 61 | ctx, cancel := context.WithCancel(context.Background()) |
| 62 | r := &schedRig{t: t, ctx: ctx, state: state, conns: conns, ran: map[string]string{}, fail: map[string]bool{}, execs: map[string]int{}} |
| 63 | r.steps = &StepEngine{State: state, Exec: r.exec, Notify: func() {}} |
| 64 | conns.Changed = r.steps.MeteredChanged |
| 65 | conns.Readings = r.steps.MeteredChanged |
| 66 | conns.Meter.Changed = r.steps.MeteredChanged |
| 67 | t.Cleanup(func() { cancel(); r.steps.Wait() }) |
| 68 | return r |
| 69 | } |
| 70 | |
| 71 | // reading records a subscription's reported windows (used 0 to 1, each |
| 72 | // resetting at its time). |
| 73 | func (r *schedRig) reading(id string, used float64, resets time.Time) { |
| 74 | r.conns.Observe(id, connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: used * 100, Minutes: 300, ResetsAt: &resets}}}}, "") |
| 75 | } |
| 76 | |
| 77 | // tensorx adds the person's validated metered connection. |
| 78 | func (r *schedRig) tensorx(budget wire.Budget) { |
| 79 | err := r.state.tx(r.ctx, func(tx *sql.Tx) error { |
| 80 | if err := metered.Add(r.ctx, tx, metered.Conn{Connection: "cn_tx", LocalID: piLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: r.t.TempDir(), Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: budget}, time.Now()); err != nil { |
| 81 | return err |
| 82 | } |
| 83 | if err := metered.Checked(r.ctx, tx, piLocal, true); err != nil { |
| 84 | return err |
| 85 | } |
| 86 | return provenModels(r.ctx, tx, piLocal, "z-ai/glm-5.3") |
| 87 | }) |
| 88 | if err != nil { |
| 89 | r.t.Fatal(err) |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // exec is the step function: admitted through the scheduler (failover |
| 94 | // included, the refused connection avoided), or held. |
| 95 | func (r *schedRig) exec(ctx context.Context, row stepRow, progress func(wire.StepReport)) wire.StepReport { |
| 96 | rep := wire.StepReport{TaskID: row.TaskID, StepID: row.StepID, Attempt: row.Attempt, Findings: []wire.Finding{}} |
| 97 | r.mu.Lock() |
| 98 | r.execs[row.StepID]++ |
| 99 | r.mu.Unlock() |
| 100 | var avoid []string |
| 101 | for { |
| 102 | b, hold, admit, err := r.conns.admit(ctx, row, connect.RoleEngineering, keptRef{}, avoid, nil) |
| 103 | if err != nil { |
| 104 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, "account_unavailable", true |
| 105 | return rep |
| 106 | } |
| 107 | if hold != nil { |
| 108 | return heldReport(rep, hold) |
| 109 | } |
| 110 | if admit != nil { |
| 111 | h := metered.Holder{Step: row.StepID, Attempt: row.Attempt, Role: metered.RoleEngineering, Model: b.Model} |
| 112 | adm, err := r.conns.Meter.Admit(ctx, b.LocalID, h, func(t *sql.Tx) error { return admit(ctx, t) }) |
| 113 | if err != nil || !adm.Admitted { |
| 114 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, "metered_refused", true |
| 115 | return rep |
| 116 | } |
| 117 | _ = r.conns.Meter.Finish(ctx, b.LocalID, h, metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}}, nil) |
| 118 | } |
| 119 | r.mu.Lock() |
| 120 | r.ran[row.StepID+"/"+itoa(row.Attempt)] = b.ID |
| 121 | refuse := r.fail[b.ID] |
| 122 | delete(r.fail, b.ID) |
| 123 | r.mu.Unlock() |
| 124 | if !refuse { |
| 125 | rep.State, rep.Termination, rep.Account = wire.StepDone, true, b.ID |
| 126 | return rep |
| 127 | } |
| 128 | // Refused on quota, its exit proven: the next attempt, advanced |
| 129 | // durably, admitted with the refused connection avoided. |
| 130 | r.conns.Limit(b.ID, connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) |
| 131 | if err := r.state.advanceStep(ctx, &row, nil, rep); err != nil { |
| 132 | r.t.Error(err) |
| 133 | return rep |
| 134 | } |
| 135 | rep.Attempt = row.Attempt |
| 136 | avoid = append(avoid, b.ID) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | func (r *schedRig) dispatch(step string, priority string) { |
| 141 | r.t.Helper() |
| 142 | d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-" + step, StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: priority} |
| 143 | if err := r.state.AcceptDispatch(r.ctx, "f-"+step, d); err != nil { |
| 144 | r.t.Fatal(err) |
| 145 | } |
| 146 | r.steps.Wake() |
| 147 | } |
| 148 | |
| 149 | func (r *schedRig) start() { |
| 150 | r.t.Helper() |
| 151 | if err := r.steps.Start(r.ctx); err != nil { |
| 152 | r.t.Fatal(err) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // reports are the step reports queued for the instance, oldest first. |
| 157 | func (r *schedRig) reports(step string) []wire.StepReport { |
| 158 | r.t.Helper() |
| 159 | rows, err := r.state.db.Query("SELECT body FROM outbox WHERE kind=? ORDER BY seq", wire.FrameStep) |
| 160 | if err != nil { |
| 161 | r.t.Fatal(err) |
| 162 | } |
| 163 | defer rows.Close() |
| 164 | var out []wire.StepReport |
| 165 | for rows.Next() { |
| 166 | var body string |
| 167 | rows.Scan(&body) |
| 168 | var rep wire.StepReport |
| 169 | json.Unmarshal([]byte(body), &rep) |
| 170 | if rep.StepID == step { |
| 171 | out = append(out, rep) |
| 172 | } |
| 173 | } |
| 174 | return out |
| 175 | } |
| 176 | |
| 177 | // until waits for cond, failing after d. |
| 178 | func (r *schedRig) until(d time.Duration, what string, cond func() bool) { |
| 179 | r.t.Helper() |
| 180 | deadline := time.Now().Add(d) |
| 181 | for !cond() { |
| 182 | if time.Now().After(deadline) { |
| 183 | r.t.Fatalf("timed out waiting for %s", what) |
| 184 | } |
| 185 | time.Sleep(20 * time.Millisecond) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func (r *schedRig) ranOn(step string, attempt int64) string { |
| 190 | r.mu.Lock() |
| 191 | defer r.mu.Unlock() |
| 192 | return r.ran[step+"/"+itoa(attempt)] |
| 193 | } |
| 194 | |
| 195 | func (r *schedRig) final(step string) (wire.StepReport, bool) { |
| 196 | for _, rep := range r.reports(step) { |
| 197 | if wire.StepTerminal(rep.State) { |
| 198 | return rep, true |
| 199 | } |
| 200 | } |
| 201 | return wire.StepReport{}, false |
| 202 | } |
| 203 | |
| 204 | // The S3 finish line: a low step holds at 0.61 and starts by itself |
| 205 | // after the reset, its hold said once with a wake-up strictly in the |
| 206 | // future; a held step never blocks one that can run. |
| 207 | func TestScheduleLowHoldsThenStartsAfterReset(t *testing.T) { |
| 208 | r := newSchedRig(t, "claude-a") |
| 209 | reset := time.Now().Add(900 * time.Millisecond) |
| 210 | r.reading("claude-a", 0.61, reset) |
| 211 | r.start() |
| 212 | before := time.Now() |
| 213 | r.dispatch("low1", wire.PriorityLow) |
| 214 | r.until(5*time.Second, "the hold", func() bool { return len(r.reports("low1")) > 0 }) |
| 215 | held := r.reports("low1")[0] |
| 216 | if held.State != wire.StepRunning || held.Hold == nil || held.Hold.Reason != wire.HoldHeadroom || held.Hold.Connection != "claude-a" || held.Hold.Provider != "claude" || held.Hold.StepRevision != 1 { |
| 217 | t.Fatalf("held report %+v %+v", held, held.Hold) |
| 218 | } |
| 219 | if held.Hold.WakeAt == nil || !held.Hold.WakeAt.After(before) || held.Hold.WakeAt.Sub(reset).Abs() > time.Millisecond { |
| 220 | t.Fatalf("wake-up %v, reset %v", held.Hold.WakeAt, reset) |
| 221 | } |
| 222 | if r.ranOn("low1", 1) != "" { |
| 223 | t.Fatal("the low step ran at 0.61") |
| 224 | } |
| 225 | // A normal step runs meanwhile: the held one does not block it. |
| 226 | r.dispatch("normal1", wire.PriorityNormal) |
| 227 | r.until(5*time.Second, "the normal step", func() bool { _, ok := r.final("normal1"); return ok }) |
| 228 | // Facts change (a reading that says the same): the step looks again |
| 229 | // and is held again, said only once. |
| 230 | for range 3 { |
| 231 | r.steps.MeteredChanged() |
| 232 | time.Sleep(30 * time.Millisecond) |
| 233 | } |
| 234 | if _, done := r.final("low1"); done { |
| 235 | t.Fatal("the low step ran before its reset") |
| 236 | } |
| 237 | r.until(5*time.Second, "the low step after the reset", func() bool { _, ok := r.final("low1"); return ok }) |
| 238 | if !time.Now().After(reset) || r.ranOn("low1", 1) != "claude-a" { |
| 239 | t.Fatalf("ran on %q at %v (reset %v)", r.ranOn("low1", 1), time.Now(), reset) |
| 240 | } |
| 241 | holds := 0 |
| 242 | for _, rep := range r.reports("low1") { |
| 243 | if rep.Hold != nil { |
| 244 | holds++ |
| 245 | } |
| 246 | } |
| 247 | if holds != 1 { |
| 248 | t.Fatalf("the hold was said %d times", holds) |
| 249 | } |
| 250 | var reason string |
| 251 | if err := r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id=? AND attempt=1", "low1").Scan(&reason); err != nil || reason != "headroom" { |
| 252 | t.Fatalf("admission %q %v", reason, err) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // Run now: a release for the held step revision is consumed with the |
| 257 | // admission it causes and becomes a grant (a normal step, so only the |
| 258 | // release lets it spend on TensorX); a replayed release, and a release |
| 259 | // for a stale step revision, start nothing. |
| 260 | func TestScheduleReleaseOnceAndStaleRefused(t *testing.T) { |
| 261 | r := newSchedRig(t) |
| 262 | r.tensorx(bigBudget) |
| 263 | r.start() |
| 264 | r.dispatch("s1", wire.PriorityNormal) |
| 265 | r.until(5*time.Second, "the hold", func() bool { return len(r.reports("s1")) > 0 }) |
| 266 | if h := r.reports("s1")[0].Hold; h == nil || h.Reason != wire.HoldNoConnection || h.NeedsPerson != wire.HoldNeedsNoConnection { |
| 267 | t.Fatalf("hold %+v", h) |
| 268 | } |
| 269 | // A stale step revision: acked and ignored; the step stays held. |
| 270 | if kept, err := r.state.Release(r.ctx, "fr-stale", wire.ReleaseCommand{ID: "rl_stale", Person: connPerson, TaskID: "tk-s1", StepID: "s1", StepRevision: 2}); err != nil || kept { |
| 271 | t.Fatalf("a stale release was kept: %v %v", kept, err) |
| 272 | } |
| 273 | // Another person's release for it: ignored too. |
| 274 | if kept, _ := r.state.Release(r.ctx, "fr-other", wire.ReleaseCommand{ID: "rl_other", Person: "q@example.com", TaskID: "tk-s1", StepID: "s1", StepRevision: 1}); kept { |
| 275 | t.Fatal("another person's release was kept") |
| 276 | } |
| 277 | r.steps.MeteredChanged() |
| 278 | time.Sleep(200 * time.Millisecond) |
| 279 | if _, done := r.final("s1"); done || r.ranOn("s1", 1) != "" { |
| 280 | t.Fatal("a stale release started the step") |
| 281 | } |
| 282 | if kept, err := r.state.Release(r.ctx, "fr-1", wire.ReleaseCommand{ID: "rl_1", Person: connPerson, TaskID: "tk-s1", StepID: "s1", StepRevision: 1}); err != nil || !kept { |
| 283 | t.Fatalf("release %v %v", kept, err) |
| 284 | } |
| 285 | r.steps.MeteredChanged() |
| 286 | r.until(5*time.Second, "the released step", func() bool { _, ok := r.final("s1"); return ok }) |
| 287 | if r.ranOn("s1", 1) != piLocal { |
| 288 | t.Fatalf("ran on %q", r.ranOn("s1", 1)) |
| 289 | } |
| 290 | var state, reason string |
| 291 | r.state.db.QueryRow("SELECT state FROM releases WHERE id='rl_1'").Scan(&state) |
| 292 | r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id='s1'").Scan(&reason) |
| 293 | var grants int |
| 294 | r.state.db.QueryRow("SELECT count(*) FROM grants WHERE step_id='s1' AND step_revision=1 AND release_id='rl_1'").Scan(&grants) |
| 295 | if state != releaseConsumed || reason != "metered_release" || grants != 1 { |
| 296 | t.Fatalf("release %q, admission %q, grants %d", state, reason, grants) |
| 297 | } |
| 298 | // Replayed: the same frame is seen; the same release under another |
| 299 | // frame id finds the grant. Neither starts anything. |
| 300 | for _, frame := range []string{"fr-1", "fr-1-again"} { |
| 301 | if kept, err := r.state.Release(r.ctx, frame, wire.ReleaseCommand{ID: "rl_1b", Person: connPerson, TaskID: "tk-s1", StepID: "s1", StepRevision: 1}); err != nil || kept { |
| 302 | t.Fatalf("a replayed release was kept (%s): %v", frame, err) |
| 303 | } |
| 304 | } |
| 305 | var admissions int |
| 306 | r.state.db.QueryRow("SELECT count(*) FROM admissions WHERE step_id='s1'").Scan(&admissions) |
| 307 | if admissions != 1 { |
| 308 | t.Fatalf("%d admissions", admissions) |
| 309 | } |
| 310 | // A step revision that holds a grant (its release consumed, the step |
| 311 | // still going: a failover attempt held on its budget) keeps no |
| 312 | // second release: the grant is the one key. |
| 313 | r.dispatch("s2", wire.PriorityNormal) |
| 314 | r.until(5*time.Second, "the second hold", func() bool { return len(r.reports("s2")) > 0 }) |
| 315 | if _, err := r.state.db.Exec("INSERT INTO grants(step_id, step_revision, release_id, at) VALUES('s2', 1, 'rl_s2', '')"); err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | if kept, err := r.state.Release(r.ctx, "fr-s2", wire.ReleaseCommand{ID: "rl_s2b", Person: connPerson, TaskID: "tk-s2", StepID: "s2", StepRevision: 1}); err != nil || kept { |
| 319 | t.Fatalf("a second release for a granted revision was kept: %v %v", kept, err) |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | // A failover attempt inside a grant is admitted: the released step's |
| 324 | // first attempt starts on Claude above its normal threshold (a release is |
| 325 | // urgent for thresholds), Claude refuses on quota, and the next attempt, |
| 326 | // admitted with Claude avoided, goes to TensorX on the same grant. |
| 327 | func TestScheduleFailoverInsideAGrant(t *testing.T) { |
| 328 | r := newSchedRig(t, "claude-a") |
| 329 | r.tensorx(bigBudget) |
| 330 | r.reading("claude-a", 0.9, time.Now().Add(time.Hour)) |
| 331 | r.fail["claude-a"] = true |
| 332 | r.start() |
| 333 | r.dispatch("f1", wire.PriorityNormal) |
| 334 | r.until(5*time.Second, "the hold", func() bool { return len(r.reports("f1")) > 0 }) |
| 335 | if _, err := r.state.Release(r.ctx, "fr-f1", wire.ReleaseCommand{ID: "rl_f1", Person: connPerson, TaskID: "tk-f1", StepID: "f1", StepRevision: 1}); err != nil { |
| 336 | t.Fatal(err) |
| 337 | } |
| 338 | r.steps.MeteredChanged() |
| 339 | r.until(5*time.Second, "the step", func() bool { _, ok := r.final("f1"); return ok }) |
| 340 | if r.ranOn("f1", 1) != "claude-a" || r.ranOn("f1", 2) != piLocal { |
| 341 | t.Fatalf("attempts on %q then %q", r.ranOn("f1", 1), r.ranOn("f1", 2)) |
| 342 | } |
| 343 | var reason string |
| 344 | var revision int64 |
| 345 | r.state.db.QueryRow("SELECT reason, step_revision FROM admissions WHERE step_id='f1' AND attempt=2").Scan(&reason, &revision) |
| 346 | if reason != "metered_release" || revision != 1 { |
| 347 | t.Fatalf("the failover attempt: %q revision %d", reason, revision) |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | // Without a release or urgent, a normal step never spends: it holds on |
| 352 | // no_connection while the only connection that could run it is metered, |
| 353 | // and an urgent priority change (the person's tap) lets it run. |
| 354 | func TestSchedulePriorityChangeGivesLeave(t *testing.T) { |
| 355 | r := newSchedRig(t) |
| 356 | r.tensorx(bigBudget) |
| 357 | r.start() |
| 358 | r.dispatch("p1", wire.PriorityNormal) |
| 359 | r.until(5*time.Second, "the hold", func() bool { return len(r.reports("p1")) > 0 }) |
| 360 | time.Sleep(100 * time.Millisecond) |
| 361 | if r.ranOn("p1", 1) != "" { |
| 362 | t.Fatal("a normal step spent") |
| 363 | } |
| 364 | if ok, err := r.state.SetPriority(r.ctx, "fp-1", wire.PriorityCommand{Person: connPerson, TaskID: "tk-p1", Priority: wire.PriorityUrgent, Revision: 2}); err != nil || !ok { |
| 365 | t.Fatalf("priority %v %v", ok, err) |
| 366 | } |
| 367 | // An older revision changes nothing. |
| 368 | if ok, _ := r.state.SetPriority(r.ctx, "fp-0", wire.PriorityCommand{Person: connPerson, TaskID: "tk-p1", Priority: wire.PriorityLow, Revision: 1}); ok { |
| 369 | t.Fatal("an older priority applied") |
| 370 | } |
| 371 | r.steps.MeteredChanged() |
| 372 | r.until(5*time.Second, "the urgent step", func() bool { _, ok := r.final("p1"); return ok }) |
| 373 | var reason string |
| 374 | r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id='p1'").Scan(&reason) |
| 375 | if r.ranOn("p1", 1) != piLocal || reason != "metered_urgent" { |
| 376 | t.Fatalf("ran on %q, %q", r.ranOn("p1", 1), reason) |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // The release order: urgent, then the earliest deadline, then normal, |
| 381 | // then low, then the oldest. |
| 382 | func TestScheduleReleaseOrder(t *testing.T) { |
| 383 | r := newSchedRig(t, "claude-a") |
| 384 | soon, later := time.Now().Add(48*time.Hour), time.Now().Add(96*time.Hour) |
| 385 | for _, d := range []wire.DispatchCommand{ |
| 386 | {StepID: "low", Priority: wire.PriorityLow}, |
| 387 | {StepID: "normal-old", Priority: wire.PriorityNormal}, |
| 388 | {StepID: "by-later", Priority: wire.PriorityLow, By: &later}, |
| 389 | {StepID: "normal-new"}, |
| 390 | {StepID: "by-soon", Priority: wire.PriorityNormal, By: &soon}, |
| 391 | {StepID: "urgent", Priority: wire.PriorityUrgent}, |
| 392 | } { |
| 393 | d.Person, d.TaskID, d.Attempt, d.Specialist, d.Findings = connPerson, "tk-"+d.StepID, 1, wire.SpecialistEngineering, []wire.Finding{} |
| 394 | if err := r.state.AcceptDispatch(r.ctx, "f-"+d.StepID, d); err != nil { |
| 395 | t.Fatal(err) |
| 396 | } |
| 397 | time.Sleep(2 * time.Millisecond) |
| 398 | } |
| 399 | var order []string |
| 400 | for range 6 { |
| 401 | row, ok, err := r.state.nextStep(r.ctx) |
| 402 | if err != nil || !ok { |
| 403 | t.Fatal(ok, err) |
| 404 | } |
| 405 | order = append(order, row.StepID) |
| 406 | if _, err := r.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, row.StepID); err != nil { |
| 407 | t.Fatal(err) |
| 408 | } |
| 409 | } |
| 410 | want := []string{"urgent", "by-soon", "by-later", "normal-old", "normal-new", "low"} |
| 411 | for i := range want { |
| 412 | if order[i] != want[i] { |
| 413 | t.Fatalf("order %v, want %v", order, want) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // The admission reads the facts again in its transaction: a reading that |
| 419 | // moved after Decide read it refuses the admission (Decide runs again). |
| 420 | func TestScheduleAdmissionRechecksFacts(t *testing.T) { |
| 421 | r := newSchedRig(t, "claude-a") |
| 422 | r.reading("claude-a", 0.5, time.Now().Add(time.Hour)) |
| 423 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| 424 | if err := r.state.AcceptDispatch(r.ctx, "f", row.DispatchCommand); err != nil { |
| 425 | t.Fatal(err) |
| 426 | } |
| 427 | d, err := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) |
| 428 | if err != nil || !d.d.Run { |
| 429 | t.Fatalf("%+v %v", d.d, err) |
| 430 | } |
| 431 | r.reading("claude-a", 0.85, time.Now().Add(time.Hour)) |
| 432 | if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { return r.conns.admitTx(r.ctx, tx, row, d) }); !errors.Is(err, errFactsMoved) { |
| 433 | t.Fatalf("admitted on moved facts: %v", err) |
| 434 | } |
| 435 | // Decided again: held now. |
| 436 | _, hold, _, err := r.conns.admit(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) |
| 437 | if err != nil || hold == nil || hold.Reason != wire.HoldHeadroom { |
| 438 | t.Fatalf("hold %+v %v", hold, err) |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | // A preference with an end is Automatic once the end passes. |
| 443 | func TestPreferenceUntilEnds(t *testing.T) { |
| 444 | r := newSchedRig(t, "claude-a") |
| 445 | until := time.Now().Add(time.Hour) |
| 446 | if err := r.conns.Prefer(r.ctx, "pf1", wire.PreferenceCommand{Person: connPerson, Provider: "codex", Revision: 1, Until: &until}); err != nil { |
| 447 | t.Fatal(err) |
| 448 | } |
| 449 | if p, _ := r.conns.Preference(r.ctx, connPerson); p.Provider != "codex" { |
| 450 | t.Fatalf("in force: %+v", p) |
| 451 | } |
| 452 | r.conns.now = func() time.Time { return until.Add(time.Second) } |
| 453 | if p, _ := r.conns.Preference(r.ctx, connPerson); p.Provider != "" { |
| 454 | t.Fatalf("after its end: %+v", p) |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | // A stale reading is refreshed by the connection's reading probe before |
| 459 | // the decision (outside it), at most once per fifteen minutes. |
| 460 | func TestScheduleRefreshesStaleReadings(t *testing.T) { |
| 461 | r := newSchedRig(t, "claude-a") |
| 462 | r.reading("claude-a", 0.9, time.Now().Add(time.Hour)) |
| 463 | probes := 0 |
| 464 | r.conns.Reading = func(context.Context, runner.AccountBinding) (*connect.Limit, error) { |
| 465 | probes++ |
| 466 | at := time.Now().Add(time.Hour) |
| 467 | return &connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: 10, Minutes: 300, ResetsAt: &at}}}}, nil |
| 468 | } |
| 469 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| 470 | // Fresh: not probed, held at 0.9. |
| 471 | if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil); d.d.Run || probes != 0 { |
| 472 | t.Fatalf("fresh reading: %+v, %d probes", d.d, probes) |
| 473 | } |
| 474 | r.conns.now = func() time.Time { return time.Now().Add(16 * time.Minute) } |
| 475 | if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil); !d.d.Run || probes != 1 { |
| 476 | t.Fatalf("stale reading: %+v, %d probes", d.d, probes) |
| 477 | } |
| 478 | r.conns.now = func() time.Time { return time.Now().Add(20 * time.Minute) } |
| 479 | r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) |
| 480 | if probes != 1 { |
| 481 | t.Fatalf("probed %d times within fifteen minutes", probes) |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | // Security round #1: a priority frame's value never outlives a newer |
| 486 | // dispatch. Urgent while a step ran, then normal and a Retry: the retry's |
| 487 | // dispatch (a newer priority revision) is what counts. |
| 488 | func TestScheduleNewerDispatchBeatsCachedPriority(t *testing.T) { |
| 489 | r := newSchedRig(t, "claude-a") |
| 490 | if ok, err := r.state.SetPriority(r.ctx, "fp", wire.PriorityCommand{Person: connPerson, TaskID: "tk-x", Priority: wire.PriorityUrgent, Revision: 2}); err != nil || !ok { |
| 491 | t.Fatal(ok, err) |
| 492 | } |
| 493 | facts := func(step string, priority string, revision int64) string { |
| 494 | t.Helper() |
| 495 | d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-x", StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: priority, PriorityRevision: revision} |
| 496 | if err := r.state.AcceptDispatch(r.ctx, "f-"+step, d); err != nil { |
| 497 | t.Fatal(err) |
| 498 | } |
| 499 | f, err := readStepFacts(r.ctx, r.state.db, stepRow{DispatchCommand: d}) |
| 500 | if err != nil { |
| 501 | t.Fatal(err) |
| 502 | } |
| 503 | // The attempt ends: one running step per task. |
| 504 | if _, err := r.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, step); err != nil { |
| 505 | t.Fatal(err) |
| 506 | } |
| 507 | return f.priority |
| 508 | } |
| 509 | if p := facts("older", wire.PriorityNormal, 1); p != wire.PriorityUrgent { |
| 510 | t.Fatalf("an older dispatch: %q", p) |
| 511 | } |
| 512 | if p := facts("newer", wire.PriorityNormal, 4); p != wire.PriorityNormal { |
| 513 | t.Fatalf("a newer dispatch lost to the cached urgent: %q", p) |
| 514 | } |
| 515 | // And the newer value is the one held now: a stale frame cannot |
| 516 | // bring urgent back. |
| 517 | if ok, _ := r.state.SetPriority(r.ctx, "fp2", wire.PriorityCommand{Person: connPerson, TaskID: "tk-x", Priority: wire.PriorityUrgent, Revision: 3}); ok { |
| 518 | t.Fatal("a priority frame older than the newest dispatch applied") |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | // Security round #2: a housekeeping attempt never spends, whatever a |
| 523 | // priority frame, an urgent dispatch or a release says. |
| 524 | func TestScheduleHousekeepingNeverSpends(t *testing.T) { |
| 525 | r := newSchedRig(t) |
| 526 | r.tensorx(bigBudget) |
| 527 | r.start() |
| 528 | d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-hk", StepID: "hk", Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: wire.PriorityUrgent, Release: "rl_hk", Housekeeping: true} |
| 529 | if err := r.state.AcceptDispatch(r.ctx, "f-hk", d); err != nil { |
| 530 | t.Fatal(err) |
| 531 | } |
| 532 | r.steps.Wake() |
| 533 | r.until(5*time.Second, "the hold", func() bool { return len(r.reports("hk")) > 0 }) |
| 534 | r.state.SetPriority(r.ctx, "fp-hk", wire.PriorityCommand{Person: connPerson, TaskID: "tk-hk", Priority: wire.PriorityUrgent, Revision: 9}) |
| 535 | r.state.Release(r.ctx, "fr-hk", wire.ReleaseCommand{ID: "rl_hk2", Person: connPerson, TaskID: "tk-hk", StepID: "hk", StepRevision: 1}) |
| 536 | r.steps.MeteredChanged() |
| 537 | time.Sleep(300 * time.Millisecond) |
| 538 | if r.ranOn("hk", 1) != "" { |
| 539 | t.Fatalf("housekeeping spent on %q", r.ranOn("hk", 1)) |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // Security round #3: a held step that never launched keeps its hold |
| 544 | // across a restart (reopening thin.db before its wake-up), and is not |
| 545 | // failed runner_restarted. |
| 546 | func TestScheduleHoldSurvivesRestart(t *testing.T) { |
| 547 | dir := t.TempDir() |
| 548 | state, err := OpenState(context.Background(), dir) |
| 549 | if err != nil { |
| 550 | t.Fatal(err) |
| 551 | } |
| 552 | d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-r", StepID: "r1", Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}} |
| 553 | if err := state.AcceptDispatch(context.Background(), "f", d); err != nil { |
| 554 | t.Fatal(err) |
| 555 | } |
| 556 | wake := time.Now().Add(time.Hour).UTC().Truncate(time.Millisecond) |
| 557 | if _, err := state.holdStep(context.Background(), stepRow{DispatchCommand: d}, &wire.StepHold{Reason: wire.HoldHeadroom, WakeAt: &wake, StepRevision: 1}); err != nil { |
| 558 | t.Fatal(err) |
| 559 | } |
| 560 | state.Close() |
| 561 | state, err = OpenState(context.Background(), dir) |
| 562 | if err != nil { |
| 563 | t.Fatal(err) |
| 564 | } |
| 565 | defer state.Close() |
| 566 | if err := state.RecoverSteps(context.Background(), func(context.Context, string) bool { return true }); err != nil { |
| 567 | t.Fatal(err) |
| 568 | } |
| 569 | var st, hold string |
| 570 | state.db.QueryRow("SELECT state, hold FROM steps WHERE step_id='r1'").Scan(&st, &hold) |
| 571 | var reports int |
| 572 | state.db.QueryRow("SELECT count(*) FROM outbox WHERE kind=?", wire.FrameStep).Scan(&reports) |
| 573 | if st != runRunning || hold == "" || reports != 0 { |
| 574 | t.Fatalf("after a restart: state %q, hold %q, %d reports", st, hold, reports) |
| 575 | } |
| 576 | if due, ok := state.nextDue(context.Background()); !ok || !due.Equal(wake) { |
| 577 | t.Fatalf("wake-up %v %v, want %v", due, ok, wake) |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | // Security round #4: an execution is admitted once. A second admission |
| 582 | // of a launched attempt is refused; a retry before anything launched is |
| 583 | // the one explicit exception. |
| 584 | func TestScheduleDuplicateAdmissionRefused(t *testing.T) { |
| 585 | r := newSchedRig(t, "claude-a") |
| 586 | row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} |
| 587 | if err := r.state.AcceptDispatch(r.ctx, "f", row.DispatchCommand); err != nil { |
| 588 | t.Fatal(err) |
| 589 | } |
| 590 | admit := func() error { |
| 591 | d, err := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) |
| 592 | if err != nil || !d.d.Run { |
| 593 | t.Fatalf("%+v %v", d.d, err) |
| 594 | } |
| 595 | return r.state.tx(r.ctx, func(tx *sql.Tx) error { return r.conns.admitTx(r.ctx, tx, row, d) }) |
| 596 | } |
| 597 | launches := 0 |
| 598 | r.reading("claude-a", 0.1, time.Now().Add(time.Hour)) |
| 599 | if err := admit(); err != nil { |
| 600 | t.Fatal(err) |
| 601 | } |
| 602 | // Before anything launched: admitted again (a prelaunch retry). |
| 603 | if err := admit(); err != nil { |
| 604 | t.Fatalf("a prelaunch retry: %v", err) |
| 605 | } |
| 606 | launches++ |
| 607 | if err := r.state.setStepNamespace(r.ctx, row, "ns-1"); err != nil { |
| 608 | t.Fatal(err) |
| 609 | } |
| 610 | if err := admit(); !errors.Is(err, errAdmitted) { |
| 611 | t.Fatalf("a launched attempt admitted again: %v", err) |
| 612 | } else { |
| 613 | // Refused: nothing launches. |
| 614 | } |
| 615 | if launches != 1 { |
| 616 | t.Fatalf("%d launches", launches) |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | // Security round #12: a hold after a failover is kept against the |
| 621 | // attempt the step moved to, and said once. |
| 622 | func TestScheduleHoldAfterFailover(t *testing.T) { |
| 623 | r := newSchedRig(t, "claude-a") |
| 624 | r.reading("claude-a", 0.1, time.Now().Add(time.Hour)) |
| 625 | r.fail["claude-a"] = true |
| 626 | r.start() |
| 627 | r.dispatch("fo", wire.PriorityNormal) |
| 628 | |
| 629 | r.until(5*time.Second, "the held second attempt", func() bool { |
| 630 | for _, rep := range r.reports("fo") { |
| 631 | if rep.Hold != nil && rep.Attempt == 2 { |
| 632 | return true |
| 633 | } |
| 634 | } |
| 635 | return false |
| 636 | }) |
| 637 | var hold string |
| 638 | r.state.db.QueryRow("SELECT hold FROM steps WHERE step_id='fo' AND attempt=2").Scan(&hold) |
| 639 | if hold == "" { |
| 640 | t.Fatal("the hold after the failover was not kept") |
| 641 | } |
| 642 | time.Sleep(200 * time.Millisecond) |
| 643 | n := 0 |
| 644 | for _, rep := range r.reports("fo") { |
| 645 | if rep.Hold != nil { |
| 646 | n++ |
| 647 | } |
| 648 | } |
| 649 | if n != 1 { |
| 650 | t.Fatalf("the hold was said %d times", n) |
| 651 | } |
| 652 | // Kept, so the step is not looked at again at once. |
| 653 | r.mu.Lock() |
| 654 | defer r.mu.Unlock() |
| 655 | if r.execs["fo"] != 1 { |
| 656 | t.Fatalf("the held step ran %d times", r.execs["fo"]) |
| 657 | } |
| 658 | } |
| 659 | |