ccfailover

package
v0.288.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 11 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 ccfailover is per-agent Claude ACCOUNT FAILOVER: when a turn on a claude-code agent fails on its account's usage limit or `auth_failed`, the agent is REBOUND to another of its owner's Claude accounts that is usable, instead of staying on the exhausted one until its limit resets.

🔴 A TRANSIENT 429 IS NOT A USAGE LIMIT AND MOVES NOTHING. ccd types both `rate_limited`; which one a failure is, is decided once, by ccpool.AccountFailure, and every caller passes ITS answer as `failure` (the gateway, the job runner). A caller that passed the runtime's raw type would fail agents over on a passing throttle.

Why

A claude-code agent runs on one account: its pod's CLAUDE_CODE_OAUTH_TOKEN. The account cooldown (internal/ccpool) only steers which worker a NEW pool job goes to, so a deployment with ONE worker (or one officer instance) on an exhausted account stalled even with a second account free.

What happens

internal/agentgateway calls Service.AccountFailed after it marks the account (ccpool.Pool.MarkFailure), for every turn shape — a chat, a kickoff, an officer re-prompt, a job. AccountFailed:

  1. ignores every failure but rate_limited (the usage limit, as ccpool.AccountFailure reads it) and auth_failed;
  2. does nothing when failover is off (MUSTER_AGENT_CC_FAILOVER=off), or the agent is PINNED (its account was named at creation — a dispatch pin, the chief's, an officer's `cc_account`) and has not opted in (cc_failover);
  3. picks the target with ccpool.ChooseFailover — another account of the owner's that is neither auth_failed for its current token nor cooling down; never rate-limited first, then rate-limited longest ago, then the name. None usable (every account cooling): nothing happens, as before;
  4. moves the agent (agentprovision.Adapter.Rebind): the row's cc_account changes (conditionally on the old one) and its spec is re-applied, so its pod restarts on the new token, keeping its volume, namespace and identity;
  5. records an event (cc_account_failovers) and logs one line — account NAMES, the reason and the reset time, never a token.

A pool submission overrides a pin (AccountFailedForPool)

A worker pool refuses a job upfront when every worker's account is cooling down or failed authentication; a refused submission runs no turn, so no failover fires and the pool stays refused until the account resets (2026-11-07: ~2.5 days, with a second account usable the whole time). So the job API fails one such worker over itself (internal/api createPoolJob) through Service.AccountFailedForPool, which is AccountFailed except that a pool worker's PIN does not stop the move: for a pool, nothing being stuck wins over the account it was created on (operator, 2026-11-07). It applies to agents in a worker pool only; a named agent, an officer instance and the chief keep their pin as before, and failover off (MUSTER_AGENT_CC_FAILOVER=off) still moves nothing.

Idempotent on (agent, from account)

Two turns on one agent failing at once produce ONE rebind: in this process a per-agent lock and a re-read of the row under it (an agent no longer on the failed account was already moved); across processes the row's conditional move (WHERE cc_account = from). A later caller for the same (agent, from) gets Rebound false and Moved true, with the move's details from a short memo — which is how the job runner, which also asks after the gateway already did, learns where its agent went and which pod it replaced.

No fail-back

Once moved, an agent stays on its new account when the old one resets: a move back would restart its pod again for nothing. It moves again only when the new account in turn fails.

Why a pod restart, not a token re-read

