ccpool

package
v0.247.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ccpool is the per-account Claude Code `setup-token` pool: which operator account a new claude-code agent runs on, and what each account's sessions have reported back.

The shape

The operator has several INDIVIDUAL Pro/Max accounts and runs `claude setup-token` once per account. Each token is one value in muster's own environment (MUSTER_AGENT_CC_TOKEN_<NAME>, named by MUSTER_AGENT_CC_ACCOUNTS — see cmd/muster-server/config.go). This package holds that map and answers three questions:

  • Select: which account should a NEW claude-code agent use?
  • Token: which setup-token does a pod on account X get?
  • MarkFailure: ccd reported `rate_limited` or `auth_failed` for an agent on account X — remember it, with a timestamp, in Postgres.

Whose accounts (bring-your-own, migration 0011)

The environment pool is the ADMIN's. A member's agents run only on accounts the member entered in muster (internal/credentials). The Source answers "which accounts may this OWNER use", and every selection, mark and live count is per (owner, account): there is no path from a member's dispatch to an environment-pool account (TestAMemberDispatchNeverSelectsAnAdminPoolAccount in internal/credentials). The one exception is the marks of a SHARED pool's accounts (SharedAccounts): the admin and the teams listed on the server pool run on the same accounts, so their marks are kept once, under the pool's marks owner, and every owner on the pool sees them.

Selection

