> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch16-model-providers-and-failover/16.5-source-deep-dive-auth-profile-rotation.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 16.5 Source Deep Dive: Auth Profile Rotation, Cooldown, and Degradation

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~266,000 tokens, Output \~13,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

This is OpenClaw's most distinctive subsystem, and the origin of §45.1's first pattern.

The scenario: under one provider you've configured a Claude Pro OAuth subscription, a Codex subscription, and three API keys. One of them gets rate-limited. What should the system do?

The answer is **four mechanisms coordinating across four time scales**:

```
profile rotation (seconds)  →  model fallback (this turn)  →  cooldown probing (30s throttle)  →  natural cooldown expiry (minutes to hours)
```

This section unpacks each layer.

## 16.5.1 Layer One: Profile Ordering — Who Goes First

`resolveAuthProfileOrder()` (`src/agents/auth-profiles/order.ts:67`).

Its first action is to **clear expired cooldowns**: `clearExpiredCooldowns` zeroes out cooldowns that have elapsed, **and resets the error count along with them**.

Why reset the count too? The comment cites issue #3604:

> Without clearing the count, the next transient failure jumps straight to a very long cooldown.

That's circuit-breaker "half-open to closed" semantics. After a cooldown ends the account should be retried as healthy, not carrying historical baggage — otherwise an account that failed three times in the past enters a one-hour cooldown after a single failure post-recovery and effectively never comes back.

Then ordering:

```ts
// src/agents/auth-profiles/order.ts:177-188
// Sort available profiles by type preference, then by lastUsed (oldest first = round-robin within type)
const scored = available.map((profileId) => {
  const type = store.profiles[profileId]?.type;
  const typeScore = type === "oauth" ? 0 : type === "token" ? 1 : type === "api_key" ? 2 : 3;
  const lastUsed = store.usageStats?.[profileId]?.lastUsed ?? 0;
  return { profileId, typeScore, lastUsed };
});
```

Those nine lines encode a cost strategy:

| Type      | Score                | Billing                               |
| --------- | -------------------- | ------------------------------------- |
| `oauth`   | 0 (highest priority) | **Subscription — zero marginal cost** |
| `token`   | 1                    | —                                     |
| `api_key` | 2                    | **Metered**                           |

**OAuth subscriptions come before API keys**, and within a type, ordering is round-robin by `lastUsed` (least recently used first).

In plain terms: **use up the flat-rate allowance first, then spend metered money.** That cost optimization is written directly into the sort function as default behavior, not an optional feature.

The intra-type round-robin matters too — it spreads load across accounts instead of hammering the first one until it's rate-limited. (Recall the test filename from §43.4.4: `does-not-prioritize-lastgood-round-robin-ordering` — **it deliberately does not prefer the account that just worked**, for exactly this reason.)

Two details:

* **Cooling profiles aren't removed, they're moved to the back** (sorted by cooldown expiry ascending) — kept as a last resort;
* **A user's explicit ordering is respected**; only cooldown reordering is applied on top.

## 16.5.2 Layer Two: Failure Accounting and the Cooldown Curve

`markAuthProfileFailure()` (`auth-profiles/usage.ts:460`) updates persisted `usageStats` under a file lock, distinguishing two failure classes.

### Transient failures: exponential cooldown

```ts
// src/agents/auth-profiles/usage.ts:272-278
export function calculateAuthProfileCooldownMs(errorCount: number): number {
  const normalized = Math.max(1, errorCount);
  return Math.min(
    60 * 60 * 1000, // 1 hour max
    60 * 1000 * 5 ** Math.min(normalized - 1, 3),
  );
}
```

For `rate_limit` / `overloaded` errors the cooldown progresses:

```
1min → 5min → 25min → 1h (cap)
```

Base 5, exponent capped at 3. Four levels is enough — longer would amount to permanently disabling the account.

### Permanent failures: heavier treatment

`billing` / `auth_permanent` use `disabledUntil` with a **5-hour base and 24-hour cap**, overridable per provider.

The distinction is straightforward: for insufficient balance or a revoked key, retrying in a minute is pointless.

### Two critical details

**Detail one: the active window cannot be extended.**

The comment reads: *"retries within the window cannot push recovery further out."*

Meaning: while an account is cooling down, no amount of retrying pushes its recovery time back.

