Skip to content

feat: Provider circuit breaker for quota exhaustion - #64127

Closed
dodge1218 wants to merge 5 commits into
openclaw:mainfrom
dodge1218:feat/provider-circuit-breaker
Closed

dodge1218 wants to merge 5 commits into
openclaw:mainfrom
dodge1218:feat/provider-circuit-breaker

Conversation

@dodge1218

@dodge1218 dodge1218 commented Apr 10, 2026 •

Copy link
Copy Markdown

Resolves #64085

This PR introduces proper handling for daily/weekly/monthly quota exhaustion errors:

  1. Detects periodic usage limits and classifies them as "quota_exhausted" (rather than transient rate_limit).
  2. Routes quota_exhausted through the same persistent backoff lane as billing failures (bypassing the provider for 5-24 hours).
  3. Adds a new agent:provider_tripped internal hook event whenever a provider enters the disabled lane, allowing plugins (like ContextClaw) to observe and react to provider death.

Real behavior proof

Behavior or issue addressed: OpenClaw previously treated periodic quota-exhaustion messages as ordinary transient rate limits, so a provider that had exhausted a daily/weekly/monthly usage window could keep being retried through the short rate-limit lane. This patch classifies those cases as quota_exhausted, routes them through the long disabled-lane backoff, and emits agent:provider_tripped when a provider enters that disabled lane.

Real environment tested:

  • Branch/head: feat/provider-circuit-breaker at 6f2493db9043f43a30a0b59def58a9d37206a222, then lint-only follow-up applied locally before push.
  • Runtime path: real OpenClaw agent/auth-profile/failover modules from this branch, run through the repository's Node/Vitest project harness.
  • Before-patch incident context: ScientificProgrammer reported a real OpenClaw deployment where a Gemini monthly spending-cap condition produced repeated RESOURCE_EXHAUSTED cascades across 26 runIds and about 390 exhausted-provider events.

Exact steps or command run after the patch:

  • Ran npm run format:check -- src/agents/auth-profiles/state-observation.ts.
  • Ran pnpm lint --threads=8.
  • Ran pnpm test src/agents/failover-error.test.ts src/agents/auth-profiles/usage.test.ts src/agents/model-fallback.probe.test.ts src/agents/embedded-agent-helpers.isbillingerrormessage.test.ts.

Evidence after fix: Copied local command output from the after-patch run:

format:check src/agents/auth-profiles/state-observation.ts: passed
pnpm lint --threads=8: passed
focused runtime-path suite:
  src/agents/failover-error.test.ts
  src/agents/auth-profiles/usage.test.ts
  src/agents/model-fallback.probe.test.ts
  src/agents/embedded-agent-helpers.isbillingerrormessage.test.ts
result: 314 assertions passed

Observed result after fix: The quota-exhaustion classifier lets quota text win over generic HTTP 429 rate-limit handling, active quota-disabled providers resolve as quota_exhausted, the 30-second billing recovery probe is not reused for quota exhaustion, and quota-disabled providers only probe near disabled-window expiry. The agent:provider_tripped hook dispatch path now satisfies the internal hook contract and narrows async dispatch errors safely.

What was not tested: I did not retest against a live already-exhausted Gemini billing account after this patch. The real-world production incident is included as before-patch validation of the cascade shape; the after-patch evidence is local OpenClaw runtime-path evidence.

@dodge1218
dodge1218 requested a review from a team as a code owner April 10, 2026 05:51
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Apr 10, 2026
@greptile-apps

greptile-apps Bot commented Apr 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a quota_exhausted failure reason to distinguish periodic usage-limit errors (daily/weekly/monthly quotas) from transient rate limits, routing them through the 5–24 h billing-style disabled lane rather than the short cooldown lane. It also adds an agent:provider_tripped internal hook event so plugins like ContextClaw can observe when a provider enters the disabled state.

  • P1 — type error in state-observation.ts: createInternalHookEvent is called with undefined as the sessionKey argument, which is typed string. This will fail pnpm tsgo / pnpm build and silently violates the InternalHookEvent contract at runtime. Fix: pass \"\" or another sentinel string.

Confidence Score: 4/5

Not safe to merge as-is — the undefined sessionKey argument is a compile-time type error that will break pnpm tsgo and pnpm build.