Choose is the whole algorithm, and it is a pure function so a test can pin it without a database:

  1. Drop every account whose CURRENT token is marked auth_failed (the mark's fingerprint equals Fingerprint of the token configured now). Replacing the token in the secret therefore clears the mark by itself; nothing else does. If that leaves nothing, refuse — dispatching onto a token that already failed authentication builds a pod that cannot answer one turn.
  2. An account still COOLING DOWN after a rate_limited mark (see "The cooldown" below) ranks after every account that is not. It is NOT dropped: dispatch never refuses for a cooldown, because an agent keeps its account for life and outlives any one rate-limit window.
  3. Least-recently-rate-limited first: never rate-limited sorts before any timestamp, then oldest timestamp first.
  4. Then fewest LIVE agents (kind claude-code, status pending, provisioning or running) on the account.
  5. Then the account name, so the answer is deterministic.

The cooldown and the per-account cap (M4)

After a `rate_limited` mark an account cools down until CooldownUntil: the reset time the CLI's message states ("resets 9:45pm (UTC)", "resets Oct 9, 9am (UTC)") when one can be read, else the mark's time plus Limits.Cooldown (default DefaultCooldown). It is over at exactly that instant — or sooner, when THE LIVE READING SAYS THE ACCOUNT IS USABLE: the usage poller (internal/ccusage) keeps reading a cooling account, and when what the account reports right now shows it usable it clears the mark (Pool.ClearRateLimit), guarded so a NEWER mark written while it was reading is never cleared. A stated reset is the CLI's estimate; the live reading is the account's own word. With the poller off nothing ends a cooldown early.

A rate_limited mark is about the SUBSCRIPTION, not the token: limits are counted per subscription, so a re-issued token on the same one is still limited, and replacing the token does NOT end the cooldown. A changed token on a cooling account is read by the live probe on the poller's next pass, and that reading decides.

🔴 ONLY THE JOB API AND THE FAILOVER REFUSE FOR IT. The job API's worker-pool choice (internal/api chooseWorker, reading AccountState.CoolingUntil) skips a worker on a cooling account — and when that leaves no worker it fails one such worker over to a usable account (internal/ccfailover) and places the job there, answering 429 only when no account is usable — and ChooseFailover never moves an agent onto a cooling account. Agent dispatch (Choose) only ranks a cooling account last and still picks it when it is all there is: an agent outlives a rate-limit window, so refusing to create it for a window of hours would buy nothing.

Limits.MaxConcurrentJobs caps how many JOBS one account runs at once, and is OPT-IN: zero (the default) is no cap, because an account's real capacity is unmeasured. This package does not count jobs; it carries the cap to the job API's worker choice in AccountState, and that choice enforces it. Agent dispatch has no cap: an agent is not a job.

An explicit pin at dispatch bypasses all of these — it is the operator's override, including for an account the pool would skip — but must name a configured account.

🔴 AN AGENT KEEPS ITS ACCOUNT UNTIL AN ACCOUNT FAILOVER MOVES IT. Select runs once, before the agent's row exists; the row stores the NAME (agents.cc_account) and migration 0003's trigger refuses any later change except the failover's (internal/ccfailover, migration 0066), which moves an agent off an account that answered rate_limited or auth_failed onto one ChooseFailover picks. A restart, a re-provision, a model of the pool changing under it — none of them re-select.

🔴 Pool.Token IS THE ONE PLACE A TOKEN LEAVES THIS PACKAGE: the pod-spec path (internal/agentprovision, through internal/credentials.Plane) asks it for the token of the agent's OWN owner and account, and agentspec places it in exactly one place — the agent's own per-agent Secret, as CLAUDE_CODE_OAUTH_TOKEN. No error, log line or stored mark here carries it; a mark stores a truncated sha256 fingerprint.

⚠ ROTATING A TOKEN DOES NOT REACH A RUNNING POD. The new value is in muster's environment; an existing agent's Secret still holds the old one until its spec is re-applied — Stop then Start a claude-code agent does that (agentprovision.Adapter.Start). Until then its turns keep failing and keep re-marking the account, now under the NEW token's fingerprint.

Index

Constants

View Source
const (
	FailureRateLimited = "rate_limited"
	FailureAuthFailed  = "auth_failed"
)

The failure types ccd reports that mark an account. They are ccd's own spellings (cmd/ccd/failure.go: failRateLimited / failAuthFailed) — the wire's `error.type` — and nothing else marks.

View Source
const DefaultCooldown = time.Hour

DefaultCooldown is how long an account rests after a `rate_limited` whose message states no reset time this package can read.

⚠ THERE IS DELIBERATELY NO DEFAULT JOB CAP. The per-account cap is opt-in (Limits.MaxConcurrentJobs zero is none): what one account sustains is not known until it is measured, and a guessed default would throttle silently.

Variables

View Source
var ErrNoUsableAccount = errors.New("ccpool: no usable Claude account")

ErrNoUsableAccount is returned by Select when automatic selection has nothing to choose from. It is a dispatch REFUSAL, surfaced to the operator.

View Source
var ErrUnknownAccount = errors.New("ccpool: unknown Claude account")

ErrUnknownAccount is returned for a pin (or a lookup) naming an account that is not configured.

Functions

func Choose

func Choose(now time.Time, cooldown time.Duration, names []string, tokens map[string]string, marks map[string]Mark, live map[string]int) (string, error)

Choose is the selection algorithm (see the package doc), pure. now and cooldown decide which rate-limited accounts are still cooling down; such an account ranks last but is never refused.

func ChooseFailover added in v0.114.0

func ChooseFailover(now time.Time, cooldown time.Duration, names []string, tokens map[string]string, marks map[string]Mark, from string) (string, bool)

ChooseFailover is the account a claude-code agent on account from is REBOUND to after from hit its limit or failed authentication (internal/ccfailover): pure, like Choose, over the same marks, the same "current token" rule and the same cooldown.

🔴 UNLIKE Choose IT REFUSES RATHER THAN RANKING LAST. Choose still picks a cooling account when it is all there is, because a new agent outlives a rate-limit window; a failover exists only to move OFF a limited account, so moving onto another one that is still cooling (or whose token failed) would restart the agent's pod to buy nothing. ok is false then, and the agent stays where it is.

Of the usable accounts other than from — not auth_failed for its current token, not cooling down at now — it prefers the order the pool and the job API use: never rate-limited first, then the one rate-limited longest ago, then the name (deterministic).

func CooldownUntil

func CooldownUntil(m Mark, cooldown time.Duration) time.Time

CooldownUntil is when m's rate-limit cooldown ends: the reset time its message states ([statedReset]), else its mark's time plus cooldown. Zero for an account never rate-limited. The account is selectable again AT that instant: cooling down is now.Before(CooldownUntil(...)).

It is computed from the stored mark at every read, not stored itself, so a changed default cooldown applies to marks already written.

func EnvSuffix

func EnvSuffix(name string) string

EnvSuffix is the part of an account's token variable after the prefix: "work-2" -> "WORK_2". It is the one place the name-to-variable mapping lives.

func Fingerprint

func Fingerprint(token string) string

Fingerprint is a short, one-way identifier for a token: the first 12 hex characters of its sha256. It is what an auth_failed mark records so the mark can expire when the token is replaced, without the database holding anything that authenticates.

func ValidName

func ValidName(name string) bool

ValidName reports whether name is a legal account name: 1-32 of [a-z0-9-], not starting or ending with '-'.

Types

type AccountState

type AccountState struct {
	// AuthFailed: the account's CURRENT token is marked auth_failed (the
	// mark's fingerprint is that token's), exactly the case [Choose] skips.
	AuthFailed bool
	// RateLimitedAt is the account's latest rate_limited mark; zero for never.
	RateLimitedAt time.Time
	// CoolingUntil is when the account's rate-limit cooldown ends ([CooldownUntil]),
	// set ONLY while it is still cooling down at the pool's clock when States
	// read it; zero once it has ended. A non-zero value means "not selectable".
	CoolingUntil time.Time
	// MaxConcurrentJobs is the per-account job cap ([Limits.MaxConcurrentJobs]),
	// the same for every account. ZERO IS NO CAP, which is the default.
	MaxConcurrentJobs int
}

AccountState is what selection knows about one of an owner's accounts.

type Cooldown added in v0.225.0

type Cooldown struct {
	// Until is when the cooldown ends ([CooldownUntil]); zero when the account
	// is not cooling now.
	Until time.Time
	// MarkedAt is the timestamp of the rate_limited mark Until was computed
	// from (zero with Until). It is what [Pool.ClearRateLimit] compares
	// against, so a clear decided on this reading can never erase a newer mark.
	MarkedAt time.Time
	// Detail is that mark's stored detail (the CLI's limit message; "" with
	// Until). It names WHICH limit was hit, which the live reading must answer
	// for before the mark is cleared (internal/ccusage LiveUsable).
	Detail string
}

Cooldown is one account's rate-limit cooldown as Pool.Cooldown read it.

type Limits

type Limits struct {
	// Cooldown is the rest after a `rate_limited` whose message carries no
	// readable reset time. Positive.
	Cooldown time.Duration
	// MaxConcurrentJobs caps the jobs one account runs at once. ZERO IS NO CAP
	// (the default); a cap is at least 1.
	MaxConcurrentJobs int
}

Limits are the pool's two knobs: the cooldown after a rate limit, and the per-account job concurrency cap.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits is DefaultCooldown and no job cap.

type Mark

type Mark struct {
	Account           string
	RateLimitedAt     time.Time
	RateLimitedDetail string
	AuthFailedAt      time.Time
	AuthFailedDetail  string
	// AuthFailedToken is the [Fingerprint] of the token that failed.
	AuthFailedToken string
}

Mark is what the pool remembers about one account. A zero time means "never".

type PGStore

type PGStore struct {
	// contains filtered or unexported fields
}

PGStore is the Postgres-backed Store (table cc_account_marks, migration 0003; per owner since 0011).

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG constructs the Postgres store.

func (*PGStore) ClearRateLimited added in v0.225.0

func (s *PGStore) ClearRateLimited(ctx context.Context, owner int64, account string, markedAt time.Time) (bool, error)

ClearRateLimited clears the account's rate-limit mark (timestamp NULL, detail empty) only while its timestamp is still markedAt.

🔴 THE rate_limited_at = $3 PREDICATE IS THE GUARD: it makes the clear a compare-and-clear in ONE statement, so a mark a turn wrote after the caller read markedAt (a newer timestamp) is left standing. markedAt is a value read back from this column, so it compares exactly (microseconds both sides).

func (*PGStore) LiveCounts

func (s *PGStore) LiveCounts(ctx context.Context, owner int64) (map[string]int, error)

LiveCounts returns, per account of owner's, how many of owner's live claude-code agents use it.

🔴 THE owner_id PREDICATE IS THE FIX FOR #64's AUDIT NOTE. Before 0011 this counted "agents under the caller's scope": a user principal saw only its own agents (row-level security), while a scope-all caller counted EVERY owner's agents on an account name. With per-owner accounts the count must be exactly this owner's agents on this owner's account, whoever is asking.

func (*PGStore) MarkAuthFailed

func (s *PGStore) MarkAuthFailed(ctx context.Context, owner int64, account, fingerprint, detail string, at time.Time) error

MarkAuthFailed upserts the account's auth-failure timestamp, detail and the failing token's fingerprint.

func (*PGStore) MarkRateLimited

func (s *PGStore) MarkRateLimited(ctx context.Context, owner int64, account, detail string, at time.Time) error

MarkRateLimited upserts the account's rate-limit timestamp and detail.

func (*PGStore) Marks

func (s *PGStore) Marks(ctx context.Context, owner int64) (map[string]Mark, error)

Marks returns every one of owner's accounts' records.

🔴 EVERY QUERY HERE NAMES THE OWNER. cc_account_marks is under row-level security (0011), which scopes a user principal on its own — but selection may run under a scope-all context, and there an un-predicated read would merge two owners' marks for one account NAME.

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool is selection and marking over a per-owner Source and its Store.

func New

func New(src Source, store Store) (*Pool, error)

New builds a pool with DefaultLimits.

func NewWithLimits

func NewWithLimits(src Source, store Store, l Limits) (*Pool, error)

NewWithLimits builds a pool with explicit limits. It refuses a non-positive cooldown (a knob that would silently disable the cooldown) and a negative cap; a zero cap is "no cap".

func (*Pool) AuthFailure

func (p *Pool) AuthFailure(ctx context.Context, owner int64, account string) (string, error)

AuthFailure reports why owner's account cannot authenticate: a non-empty sentence when its CURRENT token is marked auth-failed (the mark's fingerprint matches it, exactly as Choose skips it), "" when it is usable. An unknown account is ErrUnknownAccount.