**Why does that matter?** Without the constraint, a client that keeps retrying continually refreshes the cooldown's start point and the account **never recovers** — a retry storm locking itself out.

**Detail two: timeouts are never charged.**

`run.ts:769-778`'s comment is explicit:

> A timeout is a transport/model-path problem, not an account health signal. Charging it "poisons" the fallback models under the same provider.

Concretely: a `gpt-5.3` request times out; if that's recorded as an account failure, the account cools down and `gpt-5.2` becomes unusable too — **even though gpt-5.2 was fine**.

This is the "precise error attribution" §45.1 keeps returning to. Get attribution wrong and one network blip drags an entire provider's models down with it.

### Runtime actions

| When                                                      | Function                                                           | Action                                            |
| --------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------- |
| Prompt failed and `classifyFailoverReason` says rotatable | `advanceAuthProfile()` (`run.ts:633-658`)                          | Advance to the next profile, reset thinking state |
| All profiles cooling                                      | `allowTransientCooldownProbe` (`run.ts:687-696`)                   | Permit picking one cooling profile as a **probe** |
| Successful completion                                     | `markAuthProfileGood` + `markAuthProfileUsed` (`run.ts:1495-1507`) | Update health state and the round-robin pointer   |

The "probe when everything is cooling" rule is a necessary backstop: otherwise, once all accounts enter cooldown simultaneously (say, from a batch of network-induced failures), the system hard-refuses service until the earliest cooldown expires.

### Three supporting facilities

| File                                 | Purpose                                                                  |
| ------------------------------------ | ------------------------------------------------------------------------ |
| `api-key-rotation.ts`                | A lightweight key rotation loop for non-agent paths (e.g. model probing) |
| `auth-health.ts`                     | Computes OAuth token expiring / expired state for `/status` and doctor   |
| `auth-profiles/external-cli-sync.ts` | Syncs tokens from Claude Code / Codex CLI local credentials              |

The last one is genuinely handy: if you're already logged in via Claude Code, OpenClaw can reuse that credential instead of running OAuth again.

## 16.5.3 Layer Three: Model-Level Degradation

Profile rotation handles "same model, different account." **Switching models** is the job of the outer `runWithModelFallback()` (`src/agents/model-fallback.ts:502`), triggered when the inner layer throws `FailoverError`.

The candidate chain is the primary model plus `agents.defaults.model.fallbacks` (overridable per agent; **an explicit empty array disables fallback**).

One important rule: **fallbacks are explicit user intent and are not filtered by the model allowlist.** If you put it in the fallback chain, you meant it.

### The interesting part: deciding when everything is cooling

`resolveCooldownDecision` (`model-fallback.ts:428-500`) branches by failure reason:

| Cooldown reason             | Decision                                                                                                                                                                                                                                   |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `auth` / `auth_permanent`   | **Skip every model under that provider** — the account is broken; switching models won't help                                                                                                                                              |
| `billing`                   | **Semi-persistent**: with a single provider configured, probe with a 30-second throttle (the user may have just topped up); with fallbacks available, probe only within 2 minutes of cooldown expiry, so the fallback chain takes priority |
| `rate_limit` / `overloaded` | The primary model may be probed (30s throttle + **at most one probe per provider per fallback run**); sibling models under the same provider may also be tried, because **rate limits are frequently model-scoped**                        |

That third row's insight is practical: **rate limits are usually per-model, not per-account.** `claude-opus` being limited often leaves `claude-sonnet` on the same account perfectly usable — so one model's limit shouldn't write off the whole provider.

The `billing` handling is thoughtful too: a user who sees "insufficient balance" will go top up and expect it to work immediately, so a 30-second-throttled probe channel stays open. But when a fallback chain exists, degradation takes priority — right now the user wants *working*, not *best*.

### Short backoff in overload scenarios

```ts
// src/agents/pi-embedded-runner/run.ts:86-93
// Keep overload pacing noticeable enough to avoid tight retry bursts, but short
// enough that fallback still feels responsive within a single turn.
const OVERLOAD_FAILOVER_BACKOFF_POLICY: BackoffPolicy = {
  initialMs: 250,
  maxMs: 1_500,
  factor: 2,
  jitter: 0.2,
};
```

This prevents burning through every candidate within one second. Note the comment states the dilemma directly: **too long and the user is still waiting inside the same turn; too short and it's a retry storm.** 250 ms start, 1.5 s cap, 20% jitter is the answer to that trade-off.

