package thin import ( "context" "database/sql" "encoding/json" "errors" "os" "path/filepath" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/wire" ) // schedRig is a runner's state with the person's connections (Claude // and Codex subscriptions, and a metered TensorX) and a step engine // whose step function admits through the scheduler the way Engineering, // Review and Research do: held, it reports its hold; admitted on a // metered connection, the admission commits with the guard's claim. type schedRig struct { t *testing.T ctx context.Context state *State conns *Conns steps *StepEngine mu sync.Mutex // ran are the admitted attempts: step/attempt -> connection. ran map[string]string // fail makes an attempt on a connection refuse on quota once. fail map[string]bool // execs counts the step function's runs per step. execs map[string]int } func newSchedRig(t *testing.T, subs ...string) *schedRig { t.Helper() root := t.TempDir() os.MkdirAll(filepath.Join(root, "state"), 0700) state, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { state.Close() }) var bs []map[string]any for _, id := range subs { provider := id[:len(id)-2] 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"}}) } raw, _ := json.Marshal(bs) bindings := filepath.Join(root, "bindings.json") if err := os.WriteFile(bindings, raw, 0600); err != nil { t.Fatal(err) } conns := &Conns{Runner: runner.Config{AccountBindingsPath: bindings, ClaudePath: "/bin/true", CodexPath: "/bin/true"}, State: state} conns.Meter = &metered.Meter{DB: state.db} ctx, cancel := context.WithCancel(context.Background()) r := &schedRig{t: t, ctx: ctx, state: state, conns: conns, ran: map[string]string{}, fail: map[string]bool{}, execs: map[string]int{}} r.steps = &StepEngine{State: state, Exec: r.exec, Notify: func() {}} conns.Changed = r.steps.MeteredChanged conns.Readings = r.steps.MeteredChanged conns.Meter.Changed = r.steps.MeteredChanged t.Cleanup(func() { cancel(); r.steps.Wait() }) return r } // reading records a subscription's reported windows (used 0 to 1, each // resetting at its time). func (r *schedRig) reading(id string, used float64, resets time.Time) { r.conns.Observe(id, connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: used * 100, Minutes: 300, ResetsAt: &resets}}}}, "") } // tensorx adds the person's validated metered connection. func (r *schedRig) tensorx(budget wire.Budget) { err := r.state.tx(r.ctx, func(tx *sql.Tx) error { 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 { return err } if err := metered.Checked(r.ctx, tx, piLocal, true); err != nil { return err } return provenModels(r.ctx, tx, piLocal, "z-ai/glm-5.3") }) if err != nil { r.t.Fatal(err) } } // exec is the step function: admitted through the scheduler (failover // included, the refused connection avoided), or held. func (r *schedRig) exec(ctx context.Context, row stepRow, progress func(wire.StepReport)) wire.StepReport { rep := wire.StepReport{TaskID: row.TaskID, StepID: row.StepID, Attempt: row.Attempt, Findings: []wire.Finding{}} r.mu.Lock() r.execs[row.StepID]++ r.mu.Unlock() var avoid []string for { b, hold, admit, err := r.conns.admit(ctx, row, connect.RoleEngineering, keptRef{}, avoid, nil) if err != nil { rep.State, rep.Reason, rep.Termination = wire.StepFailed, "account_unavailable", true return rep } if hold != nil { return heldReport(rep, hold) } if admit != nil { h := metered.Holder{Step: row.StepID, Attempt: row.Attempt, Role: metered.RoleEngineering, Model: b.Model} adm, err := r.conns.Meter.Admit(ctx, b.LocalID, h, func(t *sql.Tx) error { return admit(ctx, t) }) if err != nil || !adm.Admitted { rep.State, rep.Reason, rep.Termination = wire.StepFailed, "metered_refused", true return rep } _ = r.conns.Meter.Finish(ctx, b.LocalID, h, metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}}, nil) } r.mu.Lock() r.ran[row.StepID+"/"+itoa(row.Attempt)] = b.ID refuse := r.fail[b.ID] delete(r.fail, b.ID) r.mu.Unlock() if !refuse { rep.State, rep.Termination, rep.Account = wire.StepDone, true, b.ID return rep } // Refused on quota, its exit proven: the next attempt, advanced // durably, admitted with the refused connection avoided. r.conns.Limit(b.ID, connect.Limit{Limited: true, ResetsAt: time.Now().Add(time.Hour)}) if err := r.state.advanceStep(ctx, &row, nil, rep); err != nil { r.t.Error(err) return rep } rep.Attempt = row.Attempt avoid = append(avoid, b.ID) } } func (r *schedRig) dispatch(step string, priority string) { r.t.Helper() d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-" + step, StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: priority} if err := r.state.AcceptDispatch(r.ctx, "f-"+step, d); err != nil { r.t.Fatal(err) } r.steps.Wake() } func (r *schedRig) start() { r.t.Helper() if err := r.steps.Start(r.ctx); err != nil { r.t.Fatal(err) } } // reports are the step reports queued for the instance, oldest first. func (r *schedRig) reports(step string) []wire.StepReport { r.t.Helper() rows, err := r.state.db.Query("SELECT body FROM outbox WHERE kind=? ORDER BY seq", wire.FrameStep) if err != nil { r.t.Fatal(err) } defer rows.Close() var out []wire.StepReport for rows.Next() { var body string rows.Scan(&body) var rep wire.StepReport json.Unmarshal([]byte(body), &rep) if rep.StepID == step { out = append(out, rep) } } return out } // until waits for cond, failing after d. func (r *schedRig) until(d time.Duration, what string, cond func() bool) { r.t.Helper() deadline := time.Now().Add(d) for !cond() { if time.Now().After(deadline) { r.t.Fatalf("timed out waiting for %s", what) } time.Sleep(20 * time.Millisecond) } } func (r *schedRig) ranOn(step string, attempt int64) string { r.mu.Lock() defer r.mu.Unlock() return r.ran[step+"/"+itoa(attempt)] } func (r *schedRig) final(step string) (wire.StepReport, bool) { for _, rep := range r.reports(step) { if wire.StepTerminal(rep.State) { return rep, true } } return wire.StepReport{}, false } // The S3 finish line: a low step holds at 0.61 and starts by itself // after the reset, its hold said once with a wake-up strictly in the // future; a held step never blocks one that can run. func TestScheduleLowHoldsThenStartsAfterReset(t *testing.T) { r := newSchedRig(t, "claude-a") reset := time.Now().Add(900 * time.Millisecond) r.reading("claude-a", 0.61, reset) r.start() before := time.Now() r.dispatch("low1", wire.PriorityLow) r.until(5*time.Second, "the hold", func() bool { return len(r.reports("low1")) > 0 }) held := r.reports("low1")[0] 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 { t.Fatalf("held report %+v %+v", held, held.Hold) } if held.Hold.WakeAt == nil || !held.Hold.WakeAt.After(before) || held.Hold.WakeAt.Sub(reset).Abs() > time.Millisecond { t.Fatalf("wake-up %v, reset %v", held.Hold.WakeAt, reset) } if r.ranOn("low1", 1) != "" { t.Fatal("the low step ran at 0.61") } // A normal step runs meanwhile: the held one does not block it. r.dispatch("normal1", wire.PriorityNormal) r.until(5*time.Second, "the normal step", func() bool { _, ok := r.final("normal1"); return ok }) // Facts change (a reading that says the same): the step looks again // and is held again, said only once. for range 3 { r.steps.MeteredChanged() time.Sleep(30 * time.Millisecond) } if _, done := r.final("low1"); done { t.Fatal("the low step ran before its reset") } r.until(5*time.Second, "the low step after the reset", func() bool { _, ok := r.final("low1"); return ok }) if !time.Now().After(reset) || r.ranOn("low1", 1) != "claude-a" { t.Fatalf("ran on %q at %v (reset %v)", r.ranOn("low1", 1), time.Now(), reset) } holds := 0 for _, rep := range r.reports("low1") { if rep.Hold != nil { holds++ } } if holds != 1 { t.Fatalf("the hold was said %d times", holds) } var reason string if err := r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id=? AND attempt=1", "low1").Scan(&reason); err != nil || reason != "headroom" { t.Fatalf("admission %q %v", reason, err) } } // Run now: a release for the held step revision is consumed with the // admission it causes and becomes a grant (a normal step, so only the // release lets it spend on TensorX); a replayed release, and a release // for a stale step revision, start nothing. func TestScheduleReleaseOnceAndStaleRefused(t *testing.T) { r := newSchedRig(t) r.tensorx(bigBudget) r.start() r.dispatch("s1", wire.PriorityNormal) r.until(5*time.Second, "the hold", func() bool { return len(r.reports("s1")) > 0 }) if h := r.reports("s1")[0].Hold; h == nil || h.Reason != wire.HoldNoConnection || h.NeedsPerson != wire.HoldNeedsNoConnection { t.Fatalf("hold %+v", h) } // A stale step revision: acked and ignored; the step stays held. 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 { t.Fatalf("a stale release was kept: %v %v", kept, err) } // Another person's release for it: ignored too. 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 { t.Fatal("another person's release was kept") } r.steps.MeteredChanged() time.Sleep(200 * time.Millisecond) if _, done := r.final("s1"); done || r.ranOn("s1", 1) != "" { t.Fatal("a stale release started the step") } 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 { t.Fatalf("release %v %v", kept, err) } r.steps.MeteredChanged() r.until(5*time.Second, "the released step", func() bool { _, ok := r.final("s1"); return ok }) if r.ranOn("s1", 1) != piLocal { t.Fatalf("ran on %q", r.ranOn("s1", 1)) } var state, reason string r.state.db.QueryRow("SELECT state FROM releases WHERE id='rl_1'").Scan(&state) r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id='s1'").Scan(&reason) var grants int r.state.db.QueryRow("SELECT count(*) FROM grants WHERE step_id='s1' AND step_revision=1 AND release_id='rl_1'").Scan(&grants) if state != releaseConsumed || reason != "metered_release" || grants != 1 { t.Fatalf("release %q, admission %q, grants %d", state, reason, grants) } // Replayed: the same frame is seen; the same release under another // frame id finds the grant. Neither starts anything. for _, frame := range []string{"fr-1", "fr-1-again"} { 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 { t.Fatalf("a replayed release was kept (%s): %v", frame, err) } } var admissions int r.state.db.QueryRow("SELECT count(*) FROM admissions WHERE step_id='s1'").Scan(&admissions) if admissions != 1 { t.Fatalf("%d admissions", admissions) } // A step revision that holds a grant (its release consumed, the step // still going: a failover attempt held on its budget) keeps no // second release: the grant is the one key. r.dispatch("s2", wire.PriorityNormal) r.until(5*time.Second, "the second hold", func() bool { return len(r.reports("s2")) > 0 }) if _, err := r.state.db.Exec("INSERT INTO grants(step_id, step_revision, release_id, at) VALUES('s2', 1, 'rl_s2', '')"); err != nil { t.Fatal(err) } 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 { t.Fatalf("a second release for a granted revision was kept: %v %v", kept, err) } } // A failover attempt inside a grant is admitted: the released step's // first attempt starts on Claude above its normal threshold (a release is // urgent for thresholds), Claude refuses on quota, and the next attempt, // admitted with Claude avoided, goes to TensorX on the same grant. func TestScheduleFailoverInsideAGrant(t *testing.T) { r := newSchedRig(t, "claude-a") r.tensorx(bigBudget) r.reading("claude-a", 0.9, time.Now().Add(time.Hour)) r.fail["claude-a"] = true r.start() r.dispatch("f1", wire.PriorityNormal) r.until(5*time.Second, "the hold", func() bool { return len(r.reports("f1")) > 0 }) 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 { t.Fatal(err) } r.steps.MeteredChanged() r.until(5*time.Second, "the step", func() bool { _, ok := r.final("f1"); return ok }) if r.ranOn("f1", 1) != "claude-a" || r.ranOn("f1", 2) != piLocal { t.Fatalf("attempts on %q then %q", r.ranOn("f1", 1), r.ranOn("f1", 2)) } var reason string var revision int64 r.state.db.QueryRow("SELECT reason, step_revision FROM admissions WHERE step_id='f1' AND attempt=2").Scan(&reason, &revision) if reason != "metered_release" || revision != 1 { t.Fatalf("the failover attempt: %q revision %d", reason, revision) } } // Without a release or urgent, a normal step never spends: it holds on // no_connection while the only connection that could run it is metered, // and an urgent priority change (the person's tap) lets it run. func TestSchedulePriorityChangeGivesLeave(t *testing.T) { r := newSchedRig(t) r.tensorx(bigBudget) r.start() r.dispatch("p1", wire.PriorityNormal) r.until(5*time.Second, "the hold", func() bool { return len(r.reports("p1")) > 0 }) time.Sleep(100 * time.Millisecond) if r.ranOn("p1", 1) != "" { t.Fatal("a normal step spent") } 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 { t.Fatalf("priority %v %v", ok, err) } // An older revision changes nothing. if ok, _ := r.state.SetPriority(r.ctx, "fp-0", wire.PriorityCommand{Person: connPerson, TaskID: "tk-p1", Priority: wire.PriorityLow, Revision: 1}); ok { t.Fatal("an older priority applied") } r.steps.MeteredChanged() r.until(5*time.Second, "the urgent step", func() bool { _, ok := r.final("p1"); return ok }) var reason string r.state.db.QueryRow("SELECT reason FROM admissions WHERE step_id='p1'").Scan(&reason) if r.ranOn("p1", 1) != piLocal || reason != "metered_urgent" { t.Fatalf("ran on %q, %q", r.ranOn("p1", 1), reason) } } // The release order: urgent, then the earliest deadline, then normal, // then low, then the oldest. func TestScheduleReleaseOrder(t *testing.T) { r := newSchedRig(t, "claude-a") soon, later := time.Now().Add(48*time.Hour), time.Now().Add(96*time.Hour) for _, d := range []wire.DispatchCommand{ {StepID: "low", Priority: wire.PriorityLow}, {StepID: "normal-old", Priority: wire.PriorityNormal}, {StepID: "by-later", Priority: wire.PriorityLow, By: &later}, {StepID: "normal-new"}, {StepID: "by-soon", Priority: wire.PriorityNormal, By: &soon}, {StepID: "urgent", Priority: wire.PriorityUrgent}, } { d.Person, d.TaskID, d.Attempt, d.Specialist, d.Findings = connPerson, "tk-"+d.StepID, 1, wire.SpecialistEngineering, []wire.Finding{} if err := r.state.AcceptDispatch(r.ctx, "f-"+d.StepID, d); err != nil { t.Fatal(err) } time.Sleep(2 * time.Millisecond) } var order []string for range 6 { row, ok, err := r.state.nextStep(r.ctx) if err != nil || !ok { t.Fatal(ok, err) } order = append(order, row.StepID) if _, err := r.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, row.StepID); err != nil { t.Fatal(err) } } want := []string{"urgent", "by-soon", "by-later", "normal-old", "normal-new", "low"} for i := range want { if order[i] != want[i] { t.Fatalf("order %v, want %v", order, want) } } } // The admission reads the facts again in its transaction: a reading that // moved after Decide read it refuses the admission (Decide runs again). func TestScheduleAdmissionRechecksFacts(t *testing.T) { r := newSchedRig(t, "claude-a") r.reading("claude-a", 0.5, time.Now().Add(time.Hour)) row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} if err := r.state.AcceptDispatch(r.ctx, "f", row.DispatchCommand); err != nil { t.Fatal(err) } d, err := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) if err != nil || !d.d.Run { t.Fatalf("%+v %v", d.d, err) } r.reading("claude-a", 0.85, time.Now().Add(time.Hour)) 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) { t.Fatalf("admitted on moved facts: %v", err) } // Decided again: held now. _, hold, _, err := r.conns.admit(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) if err != nil || hold == nil || hold.Reason != wire.HoldHeadroom { t.Fatalf("hold %+v %v", hold, err) } } // A preference with an end is Automatic once the end passes. func TestPreferenceUntilEnds(t *testing.T) { r := newSchedRig(t, "claude-a") until := time.Now().Add(time.Hour) if err := r.conns.Prefer(r.ctx, "pf1", wire.PreferenceCommand{Person: connPerson, Provider: "codex", Revision: 1, Until: &until}); err != nil { t.Fatal(err) } if p, _ := r.conns.Preference(r.ctx, connPerson); p.Provider != "codex" { t.Fatalf("in force: %+v", p) } r.conns.now = func() time.Time { return until.Add(time.Second) } if p, _ := r.conns.Preference(r.ctx, connPerson); p.Provider != "" { t.Fatalf("after its end: %+v", p) } } // A stale reading is refreshed by the connection's reading probe before // the decision (outside it), at most once per fifteen minutes. func TestScheduleRefreshesStaleReadings(t *testing.T) { r := newSchedRig(t, "claude-a") r.reading("claude-a", 0.9, time.Now().Add(time.Hour)) probes := 0 r.conns.Reading = func(context.Context, runner.AccountBinding) (*connect.Limit, error) { probes++ at := time.Now().Add(time.Hour) return &connect.Limit{Headroom: &wire.Headroom{Windows: []wire.Window{{Name: "five_hour", UsedPercent: 10, Minutes: 300, ResetsAt: &at}}}}, nil } row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} // Fresh: not probed, held at 0.9. if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil); d.d.Run || probes != 0 { t.Fatalf("fresh reading: %+v, %d probes", d.d, probes) } r.conns.now = func() time.Time { return time.Now().Add(16 * time.Minute) } if d, _ := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil); !d.d.Run || probes != 1 { t.Fatalf("stale reading: %+v, %d probes", d.d, probes) } r.conns.now = func() time.Time { return time.Now().Add(20 * time.Minute) } r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) if probes != 1 { t.Fatalf("probed %d times within fifteen minutes", probes) } } // Security round #1: a priority frame's value never outlives a newer // dispatch. Urgent while a step ran, then normal and a Retry: the retry's // dispatch (a newer priority revision) is what counts. func TestScheduleNewerDispatchBeatsCachedPriority(t *testing.T) { r := newSchedRig(t, "claude-a") if ok, err := r.state.SetPriority(r.ctx, "fp", wire.PriorityCommand{Person: connPerson, TaskID: "tk-x", Priority: wire.PriorityUrgent, Revision: 2}); err != nil || !ok { t.Fatal(ok, err) } facts := func(step string, priority string, revision int64) string { t.Helper() d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-x", StepID: step, Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}, Priority: priority, PriorityRevision: revision} if err := r.state.AcceptDispatch(r.ctx, "f-"+step, d); err != nil { t.Fatal(err) } f, err := readStepFacts(r.ctx, r.state.db, stepRow{DispatchCommand: d}) if err != nil { t.Fatal(err) } // The attempt ends: one running step per task. if _, err := r.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, step); err != nil { t.Fatal(err) } return f.priority } if p := facts("older", wire.PriorityNormal, 1); p != wire.PriorityUrgent { t.Fatalf("an older dispatch: %q", p) } if p := facts("newer", wire.PriorityNormal, 4); p != wire.PriorityNormal { t.Fatalf("a newer dispatch lost to the cached urgent: %q", p) } // And the newer value is the one held now: a stale frame cannot // bring urgent back. if ok, _ := r.state.SetPriority(r.ctx, "fp2", wire.PriorityCommand{Person: connPerson, TaskID: "tk-x", Priority: wire.PriorityUrgent, Revision: 3}); ok { t.Fatal("a priority frame older than the newest dispatch applied") } } // Security round #2: a housekeeping attempt never spends, whatever a // priority frame, an urgent dispatch or a release says. func TestScheduleHousekeepingNeverSpends(t *testing.T) { r := newSchedRig(t) r.tensorx(bigBudget) r.start() 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} if err := r.state.AcceptDispatch(r.ctx, "f-hk", d); err != nil { t.Fatal(err) } r.steps.Wake() r.until(5*time.Second, "the hold", func() bool { return len(r.reports("hk")) > 0 }) r.state.SetPriority(r.ctx, "fp-hk", wire.PriorityCommand{Person: connPerson, TaskID: "tk-hk", Priority: wire.PriorityUrgent, Revision: 9}) r.state.Release(r.ctx, "fr-hk", wire.ReleaseCommand{ID: "rl_hk2", Person: connPerson, TaskID: "tk-hk", StepID: "hk", StepRevision: 1}) r.steps.MeteredChanged() time.Sleep(300 * time.Millisecond) if r.ranOn("hk", 1) != "" { t.Fatalf("housekeeping spent on %q", r.ranOn("hk", 1)) } } // Security round #3: a held step that never launched keeps its hold // across a restart (reopening thin.db before its wake-up), and is not // failed runner_restarted. func TestScheduleHoldSurvivesRestart(t *testing.T) { dir := t.TempDir() state, err := OpenState(context.Background(), dir) if err != nil { t.Fatal(err) } d := wire.DispatchCommand{Person: connPerson, TaskID: "tk-r", StepID: "r1", Attempt: 1, Specialist: wire.SpecialistEngineering, Findings: []wire.Finding{}} if err := state.AcceptDispatch(context.Background(), "f", d); err != nil { t.Fatal(err) } wake := time.Now().Add(time.Hour).UTC().Truncate(time.Millisecond) if _, err := state.holdStep(context.Background(), stepRow{DispatchCommand: d}, &wire.StepHold{Reason: wire.HoldHeadroom, WakeAt: &wake, StepRevision: 1}); err != nil { t.Fatal(err) } state.Close() state, err = OpenState(context.Background(), dir) if err != nil { t.Fatal(err) } defer state.Close() if err := state.RecoverSteps(context.Background(), func(context.Context, string) bool { return true }); err != nil { t.Fatal(err) } var st, hold string state.db.QueryRow("SELECT state, hold FROM steps WHERE step_id='r1'").Scan(&st, &hold) var reports int state.db.QueryRow("SELECT count(*) FROM outbox WHERE kind=?", wire.FrameStep).Scan(&reports) if st != runRunning || hold == "" || reports != 0 { t.Fatalf("after a restart: state %q, hold %q, %d reports", st, hold, reports) } if due, ok := state.nextDue(context.Background()); !ok || !due.Equal(wake) { t.Fatalf("wake-up %v %v, want %v", due, ok, wake) } } // Security round #4: an execution is admitted once. A second admission // of a launched attempt is refused; a retry before anything launched is // the one explicit exception. func TestScheduleDuplicateAdmissionRefused(t *testing.T) { r := newSchedRig(t, "claude-a") row := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistEngineering}} if err := r.state.AcceptDispatch(r.ctx, "f", row.DispatchCommand); err != nil { t.Fatal(err) } admit := func() error { d, err := r.conns.decide(r.ctx, row, connect.RoleEngineering, keptRef{}, nil, nil) if err != nil || !d.d.Run { t.Fatalf("%+v %v", d.d, err) } return r.state.tx(r.ctx, func(tx *sql.Tx) error { return r.conns.admitTx(r.ctx, tx, row, d) }) } launches := 0 r.reading("claude-a", 0.1, time.Now().Add(time.Hour)) if err := admit(); err != nil { t.Fatal(err) } // Before anything launched: admitted again (a prelaunch retry). if err := admit(); err != nil { t.Fatalf("a prelaunch retry: %v", err) } launches++ if err := r.state.setStepNamespace(r.ctx, row, "ns-1"); err != nil { t.Fatal(err) } if err := admit(); !errors.Is(err, errAdmitted) { t.Fatalf("a launched attempt admitted again: %v", err) } else { // Refused: nothing launches. } if launches != 1 { t.Fatalf("%d launches", launches) } } // Security round #12: a hold after a failover is kept against the // attempt the step moved to, and said once. func TestScheduleHoldAfterFailover(t *testing.T) { r := newSchedRig(t, "claude-a") r.reading("claude-a", 0.1, time.Now().Add(time.Hour)) r.fail["claude-a"] = true r.start() r.dispatch("fo", wire.PriorityNormal) r.until(5*time.Second, "the held second attempt", func() bool { for _, rep := range r.reports("fo") { if rep.Hold != nil && rep.Attempt == 2 { return true } } return false }) var hold string r.state.db.QueryRow("SELECT hold FROM steps WHERE step_id='fo' AND attempt=2").Scan(&hold) if hold == "" { t.Fatal("the hold after the failover was not kept") } time.Sleep(200 * time.Millisecond) n := 0 for _, rep := range r.reports("fo") { if rep.Hold != nil { n++ } } if n != 1 { t.Fatalf("the hold was said %d times", n) } // Kept, so the step is not looked at again at once. r.mu.Lock() defer r.mu.Unlock() if r.execs["fo"] != 1 { t.Fatalf("the held step ran %d times", r.execs["fo"]) } }