⚠ Select's PIN PATH DELIBERATELY DOES NOT CALL THIS: a pin is the operator's override (TestSelectHonoursAPinOverEverySelectionRule). A caller that must not spend an irreversible step on a dead account — the chief replacement, which deletes the old chief first — asks here itself.

func (*Pool) ClearRateLimit added in v0.225.0

func (p *Pool) ClearRateLimit(ctx context.Context, owner int64, account string, markedAt time.Time) (bool, error)

ClearRateLimit clears owner's account's rate_limited mark because a LIVE reading of the account shows it usable (internal/ccusage), and reports whether it did. markedAt is Cooldown.MarkedAt as read BEFORE that reading was taken: the mark is cleared only while it is still that one, so a turn that hits the limit again while the reading is in flight keeps its mark. A zero markedAt clears nothing.

func (*Pool) Cooldown added in v0.225.0

func (p *Pool) Cooldown(ctx context.Context, owner int64, account string) (Cooldown, error)

Cooldown is owner's account's rate-limit cooldown.

func (*Pool) CoolingUntil added in v0.114.0

func (p *Pool) CoolingUntil(ctx context.Context, owner int64, account string) (time.Time, error)

CoolingUntil is Pool.Cooldown's Until: when owner's account stops cooling down, or zero when it is not cooling now.