One P1 finding: passing undefined where string is required in createInternalHookEvent is a TypeScript type error that will fail the build gate. All other changes (quota classification, backoff policy, failover policy, hook types) are logically sound and consistent. Score is 4 pending that one fix.

src/agents/auth-profiles/state-observation.ts (undefined sessionKey); src/hooks/internal-hooks.ts (missing isAgentProviderTrippedEvent guard)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/state-observation.ts
Line: 64

Comment:
**`undefined` passed for `sessionKey: string` — type error**

`createInternalHookEvent` expects its third argument as `string`, not `string | undefined`. Passing `undefined` here is a TypeScript type error that will fail `pnpm tsgo` / `pnpm build`. Provider-level events have no natural session key, but the contract must still be satisfied — use an empty string or a sentinel like `""` to stay within the type.

```suggestion
        createInternalHookEvent("agent", "provider_tripped", "", {
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/hooks/internal-hooks.ts
Line: 40-44

Comment:
**Missing `isAgentProviderTrippedEvent` type guard**

Every other exported hook event type (`AgentBootstrapHookEvent`, `GatewayStartupHookEvent`, `MessageReceivedHookEvent`, etc.) has a corresponding `isXxxEvent` narrowing function. `AgentProviderTrippedHookEvent` is the only one without one, which breaks the established plugin API pattern and makes it harder for plugin authors to safely consume this event.

Consider adding:
```ts
export function isAgentProviderTrippedEvent(
  event: InternalHookEvent,
): event is AgentProviderTrippedHookEvent {
  if (!isHookEventTypeAndAction(event, "agent", "provider_tripped")) {
    return false;
  }
  const context = getHookContext<AgentProviderTrippedHookContext>(event);
  if (!context) return false;
  return hasStringContextField(context, "provider") && hasStringContextField(context, "reason");
}
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "feat: Provider circuit breaker for quota..." | Re-trigger Greptile

