openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(channels): distinguish rate-limit sources in chat error classifier (#2364)

Open CodeGhost21 opened this issue 6 months ago • 1 comments

Summary

  • classify_inference_error in web.rs used to tag any error string containing "rate limit" as rate_limited, including the SecurityPolicy hourly-cap strings emitted by built-in tools — so users saw "Your AI provider is rate-limiting you" copy for an OpenHuman-local safety cap.
  • Split the catch-all branch into three sources (action_budget_exceeded, max_iterations, rate_limited) and surface Retry-After seconds in the user-facing message when the upstream supplies them.
  • No frontend change needed — the new copy flows through the existing chat_error.message forwarder in ChatRuntimeProvider.

Problem

Issue #2364 reports that one chat thread shows "You're being rate-limited" while a fresh thread works. Tracing the frontend (ChatRuntimeProvider.onError) showed no per-thread sticky state — inferenceStatus, inferenceTurnLifecycle, and activeThreadId all clear on chat_error. The stickiness is perceived, driven by:

  1. Generic copy that doesn't say "you can retry in this thread".
  2. No retry-after window so the user has no idea when to try again.
  3. The same generic copy used regardless of whether the limit came from the upstream LLM provider, the SecurityPolicy budget on tool calls, or the agent-loop max-iterations cap.

Solution

Three new / reshaped branches in classify_inference_error:

Source Classification User-facing copy
SecurityPolicy hourly action budget (web_fetch / curl / http_request / etc.) action_budget_exceeded "You've hit OpenHuman's per-hour action budget — this is a local safety cap, not your AI provider. The window decays gradually; you can keep chatting in this thread …"
Agent-loop max-iterations cap ("Agent exceeded maximum tool iterations") max_iterations "The agent ran the maximum number of tool steps for one turn … You can retry the same question in this thread once the underlying limit clears."
Upstream provider 429 / "rate limit" rate_limited (enriched) "Your AI provider is rate-limiting requests. This is a transient upstream limit, not a thread-level block — you can retry in this thread. Try again in 30 seconds." — retry-after parsed from Retry-After: / retry_after: header bodies, fractional values rounded up.

The SecurityPolicy and max-iterations checks run BEFORE the provider-429 branch so their substring rate limit no longer leaks into the wrong bucket. Existing rate_limited callers (FE handler, tests) continue to receive the same error_type token; only the human-readable message changed.

Submission Checklist

If a section does not apply to this change, mark the item as N/A with a one-line reason.

  • [x] Tests added or updated (happy path + at least one failure / edge case) — 5 new tests + 2 pre-existing classifier tests; cargo test --lib classify_inference_error → 7 passed.
  • [x] Diff coverage ≥ 80% — every new branch and the new retry-after helper has at least one focused test. No untested branches added.
  • [x] Coverage matrix updated — N/A: behaviour-only change to existing classifier output; no new feature row added/removed/renamed.
  • [x] All affected feature IDs from the matrix are listed in ## Related — N/A: no matrix row touched.
  • [x] No new external network dependencies introduced — pure string classification, no IO.
  • [x] Manual smoke checklist updated if this touches release-cut surfaces — N/A: error-message wording only; happy-path chat behaviour is unchanged.
  • [x] Linked issue closed via Closes #NNN in the ## Related section — see below.

Impact

  • Runtime/platform: backend chat error path (channels::providers::web::classify_inference_error).
  • User-visible: when the agent hits a SecurityPolicy budget cap, the chat surface now says "OpenHuman's per-hour action budget" instead of mislabeling the cap as an upstream provider 429. Provider 429s now include a parsed retry-after window when the upstream supplies one.
  • Performance / security: zero runtime cost (string classification only). No new error data is exposed; the retry-after parser only reads what's already in the error body.
  • Migration / compatibility: error_type tokens are unchanged for upstream consumers; only the message body is reworded. FE error forwarder picks up the new copy automatically.

Tests

cargo test --lib classify_inference_error → 7 passed, 0 failed (5 new, 2 pre-existing).

New test Covers
classify_inference_error_distinguishes_action_budget_from_provider_429 all three SecurityPolicy strings classify as action_budget_exceeded; copy says "local safety cap" + "can keep chatting in this thread"
classify_inference_error_max_iterations_gets_dedicated_branch flattened web-channel error wrapper resolves to max_iterations with the same-thread recovery hint
classify_inference_error_rate_limited_surfaces_retry_after_seconds 30-second retry-after appears verbatim; thread-recovery hint present
classify_inference_error_rate_limited_no_retry_after_omits_hint 429 without Retry-After does NOT hallucinate a window
classify_inference_error_rate_limited_handles_fractional_and_minute_windows 2.4s rounds to 3s; 180s renders as "about 3 minutes"

Related

  • Closes #2364
  • Follow-up PR(s)/TODOs: a composer-level countdown banner could read the new retry-after copy; out of scope for this PR.

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A (GitHub-only issue #2364)

Commit & Branch

  • Branch: fix/2364-rate-limit-classification (branched from origin/main after fresh fetch)
  • Commit SHA: see PR head

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: no frontend changes.
  • [x] pnpm typecheck — N/A: no TypeScript changes.
  • [x] Focused tests: cargo test --lib classify_inference_error → 7 passed, 0 failed.
  • [x] Rust fmt/check (if changed): cargo fmt --manifest-path Cargo.toml applied; cargo check clean.
  • [x] Tauri fmt/check (if changed): N/A: no Tauri shell changes.

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: error classification distinguishes OpenHuman SecurityPolicy budget caps from upstream provider 429s; retry-after seconds appear in the user-facing message when parseable.
  • User-visible effect: chat error bubbles for rate-limit-style errors now name the actual cause and (where known) a concrete retry window.

Parity Contract

  • Legacy behavior preserved: error_type tokens are unchanged for the existing rate_limited consumers; only message body changed. Generic-inference fallback unchanged. Order of remaining branches (timeout / auth / budget / provider / model_unavailable / config-rejection) is unchanged.
  • Guard/fallback/dispatch parity checks: the new SecurityPolicy / max-iterations branches are ordered BEFORE the generic 429 branch so their substring rate limit no longer leaks into the wrong bucket — locked in by _distinguishes_action_budget_from_provider_429 and _max_iterations_gets_dedicated_branch.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none.
  • Canonical PR: this PR.
  • Resolution: N/A.

Summary by CodeRabbit

  • Bug Fixes

    • Improved error messages when action budget is exhausted, clarifying that the limit is local and the thread remains usable
    • Enhanced rate-limiting responses with parsed Retry-After timing information to provide clearer retry guidance
    • Better error handling and messaging for agent tool iteration limit exceeded scenarios
  • Tests

    • Added comprehensive tests verifying correct error classification and user messaging across multiple failure scenarios

Review Change Stack

CodeGhost21 avatar May 20 '26 20:05 CodeGhost21

📝 Walkthrough

Walkthrough

The web channel error classifier now detects OpenHuman action-budget exhaustion, agent max-iteration tool-step exhaustion, and provider rate limits. It adds helpers to parse/format Retry-After timing, reorders classification priority to surface budgets first, and updates rate-limited messages to include optional retry timing hints.

Changes

Error classification improvements with retry messaging

Layer / File(s) Summary
Rate-limit parsing and message formatting
src/openhuman/channels/providers/web.rs
parse_retry_after_secs_from_str extracts numeric Retry-After values (ceiling seconds) from free-form error strings; retry_after_hint renders Option<u64> into user-facing suffixes (immediate, N seconds, or "about N minutes").
Action-budget detection
src/openhuman/channels/providers/web.rs
is_action_budget_exhausted matches OpenHuman-local action-budget phrases in lowercased error text to classify local safety budget exhaustion.
Error classification logic and orchestration
src/openhuman/channels/providers/web.rs
classify_inference_error is reordered to check action-budget first, then is_max_iterations_error, then provider rate limit/429; the rate_limited branch now uses parsed Retry-After hints and updated transient-provider messaging.
Test suite for error classification paths
src/openhuman/channels/providers/web_tests.rs
Adds tests validating action-budget classification, max-iterations classification, and several rate-limit scenarios (with/without Retry-After, fractional-second rounding-up, minute-threshold formatting, pluralization, and parsing Retry-After inside JSON bodies).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

working

Suggested reviewers

  • graycyrus

Poem

A rabbit hops through logs at night, 🐰
Counting seconds till retry feels right,
Budgets and iterations neatly pried,
Retry-After hints now stand beside—
Chat resumes when timers say "alright."

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: distinguishing rate-limit sources in the chat error classifier, which is the core objective of the PR.
Linked Issues check ✅ Passed The PR directly addresses all key requirements from issue #2364: distinguishes rate-limit sources (provider 429s, action-budget, max-iterations), provides retry-after parsing and recovery guidance, prevents thread-level state stickiness through accurate classification, and adds comprehensive tests covering transient limits and same-thread retry behavior.
Out of Scope Changes check ✅ Passed All changes are scoped to the inference error classifier in src/openhuman/channels/providers/web.rs and its corresponding tests; no unrelated alterations or dependencies outside the stated objectives are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 20 '26 20:05 coderabbitai[bot]