func (*Pool) FailoverTarget added in v0.114.0

func (p *Pool) FailoverTarget(ctx context.Context, owner int64, from string) (string, bool, error)

FailoverTarget is ChooseFailover over owner's accounts and marks, read now. ok is false when no other account of owner's is usable.

func (*Pool) MarkFailure

func (p *Pool) MarkFailure(ctx context.Context, owner int64, account, failure, detail string) error

MarkFailure records a typed ccd failure against owner's account. Types other than FailureRateLimited and FailureAuthFailed are ignored (nil): only those two say something about the ACCOUNT rather than about the turn.

func (*Pool) Names

func (p *Pool) Names(ctx context.Context, owner int64) ([]string, error)

Names returns owner's account names, sorted. Never the tokens.

func (*Pool) Select

func (p *Pool) Select(ctx context.Context, owner int64, pin string) (string, error)

Select picks the account for owner's new claude-code agent, from OWNER'S accounts only. A non-empty pin is returned as-is when it names one of them, and refused with ErrUnknownAccount otherwise.

func (*Pool) States

func (p *Pool) States(ctx context.Context, owner int64) (map[string]AccountState, error)

States is AccountState for every one of owner's configured accounts, by name. An account that is not configured for owner is absent. It is what the job API's worker-pool selection reads (internal/api createPoolJob): the same marks, under the same "current token" and cooldown rules, as Choose, plus the per-account job cap.

