oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package schedule is the scheduler's one decision (connectors spec
2// 2026-11-12 rev 3.1, §7): Decide starts or holds a step from the
3// readings taken at admission. It is pure: no clock, no I/O, no state.
4// The runner refreshes stale readings before it calls Decide, writes the
5// admission in one thin.db transaction that rechecks what Decide read,
6// and persists a hold with its wake-up.
7//
8// What it claims: admission is decided from the readings taken at
9// admission. It does not predict or reserve a step's consumption, and
10// several steps admitted against one reading may together run a window
11// out; the reserve thresholds are the margin, and a window that runs out
12// mid-step is quota failover, as before.
13package schedule
14
15import (
16 "bytes"
17 "slices"
18 "sort"
19 "time"
20)
21
22// Version is the Input's version: a change to its meaning bumps it.
23const Version = 2
24
25// Priorities (§6). An unknown or empty priority is normal.
26const (
27 Urgent = "urgent"
28 Normal = "normal"
29 Low = "low"
30)
31
32// Billing of a connection (§2.1).
33const (
34 Subscription = "subscription"
35 Metered = "metered"
36)
37
38// Roles a step runs (connect.Role*). Review has the family rule.
39const (
40 RoleEngineering = "engineering"
41 RoleReview = "review"
42 RoleResearch = "research"
43)
44
45// Connection states Decide reads (wire.Conn*).
46const (
47 StateHealthy = "healthy"
48 StateLimited = "limited"
49)
50
51// Reasons a decision is recorded with (§7, §10). The first five start a
52// step; the last five hold it.
53const (
54 ReasonSticky = "sticky"
55 ReasonPreference = "preference"
56 ReasonHeadroom = "headroom"
57 ReasonMeteredUrgent = "metered_urgent"
58 ReasonMeteredRelease = "metered_release"
59
60 // A hold's reasons: headroom (above), budget, spend unknown, the
61 // metered connection's one slot taken (a kept session held on it),
62 // and nothing that can run it.
63 ReasonBudget = "budget"
64 ReasonSpendUnknown = "spend_unknown"
65 ReasonBusy = "busy"
66 ReasonNoConnection = "no_connection"
67)
68
69// What a hold needs from the person (§8): the deadline check fired, no
70// reset in sight, or nothing can run it.
71const (
72 NeedsDeadline = "deadline"
73 NeedsNoReset = "no_reset"
74 NeedsNoConnection = "no_connection"
75)
76
77// Thresholds (§0 decision 6): a subscription admits a step at priority p
78// while every reported window is below t(p).
79const (
80 ThresholdLow = 0.60
81 ThresholdNormal = 0.80
82 ThresholdUrgent = 1.0
83)
84
85// Deadline is how long before `by` the deadline check fires; NoResetIn
86// how far away a reset may be before the person is asked.
87const (
88 Deadline = 24 * time.Hour
89 NoResetIn = 72 * time.Hour
90)
91
92// Input is everything Decide reads. It is a value: Decide never changes
93// it.
94type Input struct {
95 Version int
96 Now time.Time
97 Step Step
98 Conns []Conn
99 Preference Preference
100}
101
102// Step is the step being admitted.
103type Step struct {
104 Role string
105 Priority string
106 // By is the task's deadline, if any; DeadlineNotified records that
107 // the deadline check already fired for this step.
108 By *time.Time
109 DeadlineNotified bool
110 // Kept is the connection whose session the step resumes (a fix round
111 // on its Engineering session), "" for none; KeptModel the model that
112 // session was created on (§16.5), for a metered one.
113 Kept string
114 KeptModel string
115 // Avoid are connections this attempt must not use (failover).
116 Avoid []string
117 // Release is the Run now grant the step carries ("" for none).
118 Release string
119 // Housekeeping: the attempt was dispatched by housekeeping. It counts
120 // as low and never spends, whatever its task's priority or a release.
121 Housekeeping bool
122 // Engineer is what Engineering ran on, for Review's family rule (a
123 // Research step names the coordinator's connection the same way: it
124 // reads pages on another family first).
125 Engineer *Engineer
126}
127
128// Engineer names the connection Engineering ran on.
129type Engineer struct {
130 Families []string
131 ID, Family, Account string
132}
133
134// Conn is one of the person's connections on this runner with the facts
135// of §6.
136type Conn struct {
137 ID string
138 Provider string
139 Family string
140 Account string
141 Billing string
142 // Capable: the harness can run the step's role here.
143 Capable bool
144 State string
145 // LimitedUntil is a limited connection's reset (zero: none known).
146 LimitedUntil time.Time
147 // Windows are the reported windows, as last read.
148 Windows []Window
149 // A metered connection's facts: another attempt holds its slot, its
150 // spend is unknown, its reported spend and its budget, both in the
151 // price table's micro-units, for today and this month.
152 Busy bool
153 SpendUnknown bool
154 SpendDay int64
155 SpendMonth int64
156 BudgetDay int64
157 BudgetMonth int64
158 // Models are a metered connection's eligible models (§16.3): allowed,
159 // priced and tiered, and not unhealthy (an unhealthy one a day after
160 // it failed counts, unprobed, as a retry on demand). A metered
161 // connection with none takes nothing.
162 Models []Model
163}
164
165// Model is one eligible model on a metered connection (§16.3): its
166// family and tier from Equipo's tier table, its output and input prices
167// (micro-units per million tokens) for the tie rule, and Unprobed when
168// it must be probed before a step runs on it (§16.4).
169type Model struct {
170 ID string
171 Family string
172 Tier string
173 Output int64
174 Input int64
175 Unprobed bool
176}
177
178// Tiers (§16.2), lowest first.
179const (
180 TierCheap = "cheap"
181 TierStandard = "standard"
182 TierStrong = "strong"
183)
184
185// Fill thresholds (§16.3): a connection's fill is the larger of its
186// day's and its month's reported spend over budget; below FillStrong the
187// tier cap is strong, below FillStandard standard, else cheap.
188const (
189 FillStrong = 0.5
190 FillStandard = 0.8
191)
192
193func tierRank(t string) int {
194 switch t {
195 case TierCheap:
196 return 1
197 case TierStandard:
198 return 2
199 case TierStrong:
200 return 3
201 }
202 return 0
203}
204
205// TierCap is the highest tier c's fill allows (§16.3).
206func TierCap(c Conn) string {
207 switch f := spentFraction(c); {
208 case f < FillStrong:
209 return TierStrong
210 case f < FillStandard:
211 return TierStandard
212 }
213 return TierCheap
214}
215
216// PickModel is the model for a role on one connection (§16.3): the
217// highest tier at or below the cap; if none is, the lowest tier present.
218// Within a tier the lower output price, then the lower input price, then
219// the id bytewise. A higher fill never yields a higher tier.
220func PickModel(models []Model, cap string) (Model, bool) {
221 if len(models) == 0 {
222 return Model{}, false
223 }
224 limit := tierRank(cap)
225 under := false
226 for _, m := range models {
227 under = under || tierRank(m.Tier) <= limit
228 }
229 best, found := Model{}, false
230 for _, m := range models {
231 r := tierRank(m.Tier)
232 if under && r > limit {
233 continue
234 }
235 switch {
236 case !found:
237 best, found = m, true
238 case under && r > tierRank(best.Tier), !under && r < tierRank(best.Tier):
239 best = m
240 case r == tierRank(best.Tier) && cheaper(m, best):
241 best = m
242 }
243 }
244 return best, found
245}
246
247// cheaper is the tie rule within a tier.
248func cheaper(a, b Model) bool {
249 if a.Output != b.Output {
250 return a.Output < b.Output
251 }
252 if a.Input != b.Input {
253 return a.Input < b.Input
254 }
255 return bytes.Compare([]byte(a.ID), []byte(b.ID)) < 0
256}
257
258func modelByID(ms []Model, id string) (Model, bool) {
259 for _, m := range ms {
260 if m.ID == id {
261 return m, true
262 }
263 }
264 return Model{}, false
265}
266
267// Window is one reported window: Used from 0 to 1.
268type Window struct {
269 Name string
270 Used float64
271 Minutes int64
272 ResetsAt *time.Time
273}
274
275// Preference is the person's preferred provider and until when ("" for
276// Automatic; Until nil for no end).
277type Preference struct {
278 Provider string
279 Until *time.Time
280}
281
282// Decision is Decide's answer. Run: Connection and Reason. Hold: Reason,
283// the Connection it names (or ""), ResetsAt when that one reported a
284// reset, WakeAt (strictly after now, or nil) and NeedsPerson.
285type Decision struct {
286 Run bool
287 Connection string
288 // Model is the model a metered connection runs the step on (§16.3),
289 // Unprobed when it must be probed first (§16.4); "" on a
290 // subscription. Family is the pair's family (the connection's for a
291 // subscription).
292 Model string
293 Family string
294 Tier string
295 Unprobed bool
296 Reason string
297 ResetsAt *time.Time
298 WakeAt *time.Time
299 NeedsPerson string
300 // Effective is the priority the thresholds used: urgent with a
301 // release.
302 Effective string
303}
304
305// Effective is a step's effective priority: urgent with a release,
306// else its own (normal when unset or unknown).
307func Effective(s Step) string {
308 if s.Housekeeping {
309 return Low
310 }
311 if s.Release != "" {
312 return Urgent
313 }
314 switch s.Priority {
315 case Urgent, Low:
316 return s.Priority
317 }
318 return Normal
319}
320
321// Threshold is t(p).
322func Threshold(p string) float64 {
323 switch p {
324 case Urgent:
325 return ThresholdUrgent
326 case Low:
327 return ThresholdLow
328 }
329 return ThresholdNormal
330}
331
332// Usable reports whether c may run at now (rev 3 §2.7): healthy, or
333// limited with its reset passed.
334func Usable(c Conn, now time.Time) bool {
335 switch c.State {
336 case StateHealthy:
337 return true
338 case StateLimited:
339 return !c.LimitedUntil.IsZero() && !now.Before(c.LimitedUntil)
340 }
341 return false
342}
343
344// reported are c's windows that still count at now: one whose reset has
345// passed with no newer reading counts as not reported.
346func reported(c Conn, now time.Time) []Window {
347 var out []Window
348 for _, w := range c.Windows {
349 if w.ResetsAt != nil && !now.Before(*w.ResetsAt) {
350 continue
351 }
352 out = append(out, w)
353 }
354 return out
355}
356
357// Admits reports whether subscription c admits a step at effective
358// priority p: every reported window below t(p).
359func Admits(c Conn, p string, now time.Time) bool {
360 t := Threshold(p)
361 for _, w := range reported(c, now) {
362 if w.Used >= t {
363 return false
364 }
365 }
366 return true
367}
368
369// spendBar is why a metered connection cannot take a step with leave to
370// spend ("" when it can): the slot, the spend, the budget.
371func spendBar(c Conn) string {
372 switch {
373 case c.SpendUnknown:
374 return ReasonSpendUnknown
375 case c.SpendDay >= c.BudgetDay || c.SpendMonth >= c.BudgetMonth:
376 return ReasonBudget
377 case c.Busy:
378 return ReasonBusy
379 }
380 return ""
381}
382
383// leave is the step's leave to spend metered money (§0 decision 5).
384func leave(s Step) bool { return !s.Housekeeping && (s.Priority == Urgent || s.Release != "") }
385
386// eligible are the bars every candidate passes, Run now included: capable,
387// usable, not avoided, and for a metered connection some model it may
388// run (§16.3).
389func eligible(c Conn, s Step, now time.Time) bool {
390 return c.Capable && Usable(c, now) && !slices.Contains(s.Avoid, c.ID) && (c.Billing != Metered || len(c.Models) > 0)
391}
392
393// Decide starts or holds the step (§7). Bars are never overridden; the
394// first rule that yields a connection wins: the kept session, the
395// preference, the subscription with the most room, the metered
396// connection with the most room; else a hold.
397func Decide(in Input) Decision {
398 if in.Step.Role == "copy" {
399 in = copyInput(in)
400 }
401 now, s := in.Now, in.Step
402 eff := Effective(s)
403 pref := in.Preference
404 if pref.Until != nil && !now.Before(*pref.Until) {
405 // An expired preference is treated as absent.
406 pref = Preference{}
407 }
408 d := Decision{Effective: eff}
409 // 1. The kept session stays while it is usable; a spending bar holds
410 // it there. Without leave to spend a kept metered session is not
411 // kept: the step starts afresh elsewhere (decision 5).
412 if s.Kept != "" {
413 for _, c := range in.Conns {
414 if c.ID != s.Kept || !eligible(c, s, now) {
415 continue
416 }
417 if c.Billing != Metered {
418 d.Run, d.Connection, d.Reason, d.Family = true, c.ID, ReasonSticky, c.Family
419 return d
420 }
421 // A kept metered session stays on its own model while that is
422 // allowed and not unhealthy (§16.3); otherwise it is not kept.
423 m, ok := modelByID(c.Models, s.KeptModel)
424 if !leave(s) || !ok || m.Unprobed {
425 break
426 }
427 if bar := spendBar(c); bar != "" {
428 return hold(in, eff, bar, c)
429 }
430 d.Run, d.Connection, d.Reason = true, c.ID, ReasonSticky
431 d.Model, d.Family, d.Tier = m.ID, m.Family, m.Tier
432 return d
433 }
434 }
435 for _, group := range groups(in) {
436 if c, m, reason, ok := pick(in, eff, pref, group); ok {
437 d.Run, d.Connection, d.Reason = true, c.ID, reason
438 d.Family = c.Family
439 if c.Billing == Metered {
440 d.Model, d.Family, d.Tier, d.Unprobed = m.ID, m.Family, m.Tier, m.Unprobed
441 }
442 return d
443 }
444 }
445 return holdFor(in, eff)
446}
447
448// groups are the candidate sets the family rule tries in order, over
449// (connection, model) pairs (rev 3.3 §16.3): pairs of another family
450// than Engineering's recorded one, then pairs of the same family. A
451// metered connection joins a group with only its models of that family.
452// Within each group §7's order applies; another connection than
453// Engineering's wins only at equal rank (pick's tie rule). A step that
454// names no Engineer has one group.
455func groups(in Input) [][]Conn {
456 e := in.Step.Engineer
457 if e == nil {
458 return [][]Conn{in.Conns}
459 }
460 var other, same []Conn
461 for _, c := range in.Conns {
462 if c.Billing != Metered {
463 if c.Family == e.Family || slices.Contains(e.Families, c.Family) {
464 same = append(same, c)
465 } else {
466 other = append(other, c)
467 }
468 continue
469 }
470 var o, m []Model
471 for _, x := range c.Models {
472 if x.Family == e.Family || slices.Contains(e.Families, x.Family) {
473 m = append(m, x)
474 } else {
475 o = append(o, x)
476 }
477 }
478 if len(o) > 0 {
479 cc := c
480 cc.Models = o
481 other = append(other, cc)
482 }
483 if len(m) > 0 {
484 cc := c
485 cc.Models = m
486 same = append(same, cc)
487 }
488 }
489 return [][]Conn{other, same}
490}
491
492// elsewhere are a rule's candidates for Review with Engineering's own
493// connection left out while another remains (§16.3: at equal rank,
494// another connection; the rank is the rule that yields them, so room
495// orders only what is left). Any other step's are all of them.
496func elsewhere(cs []Conn, s Step) []Conn {
497 e := engineerID(s)
498 if e == "" {
499 return cs
500 }
501 out := slices.DeleteFunc(slices.Clone(cs), func(c Conn) bool { return c.ID == e })
502 if len(out) == 0 {
503 return cs
504 }
505 return out
506}
507
508// engineerID is the connection Review's tie rule ranks after another at
509// equal rank ("" when the step names no Engineer).
510func engineerID(s Step) string {
511 if s.Engineer == nil {
512 return ""
513 }
514 return s.Engineer.ID
515}
516
517// pick applies rules 2 to 4 to one group: the connection, and on a
518// metered one its model (PickModel under its fill's cap).
519func pick(in Input, eff string, pref Preference, cs []Conn) (Conn, Model, string, bool) {
520 now, s := in.Now, in.Step
521 var subs, metered []Conn
522 for _, c := range cs {
523 if !eligible(c, s, now) {
524 continue
525 }
526 if c.Billing == Metered {
527 if leave(s) && spendBar(c) == "" {
528 metered = append(metered, c)
529 }
530 continue
531 }
532 if Admits(c, eff, now) {
533 subs = append(subs, c)
534 }
535 }
536 // 2. The preferred provider, if it admits the step (subscriptions:
537 // a preference never puts a metered connection before one).
538 if pref.Provider != "" {
539 var mine []Conn
540 for _, c := range subs {
541 if c.Provider == pref.Provider {
542 mine = append(mine, c)
543 }
544 }
545 if len(mine) > 0 {
546 return roomiest(elsewhere(mine, s), now, engineerID(s)), Model{}, ReasonPreference, true
547 }
548 }
549 // 3. The subscription with the most room.
550 if len(subs) > 0 {
551 return roomiest(elsewhere(subs, s), now, engineerID(s)), Model{}, ReasonHeadroom, true
552 }
553 // 4. The metered connection with the most room; a preferred one first.
554 if len(metered) > 0 {
555 var mine []Conn
556 for _, c := range metered {
557 if c.Provider == pref.Provider {
558 mine = append(mine, c)
559 }
560 }
561 if len(mine) == 0 {
562 mine = metered
563 }
564 reason := ReasonMeteredRelease
565 if s.Priority == Urgent {
566 reason = ReasonMeteredUrgent
567 }
568 c := meteredRoomiest(elsewhere(mine, s), engineerID(s))
569 m, _ := PickModel(c.Models, TierCap(c))
570 return c, m, reason, true
571 }
572 return Conn{}, Model{}, "", false
573}
574
575// roomiest is the subscription with the most room (§7, fixed
576// precedence): connections with a reported window first; then the
577// lowest largest used; then the used of the first window by minutes
578// (missing last) then name; then the id bytewise.
579func roomiest(cs []Conn, now time.Time, engineer string) Conn {
580 best := cs[0]
581 for _, c := range cs[1:] {
582 if lessRoom(c, best, now, engineer) {
583 best = c
584 }
585 }
586 return best
587}
588
589// lessRoom reports whether a has more room than b (sorts before it).
590func lessRoom(a, b Conn, now time.Time, engineer string) bool {
591 wa, wb := reported(a, now), reported(b, now)
592 if (len(wa) > 0) != (len(wb) > 0) {
593 return len(wa) > 0
594 }
595 if len(wa) > 0 {
596 if ma, mb := maxUsed(wa), maxUsed(wb); ma != mb {
597 return ma < mb
598 }
599 if fa, fb := first(wa).Used, first(wb).Used; fa != fb {
600 return fa < fb
601 }
602 }
603 return lessTie(a, b, engineer)
604}
605
606// lessTie is the tie rule at equal rank: for Review another connection
607// than Engineering's first (§16.3), then the id bytewise.
608func lessTie(a, b Conn, engineer string) bool {
609 if engineer != "" && (a.ID == engineer) != (b.ID == engineer) {
610 return b.ID == engineer
611 }
612 return bytes.Compare([]byte(a.ID), []byte(b.ID)) < 0
613}
614
615func maxUsed(ws []Window) float64 {
616 m := ws[0].Used
617 for _, w := range ws[1:] {
618 m = max(m, w.Used)
619 }
620 return m
621}
622
623// first is the window sorted first by minutes ascending (missing, zero,
624// last), then by name.
625func first(ws []Window) Window {
626 sorted := slices.Clone(ws)
627 sort.SliceStable(sorted, func(i, j int) bool {
628 a, b := sorted[i], sorted[j]
629 if (a.Minutes > 0) != (b.Minutes > 0) {
630 return a.Minutes > 0
631 }
632 if a.Minutes != b.Minutes {
633 return a.Minutes < b.Minutes
634 }
635 return a.Name < b.Name
636 })
637 return sorted[0]
638}
639
640// meteredRoomiest is the metered connection with the most room: the
641// lower larger fraction of day and month spend over budget, then the id.
642func meteredRoomiest(cs []Conn, engineer string) Conn {
643 best := cs[0]
644 for _, c := range cs[1:] {
645 fc, fb := spentFraction(c), spentFraction(best)
646 if fc < fb || fc == fb && lessTie(c, best, engineer) {
647 best = c
648 }
649 }
650 return best
651}
652
653func spentFraction(c Conn) float64 {
654 frac := func(spent, budget int64) float64 {
655 if budget <= 0 {
656 return 1
657 }
658 return float64(spent) / float64(budget)
659 }
660 return max(frac(c.SpendDay, c.BudgetDay), frac(c.SpendMonth, c.BudgetMonth))
661}
662
663// holdFor is rule 5: why nothing can run the step now, naming the
664// connection it waits for.
665func holdFor(in Input, eff string) Decision {
666 now, s := in.Now, in.Step
667 // A metered connection with leave, held by a spending bar: the most
668 // actionable bar first (spend unknown, then the budget, then a busy
669 // slot), the lowest id among equals.
670 if leave(s) {
671 var named *Conn
672 rank := map[string]int{ReasonSpendUnknown: 0, ReasonBudget: 1, ReasonBusy: 2}
673 for i, c := range in.Conns {
674 if c.Billing != Metered || !eligible(c, s, now) {
675 continue
676 }
677 bar := spendBar(c)
678 if bar == "" {
679 continue
680 }
681 if named == nil || rank[bar] < rank[spendBar(*named)] || rank[bar] == rank[spendBar(*named)] && c.ID < named.ID {
682 named = &in.Conns[i]
683 }
684 }
685 // A subscription waiting for headroom is named before a spending
686 // bar only when nothing metered is in reach.
687 if named != nil {
688 return hold(in, eff, spendBar(*named), *named)
689 }
690 }
691 // Waiting for headroom: the capable subscription (not avoided) whose
692 // reset comes first, over threshold or limited.
693 var named *Conn
694 var at time.Time
695 for i, c := range in.Conns {
696 if !c.Capable || c.Billing == Metered || slices.Contains(s.Avoid, c.ID) {
697 continue
698 }
699 if c.State != StateHealthy && c.State != StateLimited {
700 continue
701 }
702 r := resetOf(c, eff, now)
703 switch {
704 case named == nil:
705 named, at = &in.Conns[i], r
706 case !r.IsZero() && (at.IsZero() || r.Before(at) || r.Equal(at) && c.ID < named.ID):
707 named, at = &in.Conns[i], r
708 case r.IsZero() && at.IsZero() && c.ID < named.ID:
709 named = &in.Conns[i]
710 }
711 }
712 if named != nil {
713 d := hold(in, eff, ReasonHeadroom, *named)
714 if !at.IsZero() {
715 d.ResetsAt = &at
716 }
717 return d
718 }
719 return hold(in, eff, ReasonNoConnection, Conn{})
720}
721
722// resetOf is when subscription c may admit a step at p again: its
723// limit's reset, else the latest reset among the windows over t(p). Zero
724// when it reported none.
725func resetOf(c Conn, p string, now time.Time) time.Time {
726 if c.State == StateLimited && !Usable(c, now) {
727 return c.LimitedUntil
728 }
729 var at time.Time
730 t := Threshold(p)
731 for _, w := range reported(c, now) {
732 if w.Used < t {
733 continue
734 }
735 if w.ResetsAt == nil {
736 return time.Time{}
737 }
738 if w.ResetsAt.After(at) {
739 at = *w.ResetsAt
740 }
741 }
742 return at
743}
744
745// hold is a held decision: the reason, the connection it names, the
746// wake-up and what it needs from the person.
747func hold(in Input, eff, reason string, named Conn) Decision {
748 now, s := in.Now, in.Step
749 d := Decision{Reason: reason, Connection: named.ID, Effective: eff}
750 resets, budgetAt := wakeUps(in)
751 wake := earliest(now, append(slices.Clone(resets), budgetAt...)...)
752 if pu := in.Preference.Until; pu != nil {
753 wake = earliest(now, append(nonNil(wake), *pu)...)
754 }
755 if s.By != nil && !s.DeadlineNotified {
756 wake = earliest(now, append(nonNil(wake), s.By.Add(-Deadline))...)
757 }
758 d.WakeAt = wake
759 // What the person can change, in order: the deadline is near, nothing
760 // can run it, no reset in sight.
761 resetWake := earliest(now, resets...)
762 if reason == ReasonBudget {
763 resetWake = earliest(now, append(slices.Clone(resets), budgetAt...)...)
764 }
765 switch {
766 case s.By != nil && !s.DeadlineNotified && !now.Before(s.By.Add(-Deadline)):
767 d.NeedsPerson = NeedsDeadline
768 case reason == ReasonNoConnection:
769 d.NeedsPerson = NeedsNoConnection
770 case reason == ReasonBusy:
771 // Another attempt holds the slot: it ends by itself.
772 case resetWake == nil || resetWake.Sub(now) > NoResetIn:
773 d.NeedsPerson = NeedsNoReset
774 }
775 return d
776}
777
778// wakeUps are the times a held step may become runnable on its own: every
779// reset of every capable connection (limited ones included), and, when
780// the step has leave to spend and a capable metered connection exists,
781// the next budget day and month.
782func wakeUps(in Input) (resets, budget []time.Time) {
783 for _, c := range in.Conns {
784 if !c.Capable {
785 continue
786 }
787 if !c.LimitedUntil.IsZero() {
788 resets = append(resets, c.LimitedUntil)
789 }
790 for _, w := range c.Windows {
791 if w.ResetsAt != nil {
792 resets = append(resets, *w.ResetsAt)
793 }
794 }
795 if c.Billing == Metered && leave(in.Step) && budget == nil {
796 now := in.Now.UTC()
797 budget = []time.Time{
798 time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC),
799 time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC),
800 }
801 }
802 }
803 return resets, budget
804}
805
806// earliest is the earliest of ts strictly after now, or nil.
807func earliest(now time.Time, ts ...time.Time) *time.Time {
808 var at *time.Time
809 for _, t := range ts {
810 if !t.After(now) {
811 continue
812 }
813 if at == nil || t.Before(*at) {
814 t := t
815 at = &t
816 }
817 }
818 return at
819}
820
821func nonNil(t *time.Time) []time.Time {
822 if t == nil {
823 return nil
824 }
825 return []time.Time{*t}
826}
827
828// DecidePinned is Run now's leave pinned to one connection (paused work,
829// 2026-11-24): the person was told it would run on pin, so it runs there
830// or nowhere. Decide reads only that connection, with the release's leave;
831// a kept session on another connection is not kept, and the bars (usable,
832// avoided, a metered connection's spend, budget and slot) still apply.
833// Every other rule of Decide is unchanged.
834func DecidePinned(in Input, pin string) Decision {
835 var only []Conn
836 for _, c := range in.Conns {
837 if c.ID == pin {
838 only = append(only, c)
839 }
840 }
841 in.Conns = only
842 if in.Step.Kept != pin {
843 in.Step.Kept, in.Step.KeptModel = "", ""
844 }
845 if in.Step.Release == "" {
846 in.Step.Release = "pinned"
847 }
848 return Decide(in)
849}
850