Documentation
¶
Overview ¶
Package strategy decides which account the engine should be on.
Index ¶
- Constants
- func ColdWindow(s *usage.Snapshot, model string, t Thresholds, now time.Time) (usage.WindowName, time.Time, bool)
- func CreditRoom(s SpendInfo, ceiling float64) (float64, bool)
- func FixedWindowFamily(n usage.WindowName) (string, bool)
- func MainPoolExhausted(cands []Candidate, o Options) bool
- func ModelFamily(name string) (string, bool)
- func ModelFamilyNames() []string
- func NextResetAmong(s *usage.Snapshot, model string, t Thresholds, now time.Time) (time.Time, bool)
- func OutOfQuota(h Headroom) (out, known bool)
- func Spent(h Headroom) (spent, known bool)
- func StatePath() (string, error)
- func StrategyNames() []string
- func SubscriptionExhausted(cands []Candidate, o Options) booldeprecated
- func WarmUpWouldSpendCredits(s *usage.Snapshot, model string, t Thresholds) bool
- func WindowForFixedFamily(family string) (usage.WindowName, bool)
- func WithState(timeout time.Duration, fn func(*State) error) (err error)
- type Action
- type Candidate
- type Config
- type CreditReason
- type Decision
- type Headroom
- type HoverPlan
- type HoverWindow
- type Mode
- type Options
- type Plan
- type Quarantine
- type Ranked
- type Reason
- type RefreshOutcome
- type Result
- type SpendInfo
- type State
- func (s *State) ClearQuarantine(uuid string) bool
- func (s *State) CooldownRemaining(now time.Time, d time.Duration) (time.Duration, bool)
- func (s *State) LastSwitch() (time.Time, string)
- func (s *State) LoadError() error
- func (s *State) Prune(managed map[string]bool)
- func (s *State) Quarantine(uuid string, now time.Time, d time.Duration, reason string)
- func (s *State) Quarantined(uuid string, now time.Time) (Quarantine, bool)
- func (s *State) QuarantinedUUIDs(now time.Time) []string
- func (s *State) RecordSwitch(uuid string, at time.Time)
- type Strategy
- type Thresholds
- type Warmup
Constants ¶
const ( // DefaultHysteresisPct is the hysteresis margin, in percentage points of // SLACK: how far a candidate must beat the active account to displace it, // which is what stops a ping-pong near the threshold. // // The margin and its `hysteresis_pct` config key are settled; the number // is not, so it is chosen here. Ten points is the smallest margin that // actually does the job it is named for: the binding window can change // between two readings — an account whose five_hour and seven_day are a // point apart flips between them — and that alone moves headroom by a few // points with no usage at all. A margin under that noise floor lets the // engine ping-pong across the threshold on jitter, which is the one thing // this margin exists to prevent. DefaultHysteresisPct = 10.0 // DefaultHeadroomRatio is 2.0. A candidate must have twice the active // account's headroom, which is what makes a REVERSE move need a 4x relative // burn: the forward move already required 2x in the other direction, so the // ratio between the two has to swing by 2x2. That squaring is the whole point, // and it falls out of applying the same 2.0 to every move rather than out of // remembering which account was left. DefaultHeadroomRatio = 2.0 // DefaultCooldown is the 5-minute minimum gap between two switches, the // mechanism against switch storms. DefaultCooldown = 5 * time.Minute // DefaultRecoveryHysteresis is 300 s. It is the margin on the RECOVERY // axis, for the all-above-threshold mode that ranks by soonest recovery: // comparing headroom there would gate on a number the order did not use. DefaultRecoveryHysteresis = 300 * time.Second // DefaultQuarantine is how long a dead refresh token holds an account out. // // No expiry is fixed for it, so it is chosen here. An hour matches // DefaultRecoveryHorizon and is short enough that a MISCLASSIFIED failure // costs an hour rather than a day; a genuinely dead token costs one wasted // refresh an hour, which is nothing. Only re-authentication actually fixes // a dead token, so this expiry is a safety valve and not a healing time — // see Quarantine. DefaultQuarantine = time.Hour )
const ( // HoverDisplayCap is the highest threshold a HUMAN table prints. Nothing // clamps the derived figure itself any more; see the note below. // // A derived threshold used to be clamped to 99 on the reasoning that a // threshold of 100 is not crossed until the account is completely out. That // reasoning was sound and the clamp was still wrong, because of WHICH // account it lands on: the clamp fires when the elapsed share plus the pool // share exceeds the cap, which is to say on whichever account is furthest // through its own window -- exactly the account whose quota expires soonest // and which the pace target exists to send work to. Above that line the // threshold was a flat 99 and the slack collapsed to 99 - utilization, with // the elapsed term thrown away, so the pool was ordered on raw utilization // for precisely the accounts that mattered most. // // It was measured rather than argued. Three accounts with weekly resets one, // three and five days out, driven through Decide on thirty-minute ticks for // five days: the clamp was live on 240 of 240 ticks, and on every single // tick where the ranking failed to put the neediest account first, that // account was the clamped one. The same loop ordered directly on the pace // deficit settled to a spread of 3.5 points; hover under the clamp // oscillated between 17 and 41, for the same number of switches. // // What made the clamp look load-bearing was that "empty implies spent" // rested on it: 100 > 99 guarantees a used-up account reports negative // slack. That now holds structurally instead -- see Spent, which reads // MinPct -- so the clamp has nothing left to carry. // // Uncapped, a threshold above 100 is a real and readable statement: there is // nobody to hand the work to, so nothing is being held back. The human table // still prints 100 as its ceiling, because a percentage above 100 reads as a // bug to everyone who has not read this comment; `--json` carries the true // figure, because a machine consumer checks slack against it. HoverDisplayCap = 100.0 // HoverFallbackThreshold is what a window with no elapsed share gets: one // that reported no reset, and one whose reset is further out than the // window is long. // // It is the same 80 the configured default has always been, which is the // honest choice for a window hover knows nothing about -- it is what the // engine would have used before hover existed. A window that lands here // because it named no reset is also the window probe_unknown wakes, and // hover forces that key on, which is what removes the fallback. HoverFallbackThreshold = 80.0 // HoverCreditThreshold is the figure a primary credit seat is measured on. // // A credit seat has no window and no reset, so there is no pace to derive // anything from and no rollover to wait for. 95 rather than the cap // because credits do not come back at all: the last few points are the // only warning a user gets that the seat is nearly spent, where a // subscription window's last few points are gone in hours anyway. HoverCreditThreshold = 95.0 // HoverHysteresisPct is 3 rather than the stock 10 because hover's // thresholds MOVE. Every window's threshold rises as the window elapses, so // a margin sized for a static threshold holds the engine on an account // whose slack the passing of time is already eroding. // // Three rather than the five it was first set to, because five turned out // to sit ABOVE the spread a real pool shows. Two accounts whose binding // windows are the same LENGTH have thresholds that rise at the same rate, // so the gap between their slacks does not close with time at all: only // burn closes it, and the burn is on the account the margin is holding the // engine on. The fleet of 2026-08-25 sat four points apart under a // five-point margin, live account at ten points of raw room and the // candidate at thirty -- so the margin spent the difference on the emptier // of the two and only released once the live account was a point nearer its // limit. TestTheHoverMarginIsUnderTheSpreadARealPoolShows is that pool. // // Three is still above the noise floor the stock margin was sized against // -- a binding window flipping between two windows a point apart, which // moves headroom by a point or two with no usage at all. What bounds the // flap RATE is HoverCooldown below, which is the mechanism for that job; a // margin sized to do it as well is a margin that strands quota. HoverHysteresisPct = 3.0 // HoverHeadroomRatio is 1.0, which is "no multiplicative margin". // // The ratio runs on RAW headroom while the ranking orders on slack, and the // two disagree hardest exactly where hover operates: with a tight, // pace-derived weekly floor, an account one point from that floor still // shows forty points of raw headroom, and the ratio refuses the move the // ranking asked for. Hover's own additive margin and its cooldown are what // bound the flap rate instead. HoverHeadroomRatio = 1.0 // HoverCooldown is 2 minutes rather than 5 for the same reason the margin // shrank: the thresholds are re-derived every tick, so a five-minute hold // is five minutes of running against numbers the clock has already moved // past. HoverCooldown = 2 * time.Minute // HoverRecoveryHysteresis keeps the stock 300 s. It is a margin on RESET // INSTANTS, which hover neither derives nor moves, so there is nothing // about hover that makes the stock figure wrong. HoverRecoveryHysteresis = 300 * time.Second // HoverMinPreemptLead is 60 s, which is the tightest cadence the poll // policy ever runs at. A lead shorter than one poll is a lead the engine // cannot act inside of. HoverMinPreemptLead = 60 * time.Second // HoverMaxPreemptLead is 10 minutes. Every second of lead is quota on the // live account deliberately left unspent, and the only cadence that // produces a wider gap is the post-429 ceiling of 1800 s -- where the // pre-emptive horizon already carries that whole blind interval, so the // lead does not have to carry it a second time. HoverMaxPreemptLead = 600 * time.Second )
const ( // DefaultThreshold is the utilization percent above which an account counts // as spent. `ccdad config` supplies the real value; this is what stands in // when it has not. DefaultThreshold = 80.0 // DefaultCreditThreshold is the utilization percent above which a // credit-metered account counts as spent. // // It matches DefaultThreshold because it answers the same question on a // different meter — a share of a credit balance rather than of a plan // window — and it is its own constant so that the two can be moved apart // without the credit axis silently inheriting a change made for // subscriptions. DefaultCreditThreshold = 80.0 // DefaultRecoveryHorizon is how soon a spent account has to come back before // "it comes back soon" outranks "it is less blown". // // The 300 s recovery hysteresis has a fixed default; nothing fixes this // one, so it is chosen here. An hour matches the window the endpoint's own // request budget slides over (pollpolicy.Recent429Window), and it is about // the longest wait a user would sit through rather than switching by hand. // Past it, "when does it come back" stops being the useful question and how // badly an account is blown is the better discriminator — which is exactly // what the far tier ranks on. DefaultRecoveryHorizon = time.Hour )
const CreditSubscriptionNotExhausted = CreditMainPoolNotExhausted
CreditSubscriptionNotExhausted is CreditMainPoolNotExhausted under the name it had while the main pool was subscriptions and nothing else.
Deprecated: use CreditMainPoolNotExhausted. Kept for one release for the same reason SubscriptionExhausted is.
const (
StateFileName = "strategy.json"
)
Variables ¶
This section is empty.
Functions ¶
func ColdWindow ¶ added in v0.5.0
func ColdWindow(s *usage.Snapshot, model string, t Thresholds, now time.Time) (usage.WindowName, time.Time, bool)
ColdWindow is the first window in an account's own candidate set — the same set HeadroomFor ranges over — whose clock is not running, together with the rollover the reading reported for it and whether there was one.
A five-hour window is anchored at first use and does not stretch when more is spent against it, so a clock started early is elapsed time the account gets for free — that is what a warm-up buys, and this names the window that has none running.
There are two ways to have no clock, and both are here because a warm-up answers both:
- NEVER SPENT: nothing used, no reset. This is the original question, and the one an account added five minutes ago asks.
- ROLLED OVER: the reading carries a reset that has already PASSED. The window ran down; the cached reading is simply older than the event. This arm is why the warm-up can land on the same tick as the poll that finds the window cold — without it the daemon must wait for one poll to write {0, null} and then for the NEXT poll's tick to notice, and both intervals are the ten-minute idle cadence.
A window at more than 0% with no reset is in neither arm; neverSpent says why.
It does not stop at the single BINDING window the way HeadroomFor does. An account's five-hour window can sit with no clock while a weekly cap binds tighter and has a running one of its own: from the ranking's point of view that account has pace already, but the five-hour clock is still stopped, and stopping is what costs lockout later. Ties resolve on the schema's own order, the same way HeadroomFor's do, which in practice means the plain five-hour window — first in wire order — wins over a weekly one when both qualify, and that is the window worth having.
func CreditRoom ¶
CreditRoom is the room calculation. Its local is named `capacity` rather than `cap` so it does not shadow the builtin.
The IsInf and IsNaN checks are load-bearing, not decoration. `max_auto_spend = inf` is valid TOML, and an infinite ceiling with no account cap yields unlimited unattended spending; NaN slips a plain `<= 0` because every NaN comparison is false.
func FixedWindowFamily ¶ added in v0.3.0
func FixedWindowFamily(n usage.WindowName) (string, bool)
FixedWindowFamily is the family a FIXED window is scoped to. It is written out rather than derived from the window's name, so that a future window whose key happens to contain a family token does not become model-scoped by accident.
This is the one place the correspondence is spelled. internal/daemon's probeModel and internal/cli's probeWindow both go through it — the first forward, the second through WindowForFixedFamily's reverse table — rather than each carrying its own switch, which is how the same two cases used to drift out of sync silently: a family added here without a matching case there left a probe that woke nothing and cost a turn every six hours, forever, with no test able to see the other switch at all.
func MainPoolExhausted ¶ added in v0.3.0
MainPoolExhausted answers step 2 of the credit gate: may the LAST-RESORT credit pool be considered at all?
The main pool is what Rank puts in Result.Order: the subscription accounts, and the credit seats marked primary. A primary seat with room means the pool is not exhausted, because its credits are quota the user is already paying for -- spending overage while it sits unused is the exact inversion the gate order exists to prevent.
An account that could not be read holds the pool OPEN. It is not known to be spent, and the fail-closed direction on money is to keep using what is already bought rather than to start spending because one poll failed. A pool with nothing in it is exhausted trivially.
The test is OutOfQuota and NOT Spent, and on this path the difference is money. Spent asks whether an account is past the number it was given, and under hover that number is a PACE target -- so a pool of six accounts every one of which is merely running ahead of schedule answers "exhausted" while carrying, between them, a fifth of a week of quota already paid for. Opening the last-resort pool there starts buying credits to avoid spending subscription quota that nobody is going to get back. The gate may only open once the free quota is actually gone.
func ModelFamily ¶ added in v0.2.0
ModelFamily reduces a model name to the family a per-model window is scoped to, and reports whether it could tell at all.
It answers false rather than guessing, and both false cases matter. A name carrying no known family is a model ccdad has not heard of, and a name carrying two is a string that is not a model name at all. Callers read false as "cannot rule this window out", which keeps an unrecognized name on the conservative side: it never narrows anything away.
func ModelFamilyNames ¶ added in v0.2.0
func ModelFamilyNames() []string
ModelFamilyNames lists the families ModelFamily knows, in its own order, so a CLI can build its refusal out of the same list the matcher reads.
func NextResetAmong ¶ added in v0.5.0
NextResetAmong is the earliest FUTURE rollover among an account's candidate windows, or false when no window has one.
FUTURE, and over the whole candidate set rather than the binding window: the caller is scheduling the poll that will find a clock stopped, and the binding window is routinely a weekly one whose reset is days out while the five-hour clock this exists to restart runs down within hours. A reset already in the past is not a schedule either — it is the event that has already happened, and ColdWindow is what answers for it.
func OutOfQuota ¶ added in v0.5.0
OutOfQuota is whether some window this account carries has nothing left in it at all -- not "past the number it was given", which is Spent, but empty.
The two questions were one question for as long as every window shared one threshold: at a flat 80, slack is raw room shifted by twenty, so "past its threshold" and "nearly empty" ordered accounts identically and one predicate answered both. Per-window thresholds broke that, and hover derives a fresh per-window table on every tick, so under hover they are never the same question again.
What makes them come apart at the top is that hover's threshold is a PACE TARGET and nothing clamps it. A window far enough through its own cycle is measured against a figure above 100, so an account with one point left reports POSITIVE slack and lands in the roomy tier ahead of an account holding sixty. Ranked on slack alone the near-empty account wins, and the engine hands the session to the one account that cannot serve it.
It reads MinPct rather than Pct for the reason MinPct exists: Pct describes whichever window is tightest on the SLACK axis, and the window that is empty is not always that one.
Three-valued for the same reason Spent is. An account nobody could read is not an empty one.
func Spent ¶ added in v0.3.0
Spent is whether an account is past a threshold on any window it carries.
One test covers them all: a negative slack means the binding window is over the threshold that window was given, and the binding window is the one with the least slack, so every other window has slack to spare.
It is three-valued on purpose. An account that could not be read is neither spent nor unspent, and folding that into a boolean is the bug that left cswap parked on the account that reset last. The MinPct clause states "empty implies spent" STRUCTURALLY rather than leaving it to arithmetic on a threshold constant. It used to be free: hover clamped every threshold below 100, so a used-up window could only ever report negative slack. With the clamp gone a window at 100% late in its own cycle is measured against a pace target above 100 and reports POSITIVE slack -- which would file an account with nothing in it in the roomy tier, and, because allOver is built from this predicate, would make ModeRecovery unreachable for the whole pool on the strength of one such account.
func StrategyNames ¶
func StrategyNames() []string
StrategyNames lists every strategy a caller may name, in this type's own order. A CLI builds its help text and its error message from this, so a strategy added here cannot be forgotten in one of them.
func SubscriptionExhausted
deprecated
SubscriptionExhausted is MainPoolExhausted under the name it had while the main pool was subscriptions and nothing else.
Deprecated: use MainPoolExhausted. It is kept for one release so a caller that has not been updated -- internal/strategy/antiflap.go among them -- keeps compiling and keeps getting the same answer, rather than a name that quietly means less than it used to.
func WarmUpWouldSpendCredits ¶ added in v0.5.0
func WarmUpWouldSpendCredits(s *usage.Snapshot, model string, t Thresholds) bool
WarmUpWouldSpendCredits reports whether spending one turn on this account could land on METERED CREDITS rather than on quota already paid for.
It is the one gate the warm-up loop shares with the credit gate's reasoning, and it is here rather than in the daemon so that `ccdad hover status` refuses on the same predicate it refuses on. Fully automatic must not become fully automatic SPENDING: the ceiling and the account's own overage switch are the two independent opt-ins unattended overage requires, and a mode cannot supply either on the user's behalf — least of all a mode whose whole job is to spend small turns nobody asked for one at a time.
Two conditions, and the first is the narrow one on purpose. A turn only reaches credits when there is no subscription quota LEFT, which is a window at 100%, not a window past the pace threshold hover derived for it: an account 80% through its week against a 46% pace target has a fifth of its quota in hand and the turn lands on that. Reading "past its threshold" as "out" here would have stopped warming five of the six accounts on the fleet this was written against, which is most of the benefit for none of the risk.
The second fails closed the way credit.go's every branch does. Only an account whose overage is demonstrably off — Disabled, or Blocked by an org or seat policy — is evidence that a turn CANNOT be billed. Unknown is not, and an unread extra_usage is the state a bug looks like.
func WindowForFixedFamily ¶ added in v0.3.0
func WindowForFixedFamily(family string) (usage.WindowName, bool)
WindowForFixedFamily is FixedWindowFamily's reverse: the fixed window one family's turn has to be spent against to reach it. A family FixedWindowFamily does not answer for is refused here too — a --model naming a real family with no fixed window of its own still falls through to the caller's own five-hour fallback, which is the honest answer for a family this build cannot scope.
func WithState ¶
WithState runs fn against the state under a cross-process lock and writes back what it changed. This is the only safe way to modify it.
An atomic rename alone is not enough. The daemon stamps a cooldown while `ccdad switch` clears a quarantine, and both do a read-modify-write of the same document: without the lock the second rename silently drops the first one's change — and the change it drops is a cooldown, which is a switch storm.
fn returning an error leaves the file exactly as it was.
Types ¶
type Action ¶
type Action uint8
Action is what the engine should do.
const ( // ActionStay is "the world is already how it should be", exit 3. ActionStay Action = iota // ActionSwitch is a move to Plan.Target. ActionSwitch // ActionBlocked is "a move was wanted and there is no viable target", // exit 4. The 3-versus-4 line in the exit contract is the actionability // line, and this is the side the user has to do something about. ActionBlocked )
type Candidate ¶
type Candidate struct {
UUID string
Kind identity.Kind
Disabled bool
// Elsewhere marks an account another machine's ccdad owns. It is ranked out
// exactly like Disabled, and it is a separate field for the same reason it
// is a separate flag on the account: the two answer different questions, and
// a listing that folds them prints the wrong reason beside the row.
Elsewhere bool
// Primary marks a credit-metered account that is the seat's ordinary
// metering rather than an overage: it ranks with the subscriptions instead
// of waiting in the last-resort pool. Nothing sets it here; the flag is an
// account fact, read off the store.
Primary bool
// Usage is the account's most recent reading, or nil when there has never
// been one. Nil is UNKNOWN, never empty.
Usage *usage.Snapshot
// FetchedAt is when this reading was taken and NextPollAt when the next one
// is due. Both are copied from usage.Entry, and the gap between them is the
// interval during which the engine is blind: a projection that has to guess
// it would be guessing the one number the cache already knows.
FetchedAt time.Time
NextPollAt time.Time
// Probe is what the last warm-up of this account did, copied from
// usage.Entry for the same reason the two stamps above are: `ccdad hover
// status` renders what the warm-up loop would do about each row, and a table
// that derived that from anything but the daemon's own inputs would be a
// second implementation of the gate, free to drift from the one that spends
// the quota.
Probe usage.ProbeState
// LastRateLimited is when the USAGE POLLER last took a 429 for this account,
// zero for never.
//
// It is not evidence that the account is out of quota, and nothing here may
// treat it as such. The throttle is on /api/oauth/usage, and the sharper of
// the two experiments on record found a Retry-After of 0 scoped to the
// ACCESS TOKEN rather than to the account -- so a 429 here can be an
// artefact of the token ccdad happens to be polling with. Filing a throttled
// account as spent is the cswap failure this package warns about in three
// other places: unreadable is not empty.
//
// What it does mean is that the reading will not be refreshed soon: the poll
// policy floors the cadence at Post429MinInterval and lets it climb to
// Post429MaxInterval. So it is read in exactly one place -- the pre-emptive
// switch, which is the rule that acts on a PROJECTION rather than on a
// figure, and which therefore has something to lose by running to an account
// whose numbers it cannot check.
LastRateLimited time.Time
}
Candidate is one account the engine may rank. It is deliberately not a store.Account: ranking needs a handful of facts, and taking only those keeps this package independent of how accounts are persisted.
type Config ¶
type Config struct {
// HysteresisPct is how many points of SLACK a candidate must beat the
// active account by.
HysteresisPct float64
// HeadroomRatio is the multiplicative margin on the same axis.
HeadroomRatio float64
// Cooldown is the minimum gap between two switches.
Cooldown time.Duration
// RecoveryHysteresis is how much sooner a candidate must recover.
RecoveryHysteresis time.Duration
// QuarantineFor is how long a dead refresh token holds an account out.
QuarantineFor time.Duration
// MaxAutoSpend is the credit gate's ceiling, in the currency's major unit.
// Its default is 0 — the explicit opt-in — so unlike every other field here
// a zero is honoured rather than replaced.
MaxAutoSpend float64
}
Config is the anti-flap set, as knobs.
Every field defaults when it is not positive, so the ZERO VALUE of this struct is the full default set. That direction is deliberate: an under-populated Config must never read as "every anti-flap mechanism off", and there is no way to switch one off at all. `ccdad config` supplies the real values; these are what stands in when it has not.
func HoverConfig ¶ added in v0.3.0
HoverConfig is the anti-flap set hover imposes, and the one number it leaves alone. Each figure's rationale sits on the constant that declares it.
preempt_lead is absent because it is not an anti-flap knob: it is a ranking input and travels on Options, where withHover puts the derived one.
MaxAutoSpend is deliberately not touched, and that is the line this function exists to hold. Fully automatic must not become fully automatic SPENDING: the ceiling is one of the two independent opt-ins unattended overage requires, and an opt-in a mode supplies on the user's behalf is not an opt-in.
type CreditReason ¶
type CreditReason uint8
CreditReason says why the gate answered as it did. It reaches a user-facing notification, so every value has a name.
const ( // CreditAllowed: there is armed room and both opt-ins are in place. CreditAllowed CreditReason = iota // CreditMainPoolNotExhausted: it is not the credit pool's turn. Steps 1 and // 2 of the gate order -- the last-resort credit pool is consulted only once // the MAIN pool is EXHAUSTED, not merely once its best candidate has failed // hysteresis. The main pool is the subscription accounts and the credit // seats marked primary. CreditMainPoolNotExhausted // CreditNotOptedIn: max_auto_spend is 0, which is the default. CreditNotOptedIn // CreditAccountDisabled: the account's own overage switch is off. CreditAccountDisabled // CreditAccountBlocked: the organization or seat refused overage — a spend // cap reached, credits out. Different from disabled, and worth saying so. CreditAccountBlocked // CreditSpendUnreadable: the figures needed to price a switch are missing. CreditSpendUnreadable // CreditNoRoom: the armed cap is spent. CreditNoRoom // CreditCeilingInvalid: the configured ceiling is infinite, NaN or negative. CreditCeilingInvalid )
func (CreditReason) String ¶
func (r CreditReason) String() string
type Decision ¶
type Decision struct {
// Allow is whether the engine may switch to this credit account.
Allow bool
// Reason is why.
Reason CreditReason
// Blocked marks a refusal the user should act on: exit 4 and a
// notification, never a silent exit 3. cswap conflates these two and a
// money-blocked engine becomes invisible to cron.
Blocked bool
// Room is the armed spend left, when there is any.
Room float64
// DisabledReason is the organization's own word for its refusal, kept
// verbatim: it is the difference between "turn overage on" and "your org
// hit its spend cap".
DisabledReason string
}
Decision is the gate's answer.
func CreditGate ¶
func CreditGate(e usage.ExtraUsage, ceiling float64, mainPoolExhausted bool) Decision
CreditGate is the last two steps of the credit gate, applied to one LAST-RESORT credit account: when the configured ceiling is 0, its default, answer blocked — exit 4 and a notification — rather than switch; and refuse when spend cannot be read.
mainPoolExhausted carries the first two steps — look for a target in the main pool, and reach the credit pool only once that pool is exhausted. It is supplied by the ranking pass: it must mean the main pool has no viable target left, not that its best candidate merely failed hysteresis.
A PRIMARY credit account never reaches this function, and that is structural rather than a branch: Rank puts one in Result.Order, so it is not in the pool Decide walks and armedRoom is not computed for it. Removing the ceiling for that one account is correct because max_auto_spend exists to bound OVERAGE -- spending beyond quota that is already paid for -- and a seat billed only in credits has no such quota, so the ceiling would not be bounding an overage, it would be refusing the account's only meter. For every other credit account it is still two independent opt-ins: the account's own extra-usage switch, checked below, and a ceiling a human wrote into config.toml. A primary seat has two of its own -- the same extra-usage switch on the wire, and a human typing `ccdad primary <ACCOUNT> on` at a named account.
ceiling is passed in rather than read from config, so this package never touches the config loader: it is max_auto_spend, 0 is its default, and Decide is what copies it from Config.MaxAutoSpend.
type Headroom ¶
type Headroom struct {
// Pct is 100 minus the binding window's utilization. It can go negative,
// and is kept that way: how far past its limit an account already is still
// orders it against other spent accounts. This is the DISPLAY axis, the one
// `ccdad list`'s LEFT column prints, and it asks the same question of every
// window.
Pct float64
// Slack is the binding window's threshold minus its utilization, and it is
// the axis the ranking orders on.
//
// It stops agreeing with Pct the moment two windows carry different
// thresholds. An account at 55% of a weekly window whose threshold is 60 has
// 45 points of raw headroom and 5 points of slack; five is the distance that
// decides whether the next prompt trips a limit, and forty-five is the
// number that would have ranked it first.
Slack float64
// Threshold is the number Slack was measured against.
//
// It is carried rather than recovered as Slack+100-Pct: that identity is
// exact in arithmetic and not in float64, and this figure is printed. It is
// also the only way a consumer holding a Headroom alone can report the
// threshold — `ccdad auto --json` renders a ranked pool and never sees the
// bundle the pass was run with.
Threshold float64
// MinPct is the LEAST raw room any binding window has, and MinWindow names
// it. It is a SEPARATE figure from Pct and it has to be.
//
// Pct is read off the window with the least SLACK, and once windows carry
// thresholds of their own those are two different windows. A five-hour
// window three percent into its cycle sits under a threshold of twenty and
// binds at 25% used, while the weekly one behind it is at 95% under a
// threshold of ninety-nine: Pct reports the five-hour window's 75 points
// while the weekly is what will actually stop the session eight prompts
// later. Slack is the right answer to "which window is this account closest
// to breaching"; it is the wrong answer to "how much work can this account
// still take", and this field is the second question asked in its own
// terms.
MinPct float64
MinWindow usage.WindowName
// Known is false when no window reported a utilization. An account that
// could not be read is NOT an empty one, and treating it as one is the
// exact bug that parked cswap's engine permanently.
Known bool
// Binding names the window Pct, Slack and Threshold all came from: the one
// with the least slack. It is the ORDERING axis and the spent test, and the
// three figures describe ONE window deliberately, so that Slack is always
// Threshold minus that window's utilization.
Binding usage.WindowName
// Floor names the WEEKLY window that has to clear before this account is
// usable again, and HasFloor is whether there is one at all. Two kinds
// qualify — one past the number it was given, and one with nothing left in
// it — and an empty one wins over a merely-tripped one. HeadroomFor's own
// loop spells out why it takes both.
//
// It is the REPORTING axis, and it is separate from Binding because it
// answers a different question. Binding is what is tightest right now; Floor
// is what will still be tight in two days. An account whose five-hour window
// rolls over in eight minutes has not recovered while its weekly cap is
// blown until Friday, so a tripped weekly window is what a user has to be
// told about and what has to clear before the account is usable again. It
// never participates in ordering.
Floor usage.WindowName
HasFloor bool
}
Headroom is how much of an account's BINDING window is left, and how far that window is from the threshold it was given.
It is deliberately not one window's number. An account carries a five-hour window and several weekly ones, and the one that binds is whichever is closest to its own threshold: ranking on five_hour alone hands work to an account whose weekly Opus quota is gone, and it hits a hard limit one prompt later.
func HeadroomFor ¶ added in v0.2.0
func HeadroomFor(s *usage.Snapshot, model string, t Thresholds) Headroom
HeadroomFor finds the binding window for a session that will run model, against that pass's own per-window thresholds.
The set it ranges over excludes cinder_cove: that is a one-time credit grant whose resets_at is an expiry, so a spent one would otherwise read as a permanently exhausted account. seven_day_oauth_apps IS included even though it is the one of the fixed five that reads as though it belonged to some other client — Claude Code is itself an OAuth app, nothing in the bundle says the window means anything else, and counting a window that does not bind is the cheaper of the two mistakes.
Windows tie on the first in the schema's own order, and the scoped ones come after the fixed five in wire order, so the answer does not depend on map iteration.
func HeadroomOf ¶
func HeadroomOf(s *usage.Snapshot, t Thresholds) Headroom
HeadroomOf finds the binding window for a session that has not named a model, which is every caller that is reporting rather than choosing.
type HoverPlan ¶ added in v0.3.0
type HoverPlan struct {
// Usable is how many accounts the quota is divided between: eligible, with
// a reading, and -- because Decide filters the pool before this runs -- not
// quarantined.
Usable int
// Windows is every derived threshold, in pool order and then in wire
// order, so two runs over one pool render identically.
Windows []HoverWindow
// CreditThreshold is what a primary credit seat is measured on.
CreditThreshold float64
// PreemptLead is derived from the observed poll gap; see hoverPreemptLead.
PreemptLead time.Duration
// contains filtered or unexported fields
}
HoverPlan is one hover pass over one pool.
func HoverThresholds ¶ added in v0.3.0
HoverThresholds derives the whole table for one pool.
It takes the pool AFTER quarantine rather than the whole store, because a quarantined account cannot be switched to: counting it would divide the quota between accounts one of which nothing can use, tightening every other account's threshold for nothing.
func (HoverPlan) For ¶ added in v0.3.0
func (p HoverPlan) For(uuid string) Thresholds
For is the threshold table one account is measured against.
type HoverWindow ¶ added in v0.3.0
type HoverWindow struct {
UUID string
Window usage.WindowName
// ExpectedPct is the share of the window that has elapsed, and HasExpected
// whether there was one. False means the threshold is the fallback.
ExpectedPct float64
HasExpected bool
// Utilization is what the window reported. A window that reported none
// gets no row at all: it cannot bind, so there is no threshold to derive.
Utilization float64
Threshold float64
Slack float64
// ProbeWanted marks a window that reported no reset. It is a rendering
// fact, not a queue: hover forces probe_unknown on and the engine's own
// probe path is what spends the turn that wakes the window.
//
// Warmup below is the one that answers "will anything actually happen", and
// the two are kept apart deliberately. This field's name and its JSON key
// have always meant "this window named no reset", which is a true and useful
// thing to say; what was wrong was the renderer printing "a probe is queued"
// from it.
ProbeWanted bool
// Warmup is what the warm-up loop would do about this row, and it is set on
// exactly one row per account.
Warmup Warmup
// Credit marks the one row that is not a window: a primary credit seat's
// own metering.
Credit bool
}
HoverWindow is one derived threshold together with the figures it came from.
It carries the inputs and not only the answer, because an automatic mode a user cannot audit is one they have to take on trust. `ccdad hover status` prints these verbatim.
type Mode ¶
type Mode uint8
Mode is the situation the ranking actually found itself in — one of the three below. It is reported so `ccdad status` can say WHY an order looks the way it does.
const ( // ModeHeadroom: at least one account has room, or some account could not be // read and might. Rank by most headroom. ModeHeadroom Mode = iota // ModeRecovery: every account is known to be over threshold. Rank by // soonest recovery, because sitting still burns the active account to a // hard limit while a peer that frees up in eight minutes is never tried. ModeRecovery // ModeConsumeFirst: the user asked for perishable quota to be spent first. ModeConsumeFirst )
type Options ¶
type Options struct {
Now time.Time
// Threshold is the utilization percent above which an account is spent. It
// is the fallback for any window the table below does not name.
Threshold float64
// WindowThreshold is the threshold for a named window, for the windows that
// have one of their own. A window missing from it — and nil, which is every
// window missing — falls back to Threshold.
//
// It is keyed by the window name the wire uses, scoped names included, so
// the map a user's configuration builds needs no translation table between
// what was typed and what the snapshot reports.
WindowThreshold map[usage.WindowName]float64
// CreditThreshold is the utilization percent above which a credit-metered
// account counts as spent.
CreditThreshold float64
// PreemptLead is how far ahead of a projected exhaustion the engine moves.
//
// A zero switches pre-emption OFF, and that is a real answer rather than an
// omission: this is an opt-out a user may legitimately want, the same
// direction MaxAutoSpend already takes, and unlike an anti-flap margin it is
// not a mechanism that must never be switched off. The default lives in the
// configuration, which is the only thing that knows a user did not say.
PreemptLead time.Duration
// Horizon is how soon a recovery has to be to win its tier.
Horizon time.Duration
Strategy Strategy
// Model is the model the session about to run will use, as the user typed
// it. Empty is the unqualified pass — every window binds — and is what the
// daemon and every reporting caller use. A named model narrows the ranking
// to the windows that bind for it; see bindingWindows for the rule.
//
// It is a free string rather than a parsed family because the refusal for a
// name ccdad cannot place belongs at the CLI, where there is a user to tell.
// Reaching the engine, an unplaceable name simply narrows nothing.
Model string
// Hover replaces every threshold in this struct with one derived per account
// and per window. It is a mode rather than a knob, so it is a plain bool with
// no default to fall back to.
Hover bool
// MaxAutoSpend is the credit gate's ceiling, and it is here for ONE reason:
// the credit pool is ordered by armed room, and room cannot be computed
// without it.
//
// It is the same number Config.MaxAutoSpend carries, and Decide copies it
// from there rather than trusting a caller to set both — a pass that ranked
// on one ceiling while the gate decided on another would walk to a first
// choice the gate then refuses. 0 is the default and arms nothing, which
// leaves the pool in the uuid order it had before this field existed.
//
// It does not bound a primary credit account; see Candidate.Primary.
MaxAutoSpend float64
// contains filtered or unexported fields
}
Options configures one ranking pass.
func (Options) Thresholds ¶ added in v0.3.0
func (o Options) Thresholds() Thresholds
Thresholds is this pass's thresholds as one value, which is the shape every consumer outside this package takes.
The defaulting lives in Thresholds rather than here, so there is one place a zero can be turned into DefaultThreshold and no way for a caller to reach a comparison with a bare zero — which would make an account at one percent read as spent and open the credit gate.
type Plan ¶
type Plan struct {
// Action is what to do.
Action Action
// Reason is why.
Reason Reason
// Target is where to move, set only when Action is ActionSwitch.
Target Ranked
// Result is the ranking this plan was made from. It covers the pool AFTER
// quarantined accounts were removed, so the mode it reports is the mode the
// decision was actually made in.
Result Result
// Quarantined lists the eligible accounts held out of the pass, in uuid
// order.
Quarantined []string
// SubscriptionExhausted answers "is the subscription pool spent", which is
// the only thing that opens the credit pool. Reported so a caller can
// say why the credit pool was or was not consulted.
SubscriptionExhausted bool
// Hover is the pass the thresholds came from, set only when hover was on.
// nil is what says the mode was not in force; `ccdad hover status` reads
// this rather than deriving a second table of its own.
Hover *HoverPlan
// Credit is the gate's answer, set only when the credit pool was reached.
Credit Decision
// CreditConsulted records that it was reached at all, because a refusing
// Decision and a never-consulted one are both zero-ish and mean opposite
// things.
CreditConsulted bool
// RetryAt is when the blocking condition lifts, when that is knowable — the
// end of a cooldown, or the soonest quarantine expiry. It is advice for a
// scheduler, never a promise that the answer changes then.
RetryAt time.Time
// HasRetryAt is whether RetryAt was set. A zero time is a real instant.
HasRetryAt bool
}
Plan is one engine evaluation.
func Decide ¶
Decide is the anti-flap margins and the credit gate's order over one ranking pass.
activeUUID must be the account in the LIVE CREDENTIALS FILE, derived by attributing that file against the stored credentials. It must NOT be store.ActiveUUID(): store.go documents that field as a display HINT, and it goes stale the moment the user runs /login inside Claude Code. Hysteresis measured against a stale baseline compares the candidate to an account that is not there, which is how an engine talks itself into a switch it already made. "" means the live login could not be attributed to a managed account, which is a real state and not an error: there is then no baseline to hold a margin against, and the margins that need one are skipped.
st carries the persisted cooldown and quarantines. It is never written here — deciding is not switching, and a plan that is not executed must not leave a cooldown behind.
type Quarantine ¶
type Quarantine struct {
// Since is when the account was quarantined.
Since time.Time `json:"since"`
// Until is when the quarantine lapses on its own. The expiry is a safety
// valve rather than a healing time: a genuinely dead token comes back,
// fails one refresh, and is quarantined again.
Until time.Time `json:"until"`
// Reason is why, kept because it reaches a user-facing notification.
Reason string `json:"reason,omitempty"`
}
Quarantine is one account held out of auto-rotation by the engine.
It carries an expiry AND can be cleared explicitly, and it needs both. Only re-authentication actually fixes a dead refresh token, so an expiry alone would put a dead account back into rotation forever; but a quarantine that only an explicit clear could lift would make a misclassified failure permanent, and nothing else in ccdad would ever notice.
func (Quarantine) Active ¶
func (q Quarantine) Active(now time.Time) bool
Active reports whether this quarantine still holds at now.
A zero Until never lapses. That is not a degradation: a hand-edited or truncated file that loses the timestamp must fail towards holding the account OUT of rotation, because the only reason an account is in here is that its credential did not work.
type Ranked ¶
type Ranked struct {
UUID string
Kind identity.Kind
Headroom Headroom
// RecoversAt is when the binding window rolls over.
RecoversAt time.Time
HasRecovery bool
// WeeklyResetsAt is the soonest weekly reset, which consume-first ranks on.
WeeklyResetsAt time.Time
HasWeeklyReset bool
// ReturnsInsideHorizon is the tier bit of lessRecovery's tiered key.
ReturnsInsideHorizon bool
// CreditRoom is the armed spend the credit gate would allow, for a credit
// account under the configured ceiling. It is the credit pool's ordering
// key and is reported so `ccdad status` can explain that order rather than
// only obey it.
CreditRoom float64
// HasCreditRoom is whether there is any. False covers every refusal the
// gate would make — no ceiling configured, overage switched off, spend
// unreadable, the armed cap spent — so it is not a claim that the account
// has none, only that none can be armed right now. It is also false for a
// PRIMARY credit seat, where no room was priced at all: Rank routes such a
// seat into Result.Order and the ceiling never applied to it.
HasCreditRoom bool
}
Ranked is a candidate with the figures the ranking used, so a caller can explain the order rather than only obey it.
type Reason ¶
type Reason uint8
Reason is why the engine answered as it did. Every value has a name because every one of them reaches a user through `ccdad auto --json` or a notification, and "no switch" with no reason is the cswap behaviour the exit contract exists to fix.
const ( // ReasonBetterTarget: a candidate cleared every margin. ReasonBetterTarget Reason = iota // ReasonAlreadyBest: the live account already tops the ranking. ReasonAlreadyBest // ReasonCooldown: a switch happened too recently. ReasonCooldown // ReasonHysteresis: the candidate is ahead, but not by the margin. ReasonHysteresis // ReasonHeadroomRatio: the candidate beat the margin but not the ratio. ReasonHeadroomRatio // ReasonRecoveryHysteresis: the candidate recovers sooner, but not by 300 s. ReasonRecoveryHysteresis // ReasonWeeklyResetMargin: consume-first's equivalent on the reset axis. ReasonWeeklyResetMargin // ReasonNoCandidates: nothing is eligible to rank at all. ReasonNoCandidates // ReasonAllQuarantined: everything eligible is held out by a quarantine. ReasonAllQuarantined // ReasonAllExhausted: every account is spent and there is no credit pool. ReasonAllExhausted // ReasonCreditGate: the credit pool was reached and the credit gate refused // it. The gate's own answer is in Plan.Credit. ReasonCreditGate // ReasonNoSubscriptionRoom: the engine is on a credit account and no // subscription account has room to go back to. Staying is right; moving to // a spent subscription account would break the session for nothing. ReasonNoSubscriptionRoom // ReasonProjectedExhaustion: the live account's binding window is projected // to reach its limit before the next reading lands, and some candidate still // has slack. Appended LAST on purpose — nothing persists these values, but // renumbering an enum that a report and a notification both name is a diff // nobody can review. ReasonProjectedExhaustion )
type RefreshOutcome ¶
type RefreshOutcome uint8
RefreshOutcome is what a token-refresh failure means for the engine.
Every TokenErrorKind gets its own value, and only one of them quarantines. The quarantine has exactly one trigger, a refresh token the server rejected, and collapsing these would fire it on anything: a transport failure quarantines every account the first time the laptop sleeps, and a bad status does it the first time Anthropic returns a 503.
const ( // RefreshOK is no failure at all. RefreshOK RefreshOutcome = iota // RefreshUnreachable is oauth.TokenErrorTransport: the request never got an // HTTP answer. That is the network, not the account. RefreshUnreachable // RefreshDead is oauth.TokenErrorInvalidCode: the refresh token itself was // rejected. This is the ONLY outcome that quarantines. RefreshDead // RefreshScopeRefused is oauth.TokenErrorInvalidScope. The credential is // live and the request was wrong, so quarantining the account would blame // it for ccdad's own bug. RefreshScopeRefused // RefreshUpstream is oauth.TokenErrorStatus: the endpoint answered, badly. RefreshUpstream // RefreshUnknown is an error that is not a token-endpoint failure at all — // a context deadline, a store read. It is not evidence about the token. RefreshUnknown )
func ClassifyRefresh ¶
func ClassifyRefresh(err error) RefreshOutcome
ClassifyRefresh maps a token-refresh failure onto the engine's answer. It is the only thing that may decide an account is dead.
func (RefreshOutcome) Quarantines ¶
func (o RefreshOutcome) Quarantines() bool
Quarantines reports whether this outcome may quarantine the account. It is a method rather than a comparison at every call site so that adding a kind cannot quietly add a way to quarantine.
func (RefreshOutcome) String ¶
func (o RefreshOutcome) String() string
type Result ¶
type Result struct {
// Order is the MAIN POOL, best first: the subscription accounts and the
// credit seats marked primary, ranked together.
Order []Ranked
// Credit is the last-resort credit accounts, ordered by most armed room;
// see lessCredit. They are not ranked on headroom and never appear in
// Order: such an account is metered in money and carries no plan windows,
// so its headroom is permanently unknown — which would file it in the "we
// have no idea" tier, ahead of every account known to be spent, and make
// the engine's best candidate the one that costs money. A credit account is
// a last resort, and the gate, not this comparator, is what decides whether
// one may be used. A credit account the user marked primary is NOT here: it
// is in Order, ranked on the credit utilization that is its ordinary meter.
Credit []Ranked
// AllOverThreshold is true only when every MAIN-POOL candidate is KNOWN
// to be over threshold. An account that could not be read makes it false:
// it is neither over nor under, and letting one expired token decide this
// is how cswap's engine came to park itself permanently. Last-resort credit
// accounts are excluded, or a registered credit account's permanently
// unknown headroom would pin this to false and make ModeRecovery
// unreachable.
AllOverThreshold bool
Mode Mode
}
Result is one ranking pass.
type SpendInfo ¶
type SpendInfo struct {
// Enabled is the account's own overage switch — one of the two independent
// opt-ins. The other is the configured ceiling.
Enabled bool
// Limit is the account's own monthly cap. Nil means the account sets none,
// so the configured ceiling is the only bound.
Limit *float64
// Used is what has already been spent. Nil means it could not be read, and
// that refuses.
Used *float64
}
SpendInfo is the credit axis, in the shape CreditRoom takes. Limit and Used are pointers because the wire declares both nullable and the difference between "not reported" and "zero" is the difference between refusing and spending.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State is the parsed anti-flap state.
func LoadState ¶
LoadState reads the state without taking a lock.
No lock is needed to read: every write is a rename, so a reader sees one whole version of the document or another, never a torn one. A file that cannot be read or parsed degrades to an empty state — no cooldown, no quarantine — and records why in LoadError. That degradation is deliberately towards MORE switching rather than less: a quarantine that cannot be read is not evidence that an account is dead, and refusing to switch at all on a corrupt file would park the engine exactly the way anti-flap must never park it: those margins bound the rate of switching, not whether the engine can switch at all.
func NewState ¶
func NewState() *State
NewState builds an empty in-memory state. It touches no disk, which is what makes the engine testable without one.
func (*State) ClearQuarantine ¶
ClearQuarantine lifts an account's quarantine and reports whether there was one. `ccdad add` re-authenticating an existing uuid must call this: store.Add updates in place, so without it the user re-logs-in successfully and the engine goes on refusing to use the account.
func (*State) CooldownRemaining ¶
CooldownRemaining is how long the anti-flap cooldown still has to run, and whether one is in force at all.
A LastSwitchAt in the future is a clock that moved backwards rather than a switch that has not happened yet, and it is deliberately still honoured: the conservative direction here is to wait, and the wait is bounded by the cooldown itself once the clock settles.
func (*State) LastSwitch ¶
LastSwitch is when the engine last moved and where to.
func (*State) LoadError ¶
LoadError is why the state came back empty when a file did exist. It is not fatal — an unreadable state file means no cooldown and no quarantine, which is the state a first run is in — but `ccdad doctor` should be able to say so rather than having the corruption stay invisible.
func (*State) Prune ¶
Prune drops quarantines for accounts that are no longer managed, so a removed account cannot come back quarantined when it is added again under the same uuid.
func (*State) Quarantine ¶
Quarantine holds an account out of auto-rotation. Callers must have decided the failure warrants it — see ClassifyRefresh, which is the only thing that may make that call.
func (*State) Quarantined ¶
Quarantined reports an account's live quarantine, if it has one.
func (*State) QuarantinedUUIDs ¶
QuarantinedUUIDs lists every account under a live quarantine, in uuid order so the answer does not depend on map iteration.
type Strategy ¶
type Strategy uint8
Strategy is which question the ranking asks.
func ParseStrategy ¶
ParseStrategy is String's inverse. Unlike identity.ParseKind it does NOT fall back to a default: a name that reaches here came from a user typing it, and silently running the wrong strategy for a typo is the cswap behaviour the exit contract exists to fix.
type Thresholds ¶ added in v0.3.0
type Thresholds struct {
// Default is the threshold for a window with no entry of its own, which is
// every window until a user writes a table.
Default float64
// PerWindow is the per-window table, keyed by the window name the wire
// uses — scoped names included — so the map a user's configuration builds
// needs no translation between what was typed and what a snapshot reports.
PerWindow map[usage.WindowName]float64
// Credit is the utilization percent above which a credit-metered account
// counts as spent. It is a separate number from Default because the two
// meter different things: Default is a share of a plan window, this is a
// share of a credit balance.
Credit float64
}
Thresholds is every threshold one ranking pass may consult, in one value.
It is a value type with a nil-safe map, so a caller never branches on presence: the zero Thresholds is the built-in default set, and a nil PerWindow is the ordinary state rather than a missing one.
func (Thresholds) CreditThreshold ¶ added in v0.3.0
func (t Thresholds) CreditThreshold() float64
CreditThreshold is the credit meter's threshold, defaulted the same way and for the same fail-open-on-money reason.
func (Thresholds) For ¶ added in v0.3.0
func (t Thresholds) For(n usage.WindowName) float64
For is the threshold for one window: its own entry when it has one, Default when it does not.
Both fallbacks default rather than being read literally, and it matters. A zero threshold read literally means "over threshold if utilization > 0", so an account with a single percent used counts as spent — which flows straight into SubscriptionExhausted, the input that opens the credit gate. A zero-valued Thresholds would therefore fail OPEN on money, against everything the credit gate stands for. Defaulting makes the omission harmless instead, and a non-positive entry in the table is treated as the same omission for the same reason.
type Warmup ¶ added in v0.5.0
type Warmup struct {
// Target marks the row a warm-up would aim at.
Target bool
// Credits marks the one refusal that is about money: a turn spent here
// could be billed to metered credits, which unattended spending's two
// opt-ins do not cover. WarmUpWouldSpendCredits is the predicate, and the
// daemon refuses on the same call.
Credits bool
// RolledOver is whether the clock is stopped because it RAN DOWN, as against
// never having been started. The two read differently to a user: one is the
// ordinary end of a cycle, the other is an account nothing has ever used.
RolledOver bool
// Eligible is whether the gate would let the turn be spent now.
Eligible bool
// PollAt is when the scheduler next intends to look at this account, copied
// from the cache. An eligible warm-up does not run at the instant the gate
// opens; it runs on the next tick where the account is also poll-due, and a
// table that named the gate's instant would be early by up to a poll
// interval every time.
PollAt time.Time
// NextAt is when the backoff opens. Zero means no backoff is holding it —
// either nothing is, or what is holding it is "one warm-up per rollover",
// which has no instant to name because the next rollover has not been
// scheduled by anything yet.
NextAt time.Time
// Streak is how many consecutive warm-ups of this window woke nothing.
Streak int
// LastAttemptAt and LastError are the last attempt's stamp and its report.
// LastError is shown and never gated on; usage.ProbeState says why.
LastAttemptAt time.Time
LastError string
}
Warmup is what the warm-up loop would do about one row, as far as the ranking package can see it.
It is filled for exactly one window per account — the one ColdWindow targets — and left zero everywhere else, because a warm-up is one turn aimed at one window and a table that marked every stopped clock would promise a turn per row.
What is deliberately NOT here is the half the daemon knows and this package does not: which account is live, whether probe_unknown is on, whether there is a Claude Code on this PATH. `ccdad hover status` layers those on top. The split is what keeps the gate itself in one place — the parts that could drift are the parts nobody duplicated.