if (windowType === "disabled" && !windowReused) {
// Fire internal hook async so ContextClaw can observe provider death
triggerInternalHook(
createInternalHookEvent("agent", "provider_tripped", undefined, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 undefined passed for sessionKey: string — type error

createInternalHookEvent expects its third argument as string, not string | undefined. Passing undefined here is a TypeScript type error that will fail pnpm tsgo / pnpm build. Provider-level events have no natural session key, but the contract must still be satisfied — use an empty string or a sentinel like "" to stay within the type.

Suggested change
createInternalHookEvent("agent", "provider_tripped", undefined, {
createInternalHookEvent("agent", "provider_tripped", "", {
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/state-observation.ts
Line: 64

Comment:
**`undefined` passed for `sessionKey: string` — type error**

`createInternalHookEvent` expects its third argument as `string`, not `string | undefined`. Passing `undefined` here is a TypeScript type error that will fail `pnpm tsgo` / `pnpm build`. Provider-level events have no natural session key, but the contract must still be satisfied — use an empty string or a sentinel like `""` to stay within the type.

```suggestion
        createInternalHookEvent("agent", "provider_tripped", "", {
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +40 to +44
export type AgentProviderTrippedHookEvent = InternalHookEvent & {
type: "agent";
action: "provider_tripped";
context: AgentProviderTrippedHookContext;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Missing isAgentProviderTrippedEvent type guard

Every other exported hook event type (AgentBootstrapHookEvent, GatewayStartupHookEvent, MessageReceivedHookEvent, etc.) has a corresponding isXxxEvent narrowing function. AgentProviderTrippedHookEvent is the only one without one, which breaks the established plugin API pattern and makes it harder for plugin authors to safely consume this event.

Consider adding:

export function isAgentProviderTrippedEvent(
  event: InternalHookEvent,
): event is AgentProviderTrippedHookEvent {
  if (!isHookEventTypeAndAction(event, "agent", "provider_tripped")) {
    return false;
  }
  const context = getHookContext<AgentProviderTrippedHookContext>(event);
  if (!context) return false;
  return hasStringContextField(context, "provider") && hasStringContextField(context, "reason");
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/hooks/internal-hooks.ts
Line: 40-44

Comment:
**Missing `isAgentProviderTrippedEvent` type guard**

Every other exported hook event type (`AgentBootstrapHookEvent`, `GatewayStartupHookEvent`, `MessageReceivedHookEvent`, etc.) has a corresponding `isXxxEvent` narrowing function. `AgentProviderTrippedHookEvent` is the only one without one, which breaks the established plugin API pattern and makes it harder for plugin authors to safely consume this event.

Consider adding:
```ts
export function isAgentProviderTrippedEvent(
  event: InternalHookEvent,
): event is AgentProviderTrippedHookEvent {
  if (!isHookEventTypeAndAction(event, "agent", "provider_tripped")) {
    return false;
  }
  const context = getHookContext<AgentProviderTrippedHookContext>(event);
  if (!context) return false;
  return hasStringContextField(context, "provider") && hasStringContextField(context, "reason");
}
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 026705940a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 734 to 736
const disabledFailureReason =
params.reason === "billing" || params.reason === "auth_permanent" ? params.reason : null;
params.reason === "billing" || params.reason === "auth_permanent" || params.reason === "quota_exhausted" ? params.reason : null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add quota_exhausted to failure-reason scoring allowlist

This branch stores quota_exhausted as a disabled reason, but resolveProfilesUnavailableReason only scores reasons present in FAILURE_REASON_SET (derived from FAILURE_REASON_PRIORITY), which still omits quota_exhausted. In practice, profiles disabled for quota exhaustion are inferred as unknown, so cooldown handling can take the transient path (including probing behavior and same-provider fallback decisions) instead of the intended persistent-disabled behavior.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S and removed size: XS labels Apr 10, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6510554dce

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 721 to 723
if (isPeriodicUsageLimitErrorMessage(raw)) {
return toReasonClassification(isBillingErrorMessage(raw) ? "billing" : "rate_limit");
return toReasonClassification("quota_exhausted");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor quota_exhausted when classifying HTTP 429 failures

This new quota_exhausted classification is computed from message text, but in classifyFailoverSignal any inferred HTTP status takes precedence, and status 429 is still forced to rate_limit. In practice, payloads like 429 ... daily/weekly limit reached never stay in the new lane, so they continue to take transient cooldown handling instead of the intended disabled/backoff path.

Useful? React with 👍 / 👎.

Comment thread src/agents/model-fallback.ts Outdated
Comment on lines 593 to 595
if (inferredReason === "billing" || inferredReason === "quota_exhausted") {
const shouldProbeSingleProviderBilling =
params.isPrimary &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop probing single-provider quota outages every 30 seconds

Including quota_exhausted in this billing branch reuses shouldProbeSingleProviderBilling, which allows attempts whenever the probe throttle opens (every MIN_PROBE_INTERVAL_MS, 30s) for single-provider setups with no fallbacks. That means quota-disabled providers are retried repeatedly throughout multi-hour disabled windows, reintroducing the 429 retry loop this circuit-breaker is intended to prevent.

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 3, 2026, 4:57 PM ET / 20:57 UTC.

Summary
The PR adds quota_exhausted classification/backoff for periodic provider quota errors and emits an agent:provider_tripped internal hook when a provider enters the disabled lane.

PR surface: Source +77, Tests +80. Total +157 across 14 files.

Reproducibility: yes. from source inspection: the PR adds a new failover reason while adjacent allowlists and schemas enumerate old reasons and would not preserve the new one. A live after-fix exhausted-provider reproduction is still missing.

Review metrics: 2 noteworthy metrics.

  • New failover reason: 1 added. A closed reason code crosses runtime, plugin SDK, gateway, cron, and docs surfaces, so explicit mappers must stay aligned before merge.
  • New internal hook event: 1 added. The hook is observable plugin-facing surface and maintainers should review the event name, payload, and dispatch point before merge.

Stored data model
Persistent data-model change detected: serialized state: src/agents/auth-profiles/state-observation.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦐 gold shrimp
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add redacted after-fix live output, logs, or a realistic exhausted-provider runtime proof.
  • Update the explicit reason mappings, schemas, docs, and tests for quota_exhausted.
  • Refresh the dirty branch against current main.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body supplies focused lint/Vitest output and before-patch incident context, but no after-fix live output, redacted logs, terminal run, or realistic exhausted-provider runtime proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] The branch is currently dirty/conflicting against main, so maintainers need a refreshed merge result before relying on the exact integration behavior.
  • [P1] The PR intentionally changes periodic quota-shaped 429s from short rate_limit handling to a multi-hour disabled-provider path; over-broad matching could make a configured provider unavailable for hours.
  • [P1] The new agent:provider_tripped hook is observable plugin-facing surface and needs maintainer acceptance of event name, payload, and dispatch point.
  • [P1] The supplied proof is local lint/Vitest output plus before-patch incident context, not after-fix live or realistic exhausted-provider runtime proof.

Maintainer options:

  1. Complete reason propagation (recommended)
    Add quota_exhausted to every explicit mapper, protocol schema, persisted run-log allowlist, and focused test before merge.
  2. Keep the existing reason contract
    If maintainers do not want a new public/internal reason yet, leave periodic quota errors in the rate_limit contract and solve retry storms through a narrower cooldown-policy change.
  3. Accept downgraded surfaces deliberately
    Maintainers could intentionally let some surfaces report quota_exhausted generically, but that should be an explicit compatibility choice with docs.

Next step before merge

  • [P1] A narrow repair exists for reason propagation, but the external PR also needs contributor real-behavior proof, branch refresh, and maintainer product/API acceptance before any merge path.

Security
Cleared: The diff touches TypeScript runtime/test surfaces only and does not add dependency, CI, secret, permission, or supply-chain changes.

Review findings

  • [P2] Propagate quota_exhausted through all reason allowlists — src/agents/embedded-agent-helpers/types.ts:7
Review details

Best possible solution:

Keep the quota-exhausted lane only if the new reason is propagated through all failover, protocol, result, docs, and error surfaces, then refresh the branch and require maintainer acceptance plus real after-fix runtime proof.

Do we have a high-confidence way to reproduce the issue?

Yes from source inspection: the PR adds a new failover reason while adjacent allowlists and schemas enumerate old reasons and would not preserve the new one. A live after-fix exhausted-provider reproduction is still missing.

Is this the best way to solve the issue?

No, not yet; the PR is a plausible owner-boundary fix, but it is incomplete until the new reason is propagated and maintainers accept the long-disable provider semantics.

Full review comments:

  • [P2] Propagate quota_exhausted through all reason allowlists — src/agents/embedded-agent-helpers/types.ts:7
    Adding quota_exhausted to FailoverReason creates a new closed reason code, but several explicit consumers still only accept the old set: OpenAI-compatible errors would fall back to internal error, embedded result fallback would drop provider payloads with this reason, and cron schemas/run-log normalization would reject it. Please update those mappings and focused tests before merge.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 010b61746379.

Label changes

Label justifications:

  • P2: The PR targets provider failover behavior with meaningful but bounded blast radius.
  • merge-risk: 🚨 compatibility: The PR changes the closed failover reason contract while current docs/protocol surfaces still describe periodic quota limits as rate_limit.
  • merge-risk: 🚨 auth-provider: The PR changes auth-profile failure routing and disabled-provider behavior for quota-shaped provider errors.
  • merge-risk: 🚨 availability: An over-broad quota match could skip a configured provider for hours instead of using the current short retry path.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body supplies focused lint/Vitest output and before-patch incident context, but no after-fix live output, redacted logs, terminal run, or realistic exhausted-provider runtime proof. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +77, Tests +80. Total +157 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 10 81 4 +77
Tests 4 90 10 +80
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 171 14 +157

What I checked:

  • Policy read: Root AGENTS.md and src/agents/AGENTS.md were read; root policy treats provider routing, auth-profile state, plugin hooks, protocol schemas, fallback behavior, and new observable surfaces as compatibility-sensitive. (AGENTS.md:24, 010b61746379)
  • Live PR state: Live GitHub shows the PR is open, external-authored, maintainer-editable, head 2d8d9f4, and mergeable state is CONFLICTING/DIRTY. (2d8d9f4235e2)
  • New failover reason surface: Current main's FailoverReason union has no quota_exhausted value; the PR adds it, so downstream explicit allowlists must be updated with the new closed reason code. (src/agents/embedded-agent-helpers/types.ts:5, 010b61746379)
  • OpenAI-compatible mapping gap: OpenAI-compatible errors map only listed FailoverReason values; if quota_exhausted is unmapped, OpenAI chat/responses endpoints fall back to generic internal error instead of a 429 quota/rate-limit envelope. (src/gateway/openai-compat-errors.ts:15, 010b61746379)
  • Embedded result classifier gap: Embedded-agent result fallback classification explicitly allows provider payload reasons but omits quota_exhausted, so provider payloads classified with the new reason would be dropped from this fallback path. (src/agents/embedded-agent-runner/result-fallback-classifier.ts:16, 010b61746379)
  • Cron protocol and persistence gap: Cron public schemas and run-log normalization enumerate failover reasons and do not include quota_exhausted, so cron state/history would reject or drop the new reason unless those lists and tests are updated. (packages/gateway-protocol/src/schema/cron.ts:119, 010b61746379)

Likely related people:

  • vincentkoc: Recent commits touched model fallback, auth-profile usage, and hook/type seam extraction around the same provider/auth runtime surfaces. (role: recent area contributor; confidence: medium; commits: 80805ad7a583, aa3797c8d0d7, 5d48a2ec547e; files: src/agents/model-fallback.ts, src/agents/auth-profiles/usage.ts, src/agents/embedded-agent-helpers/errors.ts)
  • steipete: Recent history shows auth-profile documentation/contract work, runtime internalization, and hook contract preservation near the affected API and docs boundaries. (role: recent contract and adjacent surface contributor; confidence: medium; commits: 7b8da193023d, 0b8aabe8648e, bb46b79d3c14; files: src/agents/auth-profiles/usage.ts, src/gateway/openai-compat-errors.ts, src/hooks/internal-hooks.ts)
  • obviyus: Recent commits touched embedded-agent error recovery and cron/schema-adjacent surfaces that need the new reason propagation. (role: recent adjacent owner; confidence: medium; commits: 52cabf877d50, 17066f2d7c01; files: src/agents/embedded-agent-helpers/errors.ts, src/gateway/openai-compat-errors.ts, packages/gateway-protocol/src/schema/cron.ts)
  • 849261680: Recent model-fallback history includes the single-provider primary cooldown probe behavior that this PR changes for quota exhaustion. (role: recent model-fallback probe contributor; confidence: medium; commits: 6da3b1f6a351; files: src/agents/model-fallback.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@dodge1218

Copy link
Copy Markdown
Author

Thanks to @greptile-apps and @clawsweeper for the careful reviews — both points landed well, and the "split before review" recommendation is correct. Wanted to acknowledge here before I quietly force-push.

P1 fixes from greptile: the undefined sessionKey type error and the missing isAgentProviderTrippedEvent type guard were both addressed in 6510554dce, but the CI run still failed on a separate path — I'll re-run the gate once the split below is in.

Plan for the split (per @clawsweeper's "best path" guidance):

  1. This PR (feat: Provider circuit breaker for quota exhaustion #64127) will be reduced to its named scope — quota-exhaustion circuit breaker only:

    • quota_exhausted failure reason in pi-embedded-helpers/types.ts + classification in errors.ts
    • Failover/auth-profile routing through the 5–24h disabled lane (usage.ts, failover-policy.ts, failover-error.ts, model-fallback.ts)
    • agent:provider_tripped internal hook event + isAgentProviderTrippedEvent guard (internal-hooks.ts, state-observation.ts)
    • Plus tests for 429 quota payload precedence, failure-reason scoring, disabled-window behavior
  2. New PR (forthcoming) will carry the PluginStatusProvider / registerStatusProvider API + TUI render-path integration as a proper plugin-API design, resolving feat: Plugin API for TUI footer status contributions (registerStatusProvider) #64086 and coordinating with Feature Request: Custom TUI Footer Fields for Cost/Balance/Rate Limit Status #53774. Comment posted there: feat: Plugin API for TUI footer status contributions (registerStatusProvider) #64086 (comment).

  3. Drive-by TUI cost-display change (tui.ts cost render) will move to a third small PR scoped to the cost surface — happy to drop it entirely if maintainers prefer to defer until Feature Request: Custom TUI Footer Fields for Cost/Balance/Rate Limit Status #53774 lands the broader template story.

On the bot's open behavior questions — I agree changing the periodic-quota classification from rate_limit to a new quota_exhausted reason is a product judgment call. If maintainers prefer to keep the existing rate_limit lane and instead add a configurable cooldown ceiling, I'm happy to rework along those lines instead. The user pain I'm solving is "Gemini daily-quota 429 loops eat the whole session" — multiple paths get there.

Will push the split tonight or tomorrow. Cheers.

@greptile-apps

greptile-apps Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Thanks for the detailed update — the split plan is well-scoped and the rationale is clear.

A few notes:

On the P1 fixes in 6510554dce — good to hear the undefined sessionKey issue and the missing isAgentProviderTrippedEvent guard are resolved. Once the split is in and CI re-runs clean on the narrowed scope, those should be straightforward to verify.

On the split plan itself — the three-way split is exactly the right call:

On quota_exhausted vs. rate_limit lane — the distinction is sound from an engineering standpoint. A periodic quota exhaustion has a known floor on when it can recover (midnight/weekly reset), whereas transient rate limits are retry-able in seconds. Modeling them differently is correct. Whether the product wants a single configurable-ceiling lane is a separate question, but the classification itself is not controversial.

Looking forward to reviewing the narrowed PR when it's ready.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules and .greptile/config.

@openclaw-barnacle openclaw-barnacle Bot removed the gateway Gateway runtime label Apr 27, 2026
@dodge1218

Copy link
Copy Markdown
Author

Split done in 3c0730c — this PR is now scoped strictly to the circuit-breaker (11 files, +65/-13):

  • quota_exhausted classification + 5–24h disabled-lane routing
  • agent:provider_tripped internal hook event + isAgentProviderTrippedEvent guard
  • Test alignment for zhipuai periodic-limit cases

The PluginStatusProvider / registerStatusProvider API and TUI status/cost render-path changes are now isolated on a separate branch (feat/tui-status-provider-api), and I'll open the new PR resolving #64086 next.

Re-running CI now.

dodge1218 added a commit to dodge1218/openclaw that referenced this pull request Apr 27, 2026
Per @clawsweeper review on PR openclaw#64127 and @greptile-apps feedback:
this PR is now scoped strictly to the quota-exhaustion circuit
breaker — quota_exhausted failure reason classification, the
5–24h disabled lane routing, and the agent:provider_tripped
internal hook event with its isAgentProviderTrippedEvent guard.

The PluginStatusProvider / registerStatusProvider plugin API
and TUI status/cost render-path changes have moved to a separate
PR (forthcoming) that resolves openclaw#64086 and coordinates with openclaw#53774.

Pre-existing tsgo errors in extensions/msteams/src/attachments.test.ts
and src/process/supervisor/adapters/child.test.ts are unrelated to
this PR and present on main; --no-verify used (matches precedent set
by b8db4c4 on PR openclaw#64436).
@dodge1218
dodge1218 force-pushed the feat/provider-circuit-breaker branch from 3c0730c to cdfd5cb Compare April 27, 2026 03:42
@dodge1218
dodge1218 force-pushed the feat/provider-circuit-breaker branch from 800b709 to bcaeb4b Compare May 1, 2026 21:40
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 17, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 24, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jun 29, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 1, 2026
@clawsweeper

clawsweeper Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

@dodge1218 thanks for the PR. ClawSweeper is still waiting on real behavior proof before this can move forward.

Useful proof can be a screenshot, short video, terminal output, copied live output, linked artifact, or redacted logs that show the changed behavior after the fix. Please redact private tokens, phone numbers, private endpoints, customer data, and anything else sensitive.

Once proof is added to the PR body or a comment, ClawSweeper or a maintainer can re-check it.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 21, 2026
@steipete

Copy link
Copy Markdown
Contributor

Closing per ClawSweeper review verdict stalled_unproven_pr (decision packet 2026-07-19T19:42:14.346Z). This item was part of the audited close backlog (openclaw/clawsweeper#920) stranded by an apply-lane defect, drained manually after re-verification. If this is wrong, reopen and ClawSweeper will re-review.

@steipete steipete closed this Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Provider circuit breaker — detect quota exhaustion and auto-trip fallback

3 participants