The token is an environment variable the CLI (and each job lane's CLI) is started with. A cheaper path — ccd re-reading a mounted Secret file and restarting its CLIs — would need new ccd code, a Secret volume the kubelet refreshes on its own schedule (up to a minute late, and never for a subPath mount), and would still restart every CLI the pod runs. The pod restart is the path muster already uses for a rotated token (Stop → Start), costs a cold start (the running CLI session restarts; the volume, transcripts and checkout are kept), and leaves exactly one place the token is written (agentspec, the per-agent Secret).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Eligible added in v0.257.0

func Eligible(ag agents.Agent) bool

Eligible reports whether ag is an agent a failover can move at all: a claude-code agent running on a named account. One that is not (another kind, or no account — a host-run instance) is never moved, whatever Service.Allowed says.

Types

type Agents

type Agents interface {
	Get(ctx context.Context, id int64) (agents.Agent, error)
}

Agents reads an agent's row.

type Config

type Config struct {
	// Enabled is MUSTER_AGENT_CC_FAILOVER (default on). Off: nothing is moved.
	Enabled  bool
	Pool     Pool
	Agents   Agents
	Rebinder Rebinder
	// Store is optional: without one a rebind is logged but not recorded.
	Store Store
	// Instances lists the backend's instances, for AwaitRebound. Optional:
	// without it AwaitRebound returns at once.
	Instances func(ctx context.Context) ([]provision.Instance, error)
	Logger    *log.Logger
	// Now is a test seam (time.Now when nil).
	Now func() time.Time
	// ReadyPoll and ReadyWait bound AwaitRebound (defaults 3s and 5m).
	ReadyPoll, ReadyWait time.Duration
}

Config builds a Service.

type Event

type Event struct {
	ID        int64     `json:"id"`
	OwnerID   int64     `json:"-"`
	AgentID   int64     `json:"agent_id"`
	AgentName string    `json:"agent"`
	From      string    `json:"from"`
	To        string    `json:"to"`
	Reason    string    `json:"reason"`
	ResetsAt  time.Time `json:"resets_at,omitzero"`
	At        time.Time `json:"at"`
}

Event is one recorded rebind.

func (Event) String

func (e Event) String() string

String is the event's one log line: names, reason and reset — never a token (an Event holds none).

type PGStore

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

PGStore is the Postgres Store (table cc_account_failovers, migration 0066).

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG constructs the Postgres store.

func (*PGStore) ForAgent

func (s *PGStore) ForAgent(ctx context.Context, agentID int64, limit int) ([]Event, error)

ForAgent is agentID's rebinds, newest first, at most limit (1-100).

func (*PGStore) Record

func (s *PGStore) Record(ctx context.Context, e Event) (Event, error)

Record inserts one rebind, owned by the agent's owner.

⚠ owner_id IS THE AGENT'S, READ IN THE INSERT, NOT THE CALLER'S: a failover runs under whichever principal the failing turn had (the kickoff deliverer's is the system's, which names no user), and the row belongs to the agent's owner whoever reported the failure.

type Policy

type Policy func(agents.Agent) (pinned, optIn bool)

Policy reports, for an agent, whether its account is pinned and whether it opted in to failover anyway, beyond what its row says (the officer runtime answers for an officer's configured `cc_account` / `cc_failover`).

type Pool

type Pool interface {
	FailoverTarget(ctx context.Context, owner int64, from string) (string, bool, error)
	CoolingUntil(ctx context.Context, owner int64, account string) (time.Time, error)
}

Pool is the part of ccpool.Pool a failover reads.

type Prepare

type Prepare func(context.Context, agents.Agent) error

Prepare runs after a move and before the re-apply (agentprovision.Adapter.Rebind).

type Rebinder

type Rebinder interface {
	Rebind(ctx context.Context, agentID int64, from, to string, prepare func(context.Context, agents.Agent) error) (agentprovision.RebindResult, error)
}

Rebinder is the lifecycle half (agentprovision.Adapter.Rebind).

type Result

type Result struct {
	// AgentName is the agent's name ("" when it could not be read).
	AgentName string
	// From is the account the failure was reported for.
	From string
	// To is the account the agent is on after the call, when it is not From.
	To string
	// Moved: the agent is on To, not From — by this call or an earlier one.
	Moved bool
	// Rebound: THIS call moved it.
	Rebound bool
	// PrevInstance is the instance that ran before the move ("" unknown).
	PrevInstance string
	// Event is the recorded rebind, when Moved by a call this service made.
	Event Event
	// Why is why the agent was not moved ("" when it was).
	Why string
	// NoTarget: not moved because no other account of the owner's is usable.
	// Every agent of that owner on the same account gets the same answer, so a
	// caller trying several of them stops there (internal/api
	// failoverBlockedWorker).
	NoTarget bool
}

Result is what Service.AccountFailed found or did.

type Service

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

Service is the failover.

func New

func New(cfg Config) (*Service, error)

New builds a service. Pool, Agents and Rebinder are required.

func (*Service) AccountFailed

func (s *Service) AccountFailed(ctx context.Context, agentID int64, account, failure, detail string) Result

AccountFailed is the failover's entry point: a turn on agentID, running on account, failed with failure (ccpool.AccountFailure of ccd's typed error, so rate_limited only for a usage limit) and detail (its message). It never returns an error: what it could not do is in Result.Why and the log.

func (*Service) AccountFailedForPool added in v0.170.0

func (s *Service) AccountFailedForPool(ctx context.Context, agentID int64, account, failure, detail string) Result

AccountFailedForPool is AccountFailed for a WORKER POOL's member, called by a pool submission that found no worker it could use: the member's pin does not stop the move (see the package doc). An agent in no pool is treated exactly as AccountFailed treats it, pin included.

func (*Service) Allowed

func (s *Service) Allowed(ag agents.Agent) (bool, string)

Allowed reports whether ag may be failed over, and why not.

func (*Service) AwaitRebound

func (s *Service) AwaitRebound(ctx context.Context, r Result) error

AwaitRebound waits until a moved agent's replacement instance is ready: an instance of r.AgentName that is Ready and is not r.PrevInstance. It returns nil at once when the service cannot list instances, and an error when ctx ends or ReadyWait passes first.

func (*Service) Enabled

func (s *Service) Enabled() bool

Enabled reports MUSTER_AGENT_CC_FAILOVER.

func (*Service) Events

func (s *Service) Events(ctx context.Context, agentID int64, limit int) ([]Event, error)

Events is agentID's recorded rebinds, newest first (none without a store).

func (*Service) NoteAccountFailure

func (s *Service) NoteAccountFailure(ctx context.Context, agentID int64, account, failure, detail string)

NoteAccountFailure is AccountFailed for a caller that needs no answer (internal/agentgateway, after it marks the account).

func (*Service) Rebinding added in v0.170.0

func (s *Service) Rebinding(agentID int64) (Result, bool)

Rebinding is agentID's latest move made by THIS process within the last memoTTL, so a job about to run on it can wait for its replacement pod (AwaitRebound) instead of sending a turn into a restart. ok is false when there is none.

func (*Service) UseHooks

func (s *Service) UseHooks(policy Policy, prepare Prepare)

UseHooks installs the pin policy and the pre-apply hook (internal/api's officer runtime). Either may be nil.

type Store

type Store interface {
	Record(ctx context.Context, e Event) (Event, error)
	ForAgent(ctx context.Context, agentID int64, limit int) ([]Event, error)
}

Store records rebinds.

Jump to

Keyboard shortcuts

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