The `jitter: 0.2` term prevents multiple sessions from backing off and retrying in lockstep (the thundering-herd effect).

## 16.5.4 The Four Scales Together

```
profile rotation (seconds)
   ↓ every account for this model is exhausted
model degradation (within the turn)
   ↓ the fallback chain is exhausted too
cooldown probing (30s throttle, testing for recovery)
   ↓ probing fails too
natural cooldown expiry (1min → 5min → 25min → 1h; billing class 5h → 24h)
```

**Four time scales each own a segment, with no overlap.** That layering is what lets this system stay stable under real traffic — with only one layer (say, exponential backoff alone) recovery is either too slow or retries too dense.

### Observability is a requirement, not a bonus

With this many branches in the failover logic, debugging without observability is impossible. Hence three dedicated structured logs:

| File                                 | Records                   |
| ------------------------------------ | ------------------------- |
| `model-fallback-observation.ts`      | Model-level decisions     |
| `run/failover-observation.ts`        | Run-level failover        |
| `auth-profiles/state-observation.ts` | Profile state transitions |

**Every skip / rotate / fallback can be reconstructed from the logs with its full decision rationale.**

This is exactly §44.2.4's warning in practice: **copy the degradation chain and you must copy the observability**, or you end up with a system that never errors and is inexplicably slow.

## 16.5.5 A Prerequisite: Model Resolution

Rotation and degradation both presuppose knowing what models exist.

`models-config.ts` calls `ensureOpenClawModelsJson()` before each run (`run.ts:306`), merging providers from config (static definitions plus discovery via `models-config.providers.discovery.ts`) into a `models.json` pi can read.

Then `resolveModel()` in `pi-embedded-runner/model.ts` resolves a `Model` object through pi's `ModelRegistry`, returning it alongside `AuthStorage`.

**Runtime API keys are injected via `authStorage.setRuntimeApiKey()` rather than written into config files** — which is what makes rotation possible, and avoids persisting keys to disk.

### An easy trap: model ID parsing rules

Model references are **split on the first `/` to find the provider**.

So OpenRouter-style multi-segment ids must carry the provider prefix:

```
openrouter/moonshotai/kimi-k2
└─provider─┘└──── model id ────┘
```

Writing `moonshotai/kimi-k2` parses the provider as `moonshotai` and then fails to find it.

The dozens of `*-models.ts` files in the directory (`byteplus-models.ts`, `venice-models.ts`, `together-models.ts`…) are each vendor's static catalog and probing logic.

Providers needing short-lived tokens, like GitHub Copilot, have their own refresh loop (`run.ts:464-541`): **renew 5 minutes early, retry with backoff on failure.** The early margin matters — don't wait until the token expires to swap it, because in-flight requests will already have failed.

***

## Section Summary

1. **Profile ordering encodes a cost strategy in code**: OAuth subscriptions (zero marginal cost) → token → API key (metered), with round-robin by `lastUsed` within a type to spread load; cooling profiles move to the back rather than being removed.
2. **Clearing a cooldown must also clear the error count** (#3604), or the circuit breaker can't go half-open to closed and the account effectively never returns.
3. **Two cooldown curves**: transient failures at `1min → 5min → 25min → 1h`; `billing` / `auth_permanent` use `disabledUntil` with a 5h base and 24h cap.
4. **Two critical disciplines**: **the active window cannot be extended** (preventing a retry storm from permanently locking an account out) and **timeouts are never charged** (or one network blip poisons every fallback model under that provider).
5. **Model-level degradation branches by cooldown reason**: auth-class skips the entire provider, billing-class keeps a 30-second-throttled probe channel, and **rate-limit-class may try sibling models under the same provider** (limits are usually model-scoped).
6. **Four time scales each own a segment**: profile rotation (seconds) → model degradation (this turn) → cooldown probing (30s throttle) → cooldown expiry (minutes to hours); overload backoff runs 250ms–1.5s with 20% jitter against thundering herd.
7. **Three structured observation logs are a requirement, not a bonus** — with this many branches, you cannot debug without the ability to reconstruct decision rationale.
8. Supporting infrastructure: `models.json` re-synthesized before every run, **runtime keys injected rather than persisted**, model IDs **split on the first `/` for the provider** (OpenRouter multi-segment ids need the prefix), and Copilot-class short-lived tokens **renewed 5 minutes early**.
