oficina / equipo Public

schedule: Decide, the pure scheduler (connectors spec §7)

Rules in order (kept session, preference, subscription with the most
room, metered with the most room, hold), the bars, thresholds
0.60/0.80/1.0, the fixed room precedence, wake-ups strictly after now,
and Needs you. Table tests per rule; invariants (a) to (f) as property
tests over random inputs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev ee80645dd1c4cb4f9ddb06b86d78bfeeefa5ef14 parent 379fe0d
2 files changed, +1,031 −0
  • internal/schedule/schedule.go +627 −0
  • internal/schedule/schedule_test.go +404 −0
diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go
new file mode 100644
index 00000000..4ff4c85d
--- /dev/null
+++ b/internal/schedule/schedule.go
@@ -0,0 +1,627 @@
+// Package schedule is the scheduler's one decision (connectors spec
+// 2026-11-12 rev 3.1, §7): Decide starts or holds a step from the
+// readings taken at admission. It is pure: no clock, no I/O, no state.
+// The runner refreshes stale readings before it calls Decide, writes the
+// admission in one thin.db transaction that rechecks what Decide read,
+// and persists a hold with its wake-up.
+//
+// What it claims: admission is decided from the readings taken at
+// admission. It does not predict or reserve a step's consumption, and
+// several steps admitted against one reading may together run a window
+// out; the reserve thresholds are the margin, and a window that runs out
+// mid-step is quota failover, as before.
+package schedule
+
+import (
+ "bytes"
+ "slices"
+ "sort"
+ "time"
+)
+
+// Version is the Input's version: a change to its meaning bumps it.
+const Version = 1
+
+// Priorities (§6). An unknown or empty priority is normal.
+const (
+ Urgent = "urgent"
+ Normal = "normal"
+ Low = "low"
+)
+
+// Billing of a connection (§2.1).
+const (
+ Subscription = "subscription"
+ Metered = "metered"
+)
+
+// Roles a step runs (connect.Role*). Review has the family rule.
+const (
+ RoleEngineering = "engineering"
+ RoleReview = "review"
+ RoleResearch = "research"
+)
+
+// Connection states Decide reads (wire.Conn*).
+const (
+ StateHealthy = "healthy"
+ StateLimited = "limited"
+)
+
+// Reasons a decision is recorded with (§7, §10). The first five start a
+// step; the last five hold it.
+const (
+ ReasonSticky = "sticky"
+ ReasonPreference = "preference"
+ ReasonHeadroom = "headroom"
+ ReasonMeteredUrgent = "metered_urgent"
+ ReasonMeteredRelease = "metered_release"
+
+ // A hold's reasons: headroom (above), budget, spend unknown, the
+ // metered connection's one slot taken (a kept session held on it),
+ // and nothing that can run it.
+ ReasonBudget = "budget"
+ ReasonSpendUnknown = "spend_unknown"
+ ReasonBusy = "busy"
+ ReasonNoConnection = "no_connection"
+)
+
+// What a hold needs from the person (§8): the deadline check fired, no
+// reset in sight, or nothing can run it.
+const (
+ NeedsDeadline = "deadline"
+ NeedsNoReset = "no_reset"
+ NeedsNoConnection = "no_connection"
+)
+
+// Thresholds (§0 decision 6): a subscription admits a step at priority p
+// while every reported window is below t(p).
+const (
+ ThresholdLow = 0.60
+ ThresholdNormal = 0.80
+ ThresholdUrgent = 1.0
+)
+
+// Deadline is how long before `by` the deadline check fires; NoResetIn
+// how far away a reset may be before the person is asked.
+const (
+ Deadline = 24 * time.Hour
+ NoResetIn = 72 * time.Hour
+)
+
+// Input is everything Decide reads. It is a value: Decide never changes
+// it.
+type Input struct {
+ Version int
+ Now time.Time
+ Step Step
+ Conns []Conn
+ Preference Preference
+}
+
+// Step is the step being admitted.
+type Step struct {
+ Role string
+ Priority string
+ // By is the task's deadline, if any; DeadlineNotified records that
+ // the deadline check already fired for this step.
+ By *time.Time
+ DeadlineNotified bool
+ // Kept is the connection whose session the step resumes (a fix round
+ // on its Engineering session), "" for none.
+ Kept string
+ // Avoid are connections this attempt must not use (failover).
+ Avoid []string
+ // Release is the Run now grant the step carries ("" for none).
+ Release string
+ // Engineer is what Engineering ran on, for Review's family rule.
+ Engineer *Engineer
+}
+
+// Engineer names the connection Engineering ran on.
+type Engineer struct {
+ ID, Family, Account string
+}
+
+// Conn is one of the person's connections on this runner with the facts
+// of §6.
+type Conn struct {
+ ID string
+ Provider string
+ Family string
+ Account string
+ Billing string
+ // Capable: the harness can run the step's role here.
+ Capable bool
+ State string
+ // LimitedUntil is a limited connection's reset (zero: none known).
+ LimitedUntil time.Time
+ // Windows are the reported windows, as last read.
+ Windows []Window
+ // A metered connection's facts: another attempt holds its slot, its
+ // spend is unknown, its reported spend and its budget, both in the
+ // price table's micro-units, for today and this month.
+ Busy bool
+ SpendUnknown bool
+ SpendDay int64
+ SpendMonth int64
+ BudgetDay int64
+ BudgetMonth int64
+}
+
+// Window is one reported window: Used from 0 to 1.
+type Window struct {
+ Name string
+ Used float64
+ Minutes int64
+ ResetsAt *time.Time
+}
+
+// Preference is the person's preferred provider and until when ("" for
+// Automatic; Until nil for no end).
+type Preference struct {
+ Provider string
+ Until *time.Time
+}
+
+// Decision is Decide's answer. Run: Connection and Reason. Hold: Reason,
+// the Connection it names (or ""), ResetsAt when that one reported a
+// reset, WakeAt (strictly after now, or nil) and NeedsPerson.
+type Decision struct {
+ Run bool
+ Connection string
+ Reason string
+ ResetsAt *time.Time
+ WakeAt *time.Time
+ NeedsPerson string
+ // Effective is the priority the thresholds used: urgent with a
+ // release.
+ Effective string
+}
+
+// Effective is a step's effective priority: urgent with a release,
+// else its own (normal when unset or unknown).
+func Effective(s Step) string {
+ if s.Release != "" {
+ return Urgent
+ }
+ switch s.Priority {
+ case Urgent, Low:
+ return s.Priority
+ }
+ return Normal
+}
+
+// Threshold is t(p).
+func Threshold(p string) float64 {
+ switch p {
+ case Urgent:
+ return ThresholdUrgent
+ case Low:
+ return ThresholdLow
+ }
+ return ThresholdNormal
+}
+
+// Usable reports whether c may run at now (rev 3 §2.7): healthy, or
+// limited with its reset passed.
+func Usable(c Conn, now time.Time) bool {
+ switch c.State {
+ case StateHealthy:
+ return true
+ case StateLimited:
+ return !c.LimitedUntil.IsZero() && !now.Before(c.LimitedUntil)
+ }
+ return false
+}
+
+// reported are c's windows that still count at now: one whose reset has
+// passed with no newer reading counts as not reported.
+func reported(c Conn, now time.Time) []Window {
+ var out []Window
+ for _, w := range c.Windows {
+ if w.ResetsAt != nil && !now.Before(*w.ResetsAt) {
+ continue
+ }
+ out = append(out, w)
+ }
+ return out
+}
+
+// Admits reports whether subscription c admits a step at effective
+// priority p: every reported window below t(p).
+func Admits(c Conn, p string, now time.Time) bool {
+ t := Threshold(p)
+ for _, w := range reported(c, now) {
+ if w.Used >= t {
+ return false
+ }
+ }
+ return true
+}
+
+// spendBar is why a metered connection cannot take a step with leave to
+// spend ("" when it can): the slot, the spend, the budget.
+func spendBar(c Conn) string {
+ switch {
+ case c.SpendUnknown:
+ return ReasonSpendUnknown
+ case c.SpendDay >= c.BudgetDay || c.SpendMonth >= c.BudgetMonth:
+ return ReasonBudget
+ case c.Busy:
+ return ReasonBusy
+ }
+ return ""
+}
+
+// leave is the step's leave to spend metered money (§0 decision 5).
+func leave(s Step) bool { return s.Priority == Urgent || s.Release != "" }
+
+// eligible are the bars every candidate passes, Run now included: capable,
+// usable, not avoided.
+func eligible(c Conn, s Step, now time.Time) bool {
+ return c.Capable && Usable(c, now) && !slices.Contains(s.Avoid, c.ID)
+}
+
+// Decide starts or holds the step (§7). Bars are never overridden; the
+// first rule that yields a connection wins: the kept session, the
+// preference, the subscription with the most room, the metered
+// connection with the most room; else a hold.
+func Decide(in Input) Decision {
+ now, s := in.Now, in.Step
+ eff := Effective(s)
+ pref := in.Preference
+ if pref.Until != nil && !now.Before(*pref.Until) {
+ // An expired preference is treated as absent.
+ pref = Preference{}
+ }
+ d := Decision{Effective: eff}
+ // 1. The kept session stays while it is usable; a spending bar holds
+ // it there. Without leave to spend a kept metered session is not
+ // kept: the step starts afresh elsewhere (decision 5).
+ if s.Kept != "" {
+ for _, c := range in.Conns {
+ if c.ID != s.Kept || !eligible(c, s, now) {
+ continue
+ }
+ if c.Billing != Metered {
+ d.Run, d.Connection, d.Reason = true, c.ID, ReasonSticky
+ return d
+ }
+ if !leave(s) {
+ break
+ }
+ if bar := spendBar(c); bar != "" {
+ return hold(in, eff, bar, c)
+ }
+ d.Run, d.Connection, d.Reason = true, c.ID, ReasonSticky
+ return d
+ }
+ }
+ for _, tier := range tiers(in) {
+ if c, reason, ok := pick(in, eff, pref, tier); ok {
+ d.Run, d.Connection, d.Reason = true, c, reason
+ return d
+ }
+ }
+ return holdFor(in, eff)
+}
+
+// tiers are the candidate sets Review's family rule tries in order:
+// another family; then any connection but Engineering's; then all. Every
+// other role has one tier.
+func tiers(in Input) [][]Conn {
+ e := in.Step.Engineer
+ if in.Step.Role != RoleReview || e == nil {
+ return [][]Conn{in.Conns}
+ }
+ var other, notEngineer []Conn
+ for _, c := range in.Conns {
+ if c.Family != e.Family {
+ other = append(other, c)
+ }
+ if c.ID != e.ID {
+ notEngineer = append(notEngineer, c)
+ }
+ }
+ return [][]Conn{other, notEngineer, in.Conns}
+}
+
+// pick applies rules 2 to 4 to one tier.
+func pick(in Input, eff string, pref Preference, cs []Conn) (string, string, bool) {
+ now, s := in.Now, in.Step
+ var subs, metered []Conn
+ for _, c := range cs {
+ if !eligible(c, s, now) {
+ continue
+ }
+ if c.Billing == Metered {
+ if leave(s) && spendBar(c) == "" {
+ metered = append(metered, c)
+ }
+ continue
+ }
+ if Admits(c, eff, now) {
+ subs = append(subs, c)
+ }
+ }
+ // 2. The preferred provider, if it admits the step (subscriptions:
+ // a preference never puts a metered connection before one).
+ if pref.Provider != "" {
+ var mine []Conn
+ for _, c := range subs {
+ if c.Provider == pref.Provider {
+ mine = append(mine, c)
+ }
+ }
+ if len(mine) > 0 {
+ return roomiest(mine, now).ID, ReasonPreference, true
+ }
+ }
+ // 3. The subscription with the most room.
+ if len(subs) > 0 {
+ return roomiest(subs, now).ID, ReasonHeadroom, true
+ }
+ // 4. The metered connection with the most room; a preferred one first.
+ if len(metered) > 0 {
+ var mine []Conn
+ for _, c := range metered {
+ if c.Provider == pref.Provider {
+ mine = append(mine, c)
+ }
+ }
+ if len(mine) == 0 {
+ mine = metered
+ }
+ reason := ReasonMeteredRelease
+ if s.Priority == Urgent {
+ reason = ReasonMeteredUrgent
+ }
+ return meteredRoomiest(mine).ID, reason, true
+ }
+ return "", "", false
+}
+
+// roomiest is the subscription with the most room (§7, fixed
+// precedence): connections with a reported window first; then the
+// lowest largest used; then the used of the first window by minutes
+// (missing last) then name; then the id bytewise.
+func roomiest(cs []Conn, now time.Time) Conn {
+ best := cs[0]
+ for _, c := range cs[1:] {
+ if lessRoom(c, best, now) {
+ best = c
+ }
+ }
+ return best
+}
+
+// lessRoom reports whether a has more room than b (sorts before it).
+func lessRoom(a, b Conn, now time.Time) bool {
+ wa, wb := reported(a, now), reported(b, now)
+ if (len(wa) > 0) != (len(wb) > 0) {
+ return len(wa) > 0
+ }
+ if len(wa) > 0 {
+ if ma, mb := maxUsed(wa), maxUsed(wb); ma != mb {
+ return ma < mb
+ }
+ if fa, fb := first(wa).Used, first(wb).Used; fa != fb {
+ return fa < fb
+ }
+ }
+ return bytes.Compare([]byte(a.ID), []byte(b.ID)) < 0
+}
+
+func maxUsed(ws []Window) float64 {
+ m := ws[0].Used
+ for _, w := range ws[1:] {
+ m = max(m, w.Used)
+ }
+ return m
+}
+
+// first is the window sorted first by minutes ascending (missing, zero,
+// last), then by name.
+func first(ws []Window) Window {
+ sorted := slices.Clone(ws)
+ sort.SliceStable(sorted, func(i, j int) bool {
+ a, b := sorted[i], sorted[j]
+ if (a.Minutes > 0) != (b.Minutes > 0) {
+ return a.Minutes > 0
+ }
+ if a.Minutes != b.Minutes {
+ return a.Minutes < b.Minutes
+ }
+ return a.Name < b.Name
+ })
+ return sorted[0]
+}
+
+// meteredRoomiest is the metered connection with the most room: the
+// lower larger fraction of day and month spend over budget, then the id.
+func meteredRoomiest(cs []Conn) Conn {
+ best := cs[0]
+ for _, c := range cs[1:] {
+ fc, fb := spentFraction(c), spentFraction(best)
+ if fc < fb || fc == fb && bytes.Compare([]byte(c.ID), []byte(best.ID)) < 0 {
+ best = c
+ }
+ }
+ return best
+}
+
+func spentFraction(c Conn) float64 {
+ frac := func(spent, budget int64) float64 {
+ if budget <= 0 {
+ return 1
+ }
+ return float64(spent) / float64(budget)
+ }
+ return max(frac(c.SpendDay, c.BudgetDay), frac(c.SpendMonth, c.BudgetMonth))
+}
+
+// holdFor is rule 5: why nothing can run the step now, naming the
+// connection it waits for.
+func holdFor(in Input, eff string) Decision {
+ now, s := in.Now, in.Step
+ // A metered connection with leave, held by a spending bar: the most
+ // actionable bar first (spend unknown, then the budget, then a busy
+ // slot), the lowest id among equals.
+ if leave(s) {
+ var named *Conn
+ rank := map[string]int{ReasonSpendUnknown: 0, ReasonBudget: 1, ReasonBusy: 2}
+ for i, c := range in.Conns {
+ if c.Billing != Metered || !eligible(c, s, now) {
+ continue
+ }
+ bar := spendBar(c)
+ if bar == "" {
+ continue
+ }
+ if named == nil || rank[bar] < rank[spendBar(*named)] || rank[bar] == rank[spendBar(*named)] && c.ID < named.ID {
+ named = &in.Conns[i]
+ }
+ }
+ // A subscription waiting for headroom is named before a spending
+ // bar only when nothing metered is in reach.
+ if named != nil {
+ return hold(in, eff, spendBar(*named), *named)
+ }
+ }
+ // Waiting for headroom: the capable subscription (not avoided) whose
+ // reset comes first, over threshold or limited.
+ var named *Conn
+ var at time.Time
+ for i, c := range in.Conns {
+ if !c.Capable || c.Billing == Metered || slices.Contains(s.Avoid, c.ID) {
+ continue
+ }
+ if c.State != StateHealthy && c.State != StateLimited {
+ continue
+ }
+ r := resetOf(c, eff, now)
+ switch {
+ case named == nil:
+ named, at = &in.Conns[i], r
+ case !r.IsZero() && (at.IsZero() || r.Before(at) || r.Equal(at) && c.ID < named.ID):
+ named, at = &in.Conns[i], r
+ case r.IsZero() && at.IsZero() && c.ID < named.ID:
+ named = &in.Conns[i]
+ }
+ }
+ if named != nil {
+ d := hold(in, eff, ReasonHeadroom, *named)
+ if !at.IsZero() {
+ d.ResetsAt = &at
+ }
+ return d
+ }
+ return hold(in, eff, ReasonNoConnection, Conn{})
+}
+
+// resetOf is when subscription c may admit a step at p again: its
+// limit's reset, else the latest reset among the windows over t(p). Zero
+// when it reported none.
+func resetOf(c Conn, p string, now time.Time) time.Time {
+ if c.State == StateLimited && !Usable(c, now) {
+ return c.LimitedUntil
+ }
+ var at time.Time
+ t := Threshold(p)
+ for _, w := range reported(c, now) {
+ if w.Used < t {
+ continue
+ }
+ if w.ResetsAt == nil {
+ return time.Time{}
+ }
+ if w.ResetsAt.After(at) {
+ at = *w.ResetsAt
+ }
+ }
+ return at
+}
+
+// hold is a held decision: the reason, the connection it names, the
+// wake-up and what it needs from the person.
+func hold(in Input, eff, reason string, named Conn) Decision {
+ now, s := in.Now, in.Step
+ d := Decision{Reason: reason, Connection: named.ID, Effective: eff}
+ resets, budgetAt := wakeUps(in)
+ wake := earliest(now, append(slices.Clone(resets), budgetAt...)...)
+ if pu := in.Preference.Until; pu != nil {
+ wake = earliest(now, append(nonNil(wake), *pu)...)
+ }
+ if s.By != nil && !s.DeadlineNotified {
+ wake = earliest(now, append(nonNil(wake), s.By.Add(-Deadline))...)
+ }
+ d.WakeAt = wake
+ // What the person can change, in order: the deadline is near, nothing
+ // can run it, no reset in sight.
+ resetWake := earliest(now, resets...)
+ if reason == ReasonBudget {
+ resetWake = earliest(now, append(slices.Clone(resets), budgetAt...)...)
+ }
+ switch {
+ case s.By != nil && !s.DeadlineNotified && !now.Before(s.By.Add(-Deadline)):
+ d.NeedsPerson = NeedsDeadline
+ case reason == ReasonNoConnection:
+ d.NeedsPerson = NeedsNoConnection
+ case reason == ReasonBusy:
+ // Another attempt holds the slot: it ends by itself.
+ case resetWake == nil || resetWake.Sub(now) > NoResetIn:
+ d.NeedsPerson = NeedsNoReset
+ }
+ return d
+}
+
+// wakeUps are the times a held step may become runnable on its own: every
+// reset of every capable connection (limited ones included), and, when
+// the step has leave to spend and a capable metered connection exists,
+// the next budget day and month.
+func wakeUps(in Input) (resets, budget []time.Time) {
+ for _, c := range in.Conns {
+ if !c.Capable {
+ continue
+ }
+ if !c.LimitedUntil.IsZero() {
+ resets = append(resets, c.LimitedUntil)
+ }
+ for _, w := range c.Windows {
+ if w.ResetsAt != nil {
+ resets = append(resets, *w.ResetsAt)
+ }
+ }
+ if c.Billing == Metered && leave(in.Step) && budget == nil {
+ now := in.Now.UTC()
+ budget = []time.Time{
+ time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC),
+ time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC),
+ }
+ }
+ }
+ return resets, budget
+}
+
+// earliest is the earliest of ts strictly after now, or nil.
+func earliest(now time.Time, ts ...time.Time) *time.Time {
+ var at *time.Time
+ for _, t := range ts {
+ if !t.After(now) {
+ continue
+ }
+ if at == nil || t.Before(*at) {
+ t := t
+ at = &t
+ }
+ }
+ return at
+}
+
+func nonNil(t *time.Time) []time.Time {
+ if t == nil {
+ return nil
+ }
+ return []time.Time{*t}
+}
diff --git a/internal/schedule/schedule_test.go b/internal/schedule/schedule_test.go
new file mode 100644
index 00000000..ca754045
--- /dev/null
+++ b/internal/schedule/schedule_test.go
@@ -0,0 +1,404 @@
+package schedule
+
+import (
+ "fmt"
+ "math/rand/v2"
+ "reflect"
+ "slices"
+ "testing"
+ "time"
+)
+
+var t0 = time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)
+
+func at(d time.Duration) *time.Time { t := t0.Add(d); return &t }
+
+func sub(id, provider string, used ...float64) Conn {
+ c := Conn{ID: id, Provider: provider, Family: provider, Account: id, Billing: Subscription, Capable: true, State: StateHealthy}
+ for i, u := range used {
+ c.Windows = append(c.Windows, Window{Name: fmt.Sprintf("w%d", i), Used: u, Minutes: int64(300 * (i + 1)), ResetsAt: at(time.Duration(i+1) * time.Hour)})
+ }
+ return c
+}
+
+func meter(id string, day, month int64) Conn {
+ return Conn{ID: id, Provider: "tensorx", Family: "glm", Account: id, Billing: Metered, Capable: true, State: StateHealthy, SpendDay: day, SpendMonth: month, BudgetDay: 1_000_000, BudgetMonth: 10_000_000}
+}
+
+func in(step Step, cs ...Conn) Input {
+ if step.Role == "" {
+ step.Role = RoleEngineering
+ }
+ return Input{Version: Version, Now: t0, Step: step, Conns: cs}
+}
+
+// TestDecideRules is one table row per rule of §7 (and the bars).
+func TestDecideRules(t *testing.T) {
+ limited := sub("c-lim", "claude")
+ limited.State, limited.LimitedUntil = StateLimited, t0.Add(2*time.Hour)
+ passed := sub("c-back", "claude")
+ passed.State, passed.LimitedUntil = StateLimited, t0.Add(-time.Minute)
+ expired := sub("c-exp", "claude", 0.95)
+ expired.Windows[0].ResetsAt = at(-time.Minute)
+ busy := meter("t-busy", 0, 0)
+ busy.Busy = true
+ unknown := meter("t-unk", 0, 0)
+ unknown.SpendUnknown = true
+ refused := sub("c-ref", "claude")
+ refused.State = "sign_in_again"
+ cases := []struct {
+ name string
+ in Input
+ run bool
+ conn string
+ reason string
+ }{
+ // Bars.
+ {"not capable", in(Step{}, Conn{ID: "x", Billing: Subscription, State: StateHealthy}), false, "", ReasonNoConnection},
+ {"refused is not usable", in(Step{}, refused), false, "", ReasonNoConnection},
+ {"limited is not usable", in(Step{}, limited), false, "c-lim", ReasonHeadroom},
+ {"limited with its reset passed is usable", in(Step{}, passed), true, "c-back", ReasonHeadroom},
+ {"avoided", in(Step{Avoid: []string{"a"}}, sub("a", "claude"), sub("b", "codex")), true, "b", ReasonHeadroom},
+ // Thresholds.
+ {"low holds at 0.61", in(Step{Priority: Low}, sub("a", "claude", 0.61)), false, "a", ReasonHeadroom},
+ {"low runs at 0.59", in(Step{Priority: Low}, sub("a", "claude", 0.59)), true, "a", ReasonHeadroom},
+ {"normal holds at 0.80", in(Step{}, sub("a", "claude", 0.80)), false, "a", ReasonHeadroom},
+ {"normal runs at 0.79", in(Step{Priority: Normal}, sub("a", "claude", 0.79)), true, "a", ReasonHeadroom},
+ {"urgent runs at 0.99", in(Step{Priority: Urgent}, sub("a", "claude", 0.99)), true, "a", ReasonHeadroom},
+ {"urgent holds at 1.0", in(Step{Priority: Urgent}, sub("a", "claude", 1.0)), false, "a", ReasonHeadroom},
+ {"every window counts", in(Step{}, sub("a", "claude", 0.1, 0.85)), false, "a", ReasonHeadroom},
+ {"no window reported admits", in(Step{Priority: Low}, sub("a", "claude")), true, "a", ReasonHeadroom},
+ {"a window past its reset is not reported", in(Step{Priority: Low}, expired), true, "c-exp", ReasonHeadroom},
+ {"a release is urgent for thresholds", in(Step{Priority: Low, Release: "r1"}, sub("a", "claude", 0.9)), true, "a", ReasonHeadroom},
+ // Rule 1: the kept session.
+ {"kept stays whatever the threshold", in(Step{Kept: "a", Priority: Low}, sub("a", "claude", 0.95), sub("b", "codex")), true, "a", ReasonSticky},
+ {"kept not usable moves", in(Step{Kept: "c-lim"}, limited, sub("b", "codex")), true, "b", ReasonHeadroom},
+ {"kept avoided moves", in(Step{Kept: "a", Avoid: []string{"a"}}, sub("a", "claude"), sub("b", "codex")), true, "b", ReasonHeadroom},
+ {"kept metered with leave stays", in(Step{Kept: "t", Priority: Urgent}, meter("t", 0, 0), sub("b", "codex")), true, "t", ReasonSticky},
+ {"kept metered busy holds there", in(Step{Kept: "t-busy", Priority: Urgent}, busy, sub("b", "codex")), false, "t-busy", ReasonBusy},
+ {"kept metered over budget holds there", in(Step{Kept: "t", Release: "r"}, meter("t", 1_000_000, 0), sub("b", "codex")), false, "t", ReasonBudget},
+ {"kept metered spend unknown holds there", in(Step{Kept: "t-unk", Priority: Urgent}, unknown, sub("b", "codex")), false, "t-unk", ReasonSpendUnknown},
+ {"kept metered without leave moves", in(Step{Kept: "t"}, meter("t", 0, 0), sub("b", "codex")), true, "b", ReasonHeadroom},
+ // Rule 2: the preference.
+ {"preferred when it admits", Input{Now: t0, Step: Step{Role: RoleEngineering}, Conns: []Conn{sub("a", "claude", 0.5), sub("b", "codex", 0.1)}, Preference: Preference{Provider: "claude"}}, true, "a", ReasonPreference},
+ {"preferred over threshold is skipped", Input{Now: t0, Step: Step{Role: RoleEngineering}, Conns: []Conn{sub("a", "claude", 0.85), sub("b", "codex", 0.1)}, Preference: Preference{Provider: "claude"}}, true, "b", ReasonHeadroom},
+ {"an expired preference is absent", Input{Now: t0, Step: Step{Role: RoleEngineering}, Conns: []Conn{sub("a", "claude", 0.5), sub("b", "codex", 0.1)}, Preference: Preference{Provider: "claude", Until: at(-time.Second)}}, true, "b", ReasonHeadroom},
+ {"a preference in force", Input{Now: t0, Step: Step{Role: RoleEngineering}, Conns: []Conn{sub("a", "claude", 0.5), sub("b", "codex", 0.1)}, Preference: Preference{Provider: "claude", Until: at(time.Hour)}}, true, "a", ReasonPreference},
+ {"a metered preference never beats a subscription", Input{Now: t0, Step: Step{Role: RoleEngineering, Priority: Urgent}, Conns: []Conn{meter("t", 0, 0), sub("b", "codex", 0.9)}, Preference: Preference{Provider: "tensorx"}}, true, "b", ReasonHeadroom},
+ // Rule 3: the subscription with the most room.
+ {"reported before unreported", in(Step{}, sub("a", "claude"), sub("b", "codex", 0.7)), true, "b", ReasonHeadroom},
+ {"lowest largest used", in(Step{}, sub("a", "claude", 0.1, 0.5), sub("b", "codex", 0.4, 0.4)), true, "b", ReasonHeadroom},
+ {"then the first window", in(Step{}, sub("b", "claude", 0.3, 0.5), sub("a", "codex", 0.5, 0.2)), true, "b", ReasonHeadroom},
+ {"then the id", in(Step{}, sub("b", "claude", 0.5), sub("a", "codex", 0.5)), true, "a", ReasonHeadroom},
+ {"a subscription before metered", in(Step{Priority: Urgent}, meter("t", 0, 0), sub("b", "codex", 0.95)), true, "b", ReasonHeadroom},
+ // Rule 4: metered.
+ {"metered only with urgent", in(Step{Priority: Urgent}, meter("t", 0, 0)), true, "t", ReasonMeteredUrgent},
+ {"metered with a release", in(Step{Release: "r1"}, meter("t", 0, 0)), true, "t", ReasonMeteredRelease},
+ {"metered never for normal", in(Step{}, meter("t", 0, 0)), false, "", ReasonNoConnection},
+ {"metered never for low", in(Step{Priority: Low}, meter("t", 0, 0)), false, "", ReasonNoConnection},
+ {"metered most room", in(Step{Priority: Urgent}, meter("t2", 500_000, 0), meter("t1", 0, 6_000_000)), true, "t2", ReasonMeteredUrgent},
+ {"metered tie by id", in(Step{Priority: Urgent}, meter("t2", 0, 0), meter("t1", 0, 0)), true, "t1", ReasonMeteredUrgent},
+ {"metered at the day budget holds", in(Step{Priority: Urgent}, meter("t", 1_000_000, 0)), false, "t", ReasonBudget},
+ {"metered at the month budget holds", in(Step{Priority: Urgent}, meter("t", 0, 10_000_000)), false, "t", ReasonBudget},
+ {"metered spend unknown holds", in(Step{Priority: Urgent}, unknown), false, "t-unk", ReasonSpendUnknown},
+ {"metered busy holds", in(Step{Priority: Urgent}, busy), false, "t-busy", ReasonBusy},
+ {"a subscription over threshold, metered with leave", in(Step{Release: "r"}, sub("a", "claude", 1.0), meter("t", 0, 0)), true, "t", ReasonMeteredRelease},
+ // Rule 5: the hold names what it waits for.
+ {"nothing at all", in(Step{}), false, "", ReasonNoConnection},
+ {"headroom names the first reset", in(Step{}, sub("a", "claude", 0.9, 0.9), sub("b", "codex", 0.95)), false, "b", ReasonHeadroom},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ d := Decide(c.in)
+ if d.Run != c.run || d.Connection != c.conn || d.Reason != c.reason {
+ t.Fatalf("Decide = run %v %q %q, want run %v %q %q", d.Run, d.Connection, d.Reason, c.run, c.conn, c.reason)
+ }
+ })
+ }
+}
+
+// TestDecideReviewFamily: Review prefers another family, then another
+// account, then Engineering's own; a release never overrides the order.
+func TestDecideReviewFamily(t *testing.T) {
+ eng := &Engineer{ID: "a", Family: "claude", Account: "a"}
+ review := func(extra Step, cs ...Conn) Decision {
+ extra.Role, extra.Engineer = RoleReview, eng
+ return Decide(in(extra, cs...))
+ }
+ if d := review(Step{}, sub("a", "claude", 0.1), sub("b", "codex", 0.5)); d.Connection != "b" {
+ t.Fatalf("another family first: %+v", d)
+ }
+ if d := review(Step{}, sub("a", "claude", 0.1), sub("a2", "claude", 0.5)); d.Connection != "a2" {
+ t.Fatalf("another account next: %+v", d)
+ }
+ if d := review(Step{}, sub("a", "claude", 0.1)); d.Connection != "a" {
+ t.Fatalf("the same account last: %+v", d)
+ }
+ // Another family over threshold: the same family's other account
+ // reviews now rather than waiting.
+ if d := review(Step{}, sub("a", "claude", 0.1), sub("a2", "claude", 0.3), sub("b", "codex", 0.9)); d.Connection != "a2" {
+ t.Fatalf("other family held: %+v", d)
+ }
+ // Metered of another family with a release, before Engineering's own
+ // subscription.
+ if d := review(Step{Release: "r"}, sub("a", "claude", 0.1), meter("t", 0, 0)); d.Connection != "t" || d.Reason != ReasonMeteredRelease {
+ t.Fatalf("other family metered with a release: %+v", d)
+ }
+ if d := review(Step{}, sub("a", "claude", 0.1), meter("t", 0, 0)); d.Connection != "a" {
+ t.Fatalf("no leave: Engineering's own: %+v", d)
+ }
+}
+
+// TestDecideWakeUps: wake_at is the earliest time strictly after now
+// among the resets, the budget boundaries, the preference's end and the
+// deadline check; null when none.
+func TestDecideWakeUps(t *testing.T) {
+ a := sub("a", "claude", 0.9) // resets in 1h
+ lim := sub("l", "codex")
+ lim.State, lim.LimitedUntil = StateLimited, t0.Add(30*time.Minute)
+ d := Decide(in(Step{}, a, lim))
+ if d.Run || d.WakeAt == nil || !d.WakeAt.Equal(t0.Add(30*time.Minute)) {
+ t.Fatalf("a limited one's reset: %+v", d)
+ }
+ // The preference's end comes first.
+ i := in(Step{}, a)
+ i.Preference = Preference{Provider: "claude", Until: at(10 * time.Minute)}
+ if d := Decide(i); d.WakeAt == nil || !d.WakeAt.Equal(t0.Add(10*time.Minute)) {
+ t.Fatalf("the preference's end: %+v", d)
+ }
+ // The deadline check, unless it fired already.
+ by := t0.Add(24*time.Hour + 5*time.Minute)
+ if d := Decide(in(Step{By: &by}, a)); d.WakeAt == nil || !d.WakeAt.Equal(t0.Add(5*time.Minute)) {
+ t.Fatalf("the deadline check: %+v", d)
+ }
+ if d := Decide(in(Step{By: &by, DeadlineNotified: true}, a)); !d.WakeAt.Equal(t0.Add(time.Hour)) {
+ t.Fatalf("the deadline check fired already: %+v", d)
+ }
+ // The budget day boundary for a metered hold.
+ if d := Decide(in(Step{Priority: Urgent}, meter("t", 1_000_000, 0))); d.WakeAt == nil || !d.WakeAt.Equal(time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC)) {
+ t.Fatalf("the next budget day: %+v", d)
+ }
+ // Past times never wake: a reset that passed, a preference that ended.
+ old := sub("o", "claude", 0.9)
+ old.Windows[0].ResetsAt = at(-time.Hour)
+ old.Windows = append(old.Windows, Window{Name: "w9", Used: 0.95}, Window{Name: "w8", Used: 0.95, ResetsAt: at(0)})
+ i = in(Step{}, old)
+ i.Preference = Preference{Provider: "claude", Until: at(-time.Minute)}
+ if d := Decide(i); d.Run || d.WakeAt != nil {
+ t.Fatalf("no future wake-up: %+v", d)
+ }
+}
+
+// TestDecideNeedsYou: the deadline check, no reset in sight and
+// nothing that can run it ask the person; a reset in time does not.
+func TestDecideNeedsYou(t *testing.T) {
+ a := sub("a", "claude", 0.9)
+ if d := Decide(in(Step{}, a)); d.NeedsPerson != "" {
+ t.Fatalf("a reset in an hour asks nobody: %+v", d)
+ }
+ far := sub("f", "claude", 0.9)
+ far.Windows[0].ResetsAt = at(73 * time.Hour)
+ if d := Decide(in(Step{}, far)); d.NeedsPerson != NeedsNoReset {
+ t.Fatalf("a reset 73 h away: %+v", d)
+ }
+ none := sub("n", "claude", 0.9)
+ none.Windows[0].ResetsAt = nil
+ if d := Decide(in(Step{}, none)); d.NeedsPerson != NeedsNoReset || d.WakeAt != nil {
+ t.Fatalf("no reset reported: %+v", d)
+ }
+ if d := Decide(in(Step{})); d.NeedsPerson != NeedsNoConnection {
+ t.Fatalf("nothing connected: %+v", d)
+ }
+ by := t0.Add(23 * time.Hour)
+ if d := Decide(in(Step{By: &by}, a)); d.NeedsPerson != NeedsDeadline {
+ t.Fatalf("the deadline check: %+v", d)
+ }
+ if d := Decide(in(Step{By: &by, DeadlineNotified: true}, a)); d.NeedsPerson != "" {
+ t.Fatalf("the deadline check fired already: %+v", d)
+ }
+ busy := meter("t", 0, 0)
+ busy.Busy = true
+ if d := Decide(in(Step{Priority: Urgent}, busy)); d.NeedsPerson != "" {
+ t.Fatalf("a busy slot ends by itself: %+v", d)
+ }
+ unknown := meter("t", 0, 0)
+ unknown.SpendUnknown = true
+ if d := Decide(in(Step{Priority: Urgent}, unknown)); d.NeedsPerson != NeedsNoReset {
+ t.Fatalf("spend unknown waits for the person: %+v", d)
+ }
+}
+
+// randomInput is a random Input over a small, adversarial domain:
+// thresholds' edges, past and future resets, every bar.
+func randomInput(r *rand.Rand) Input {
+ pick := func(xs ...float64) float64 { return xs[r.IntN(len(xs))] }
+ dur := func() *time.Time {
+ switch r.IntN(4) {
+ case 0:
+ return nil
+ case 1:
+ return at(-time.Duration(r.IntN(120)) * time.Minute)
+ }
+ return at(time.Duration(r.IntN(100*60)) * time.Minute)
+ }
+ providers := []string{"claude", "codex", "tensorx"}
+ var cs []Conn
+ for i := range r.IntN(5) {
+ p := providers[r.IntN(len(providers))]
+ c := Conn{ID: fmt.Sprintf("c%d", i), Provider: p, Family: p, Account: fmt.Sprintf("acct%d", r.IntN(3)), Capable: r.IntN(6) > 0}
+ c.State = []string{StateHealthy, StateHealthy, StateLimited, "sign_in_again", ""}[r.IntN(5)]
+ if c.State == StateLimited {
+ if t := dur(); t != nil {
+ c.LimitedUntil = *t
+ }
+ }
+ if p == "tensorx" {
+ c.Billing = Metered
+ c.Busy, c.SpendUnknown = r.IntN(4) == 0, r.IntN(5) == 0
+ c.BudgetDay, c.BudgetMonth = 1_000_000, 10_000_000
+ c.SpendDay = int64(pick(0, 500_000, 999_999, 1_000_000, 2_000_000))
+ c.SpendMonth = int64(pick(0, 9_999_999, 10_000_000))
+ } else {
+ c.Billing = Subscription
+ for j := range r.IntN(3) {
+ c.Windows = append(c.Windows, Window{Name: fmt.Sprintf("w%d", j), Used: pick(0, 0.3, 0.59, 0.6, 0.61, 0.79, 0.8, 0.81, 0.99, 1.0), Minutes: int64(pick(0, 300, 10080)), ResetsAt: dur()})
+ }
+ }
+ cs = append(cs, c)
+ }
+ step := Step{Role: []string{RoleEngineering, RoleReview, RoleResearch}[r.IntN(3)], Priority: []string{"", Low, Normal, Urgent, "bogus"}[r.IntN(5)], DeadlineNotified: r.IntN(2) == 0}
+ if r.IntN(3) == 0 {
+ step.Release = "r1"
+ }
+ if r.IntN(2) == 0 {
+ step.By = dur()
+ }
+ if len(cs) > 0 && r.IntN(3) == 0 {
+ step.Kept = cs[r.IntN(len(cs))].ID
+ }
+ if len(cs) > 0 && r.IntN(3) == 0 {
+ step.Avoid = []string{cs[r.IntN(len(cs))].ID}
+ }
+ if step.Role == RoleReview && len(cs) > 0 {
+ e := cs[r.IntN(len(cs))]
+ step.Engineer = &Engineer{ID: e.ID, Family: e.Family, Account: e.Account}
+ }
+ pref := Preference{Provider: []string{"", "claude", "codex", "tensorx"}[r.IntN(4)]}
+ if r.IntN(2) == 0 {
+ pref.Until = dur()
+ }
+ return Input{Version: Version, Now: t0, Step: step, Conns: cs, Preference: pref}
+}
+
+func connOf(i Input, id string) (Conn, bool) {
+ for _, c := range i.Conns {
+ if c.ID == id {
+ return c, true
+ }
+ }
+ return Conn{}, false
+}
+
+// someAdmits reports whether any candidate passes every bar and its
+// threshold: rules 1 to 4 would yield it.
+func someAdmits(i Input) bool {
+ for _, c := range i.Conns {
+ if !eligible(c, i.Step, i.Now) {
+ continue
+ }
+ if c.Billing == Metered {
+ if leave(i.Step) && spendBar(c) == "" {
+ return true
+ }
+ continue
+ }
+ if Admits(c, Effective(i.Step), i.Now) || c.ID == i.Step.Kept {
+ return true
+ }
+ }
+ return false
+}
+
+// TestDecideInvariants are §7's invariants (a) to (f), and wake-ups
+// strictly in the future, over many random inputs.
+func TestDecideInvariants(t *testing.T) {
+ r := rand.New(rand.NewPCG(7, 13))
+ runs, holds := 0, 0
+ for n := range 20000 {
+ i := randomInput(r)
+ before := fmt.Sprintf("%#v", i)
+ d := Decide(i)
+ if fmt.Sprintf("%#v", i) != before {
+ t.Fatalf("#%d: Decide changed its input", n)
+ }
+ // (f) the same input, the same output.
+ if again := Decide(i); !reflect.DeepEqual(again, d) {
+ t.Fatalf("#%d: not deterministic: %+v then %+v", n, d, again)
+ }
+ if d.WakeAt != nil && !d.WakeAt.After(i.Now) {
+ t.Fatalf("#%d: a wake-up not after now: %v", n, d.WakeAt)
+ }
+ if !d.Run {
+ holds++
+ // (e) a hold only when rules 1 to 4 all fail. A kept metered
+ // session held by its spending bar is rule 1's hold.
+ if k, ok := connOf(i, i.Step.Kept); ok && k.Billing == Metered && eligible(k, i.Step, i.Now) && leave(i.Step) && spendBar(k) != "" {
+ continue
+ }
+ if someAdmits(i) {
+ t.Fatalf("#%d: held though a candidate admits: %+v\n%#v", n, d, i)
+ }
+ continue
+ }
+ runs++
+ c, ok := connOf(i, d.Connection)
+ if !ok {
+ t.Fatalf("#%d: ran on an unknown connection %q", n, d.Connection)
+ }
+ if !eligible(c, i.Step, i.Now) {
+ t.Fatalf("#%d: a bar passed: %+v on %#v", n, d, c)
+ }
+ if c.Billing == Metered {
+ // (b) no metered admission without urgent or a release.
+ if i.Step.Priority != Urgent && i.Step.Release == "" {
+ t.Fatalf("#%d: metered without leave: %+v", n, d)
+ }
+ // (c) never two attempts on one slot; (d) never at the budget
+ // or with the spend unknown.
+ if c.Busy || c.SpendUnknown || c.SpendDay >= c.BudgetDay || c.SpendMonth >= c.BudgetMonth {
+ t.Fatalf("#%d: metered admitted past its guard: %+v on %#v", n, d, c)
+ }
+ continue
+ }
+ // (a) no subscription admission at or above t(effective), except a
+ // kept session.
+ if d.Reason != ReasonSticky {
+ for _, w := range c.Windows {
+ if (w.ResetsAt == nil || i.Now.Before(*w.ResetsAt)) && w.Used >= Threshold(Effective(i.Step)) {
+ t.Fatalf("#%d: admitted at %.2f, threshold %.2f: %+v", n, w.Used, Threshold(Effective(i.Step)), d)
+ }
+ }
+ } else if c.ID != i.Step.Kept {
+ t.Fatalf("#%d: sticky on a connection that is not kept: %+v", n, d)
+ }
+ }
+ if runs < 1000 || holds < 1000 {
+ t.Fatalf("the generator is lopsided: %d runs, %d holds", runs, holds)
+ }
+}
+
+// TestDecideOrderFree: the order the connections are listed in never
+// changes the decision (the precedence is total).
+func TestDecideOrderFree(t *testing.T) {
+ r := rand.New(rand.NewPCG(3, 5))
+ for n := range 5000 {
+ i := randomInput(r)
+ d := Decide(i)
+ j := i
+ j.Conns = slices.Clone(i.Conns)
+ r.Shuffle(len(j.Conns), func(a, b int) { j.Conns[a], j.Conns[b] = j.Conns[b], j.Conns[a] })
+ if e := Decide(j); !reflect.DeepEqual(e, d) {
+ t.Fatalf("#%d: order changed the decision: %+v then %+v", n, d, e)
+ }
+ }
+}