func (*Pool) Token

func (p *Pool) Token(ctx context.Context, owner int64, account string) (string, error)

Token returns the setup-token of owner's account. It is how a pod spec gets its token; ErrUnknownAccount when owner has no such account — including when ANOTHER owner does.

type SharedAccounts added in v0.230.0

type SharedAccounts interface {
	// MarksOwner reports the owner whose marks stand for owner's accounts, and
	// true, when owner's accounts are a shared pool's. false: owner's accounts
	// are its own, and so are its marks.
	MarksOwner(ctx context.Context, owner int64) (int64, bool)
}

SharedAccounts is implemented by a Source under which several owners run on ONE set of accounts (internal/credentials.Plane: the admin and every team in MUSTER_TEAMS_ON_SERVER_POOL share the environment pool).

A rate limit or an auth failure is a property of the ACCOUNT, not of whoever hit it: a team's first agent on the server pool must not be placed on an account the admin's agents already found exhausted. So the marks of a shared pool's accounts are kept under ONE owner, the one MarksOwner names, and every owner on that pool reads and writes them there. Live counts stay per owner.

type Source

type Source interface {
	Accounts(ctx context.Context, owner int64) (map[string]string, error)
}

Source answers which Claude accounts an OWNER's agents may run on: name → setup-token. An empty map is "this owner has none", which Select refuses with ErrNoUsableAccount. internal/credentials.Plane is the production Source (the environment pool for the admin, the member's own tokens for a member); Static is a fixed map.

type Static

type Static struct {
	// contains filtered or unexported fields
}

Static is a fixed account map, the same for every owner: the environment pool. Build it with NewStatic, which validates it.

func NewStatic

func NewStatic(accounts map[string]string) (Static, error)

NewStatic validates an account map. It REFUSES an empty pool, an invalid name and an empty token, so a misconfiguration stops the process at boot instead of building a pod with no credential at the first dispatch.

func (Static) Accounts

func (s Static) Accounts(context.Context, int64) (map[string]string, error)

Accounts implements Source: a copy, whoever asks.

type Store

type Store interface {
	Marks(ctx context.Context, owner int64) (map[string]Mark, error)
	LiveCounts(ctx context.Context, owner int64) (map[string]int, error)
	MarkRateLimited(ctx context.Context, owner int64, account, detail string, at time.Time) error
	MarkAuthFailed(ctx context.Context, owner int64, account, fingerprint, detail string, at time.Time) error
	// ClearRateLimited clears owner's account's rate_limited mark ONLY while
	// its timestamp is still markedAt (a compare-and-clear), and reports
	// whether it did. A newer mark, written after markedAt was read, stands.
	ClearRateLimited(ctx context.Context, owner int64, account string, markedAt time.Time) (bool, error)
}

Store persists marks and counts live agents per account — PER OWNER.

🔴 AN ACCOUNT IS (owner, name), NOT A NAME. Members bring their own accounts (internal/credentials), and two owners may each call one "work": they are different subscriptions, so a rate-limit mark on one must not push the other down the order, and one owner's live agents must not count against the other's. Every method takes the owner and every query names it (migration 0011 keys cc_account_marks on (owner_id, account)).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL