// 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 = 2 // 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; KeptModel the model that // session was created on (§16.5), for a metered one. Kept string KeptModel 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 // Housekeeping: the attempt was dispatched by housekeeping. It counts // as low and never spends, whatever its task's priority or a release. Housekeeping bool // Engineer is what Engineering ran on, for Review's family rule (a // Research step names the coordinator's connection the same way: it // reads pages on another family first). Engineer *Engineer } // Engineer names the connection Engineering ran on. type Engineer struct { Families []string 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 // Models are a metered connection's eligible models (§16.3): allowed, // priced and tiered, and not unhealthy (an unhealthy one a day after // it failed counts, unprobed, as a retry on demand). A metered // connection with none takes nothing. Models []Model } // Model is one eligible model on a metered connection (§16.3): its // family and tier from Equipo's tier table, its output and input prices // (micro-units per million tokens) for the tie rule, and Unprobed when // it must be probed before a step runs on it (§16.4). type Model struct { ID string Family string Tier string Output int64 Input int64 Unprobed bool } // Tiers (§16.2), lowest first. const ( TierCheap = "cheap" TierStandard = "standard" TierStrong = "strong" ) // Fill thresholds (§16.3): a connection's fill is the larger of its // day's and its month's reported spend over budget; below FillStrong the // tier cap is strong, below FillStandard standard, else cheap. const ( FillStrong = 0.5 FillStandard = 0.8 ) func tierRank(t string) int { switch t { case TierCheap: return 1 case TierStandard: return 2 case TierStrong: return 3 } return 0 } // TierCap is the highest tier c's fill allows (§16.3). func TierCap(c Conn) string { switch f := spentFraction(c); { case f < FillStrong: return TierStrong case f < FillStandard: return TierStandard } return TierCheap } // PickModel is the model for a role on one connection (§16.3): the // highest tier at or below the cap; if none is, the lowest tier present. // Within a tier the lower output price, then the lower input price, then // the id bytewise. A higher fill never yields a higher tier. func PickModel(models []Model, cap string) (Model, bool) { if len(models) == 0 { return Model{}, false } limit := tierRank(cap) under := false for _, m := range models { under = under || tierRank(m.Tier) <= limit } best, found := Model{}, false for _, m := range models { r := tierRank(m.Tier) if under && r > limit { continue } switch { case !found: best, found = m, true case under && r > tierRank(best.Tier), !under && r < tierRank(best.Tier): best = m case r == tierRank(best.Tier) && cheaper(m, best): best = m } } return best, found } // cheaper is the tie rule within a tier. func cheaper(a, b Model) bool { if a.Output != b.Output { return a.Output < b.Output } if a.Input != b.Input { return a.Input < b.Input } return bytes.Compare([]byte(a.ID), []byte(b.ID)) < 0 } func modelByID(ms []Model, id string) (Model, bool) { for _, m := range ms { if m.ID == id { return m, true } } return Model{}, false } // 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 // Model is the model a metered connection runs the step on (§16.3), // Unprobed when it must be probed first (§16.4); "" on a // subscription. Family is the pair's family (the connection's for a // subscription). Model string Family string Tier string Unprobed bool 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.Housekeeping { return Low } 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.Housekeeping && (s.Priority == Urgent || s.Release != "") } // eligible are the bars every candidate passes, Run now included: capable, // usable, not avoided, and for a metered connection some model it may // run (§16.3). func eligible(c Conn, s Step, now time.Time) bool { return c.Capable && Usable(c, now) && !slices.Contains(s.Avoid, c.ID) && (c.Billing != Metered || len(c.Models) > 0) } // 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 { if in.Step.Role == "copy" { in = copyInput(in) } 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, d.Family = true, c.ID, ReasonSticky, c.Family return d } // A kept metered session stays on its own model while that is // allowed and not unhealthy (§16.3); otherwise it is not kept. m, ok := modelByID(c.Models, s.KeptModel) if !leave(s) || !ok || m.Unprobed { break } if bar := spendBar(c); bar != "" { return hold(in, eff, bar, c) } d.Run, d.Connection, d.Reason = true, c.ID, ReasonSticky d.Model, d.Family, d.Tier = m.ID, m.Family, m.Tier return d } } for _, group := range groups(in) { if c, m, reason, ok := pick(in, eff, pref, group); ok { d.Run, d.Connection, d.Reason = true, c.ID, reason d.Family = c.Family if c.Billing == Metered { d.Model, d.Family, d.Tier, d.Unprobed = m.ID, m.Family, m.Tier, m.Unprobed } return d } } return holdFor(in, eff) } // groups are the candidate sets the family rule tries in order, over // (connection, model) pairs (rev 3.3 §16.3): pairs of another family // than Engineering's recorded one, then pairs of the same family. A // metered connection joins a group with only its models of that family. // Within each group §7's order applies; another connection than // Engineering's wins only at equal rank (pick's tie rule). A step that // names no Engineer has one group. func groups(in Input) [][]Conn { e := in.Step.Engineer if e == nil { return [][]Conn{in.Conns} } var other, same []Conn for _, c := range in.Conns { if c.Billing != Metered { if c.Family == e.Family || slices.Contains(e.Families, c.Family) { same = append(same, c) } else { other = append(other, c) } continue } var o, m []Model for _, x := range c.Models { if x.Family == e.Family || slices.Contains(e.Families, x.Family) { m = append(m, x) } else { o = append(o, x) } } if len(o) > 0 { cc := c cc.Models = o other = append(other, cc) } if len(m) > 0 { cc := c cc.Models = m same = append(same, cc) } } return [][]Conn{other, same} } // elsewhere are a rule's candidates for Review with Engineering's own // connection left out while another remains (§16.3: at equal rank, // another connection; the rank is the rule that yields them, so room // orders only what is left). Any other step's are all of them. func elsewhere(cs []Conn, s Step) []Conn { e := engineerID(s) if e == "" { return cs } out := slices.DeleteFunc(slices.Clone(cs), func(c Conn) bool { return c.ID == e }) if len(out) == 0 { return cs } return out } // engineerID is the connection Review's tie rule ranks after another at // equal rank ("" when the step names no Engineer). func engineerID(s Step) string { if s.Engineer == nil { return "" } return s.Engineer.ID } // pick applies rules 2 to 4 to one group: the connection, and on a // metered one its model (PickModel under its fill's cap). func pick(in Input, eff string, pref Preference, cs []Conn) (Conn, Model, 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(elsewhere(mine, s), now, engineerID(s)), Model{}, ReasonPreference, true } } // 3. The subscription with the most room. if len(subs) > 0 { return roomiest(elsewhere(subs, s), now, engineerID(s)), Model{}, 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 } c := meteredRoomiest(elsewhere(mine, s), engineerID(s)) m, _ := PickModel(c.Models, TierCap(c)) return c, m, reason, true } return Conn{}, Model{}, "", 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, engineer string) Conn { best := cs[0] for _, c := range cs[1:] { if lessRoom(c, best, now, engineer) { best = c } } return best } // lessRoom reports whether a has more room than b (sorts before it). func lessRoom(a, b Conn, now time.Time, engineer string) 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 lessTie(a, b, engineer) } // lessTie is the tie rule at equal rank: for Review another connection // than Engineering's first (§16.3), then the id bytewise. func lessTie(a, b Conn, engineer string) bool { if engineer != "" && (a.ID == engineer) != (b.ID == engineer) { return b.ID == engineer } 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, engineer string) Conn { best := cs[0] for _, c := range cs[1:] { fc, fb := spentFraction(c), spentFraction(best) if fc < fb || fc == fb && lessTie(c, best, engineer) { 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} } // DecidePinned is Run now's leave pinned to one connection (paused work, // 2026-11-24): the person was told it would run on pin, so it runs there // or nowhere. Decide reads only that connection, with the release's leave; // a kept session on another connection is not kept, and the bars (usable, // avoided, a metered connection's spend, budget and slot) still apply. // Every other rule of Decide is unchanged. func DecidePinned(in Input, pin string) Decision { var only []Conn for _, c := range in.Conns { if c.ID == pin { only = append(only, c) } } in.Conns = only if in.Step.Kept != pin { in.Step.Kept, in.Step.KeptModel = "", "" } if in.Step.Release == "" { in.Step.Release = "pinned" } return Decide(in) }