openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(channels): surface structured rate-limit metadata on chat_error (#2606)

Open CodeGhost21 opened this issue 6 months ago • 1 comments

Summary

  • Promote rate-limit error metadata from message-text-only to typed wire fields on chat_error so the frontend can render a real countdown, retry button, and provider/source label without regexing the message.
  • Add five additive optional fields to WebChannelEvent: error_source, error_retryable, error_retry_after_ms, error_provider, error_fallback_available. Older FE clients that read only message / error_type keep working unchanged (skip_serializing_if = "Option::is_none").
  • Distinguishes upstream provider 429s from OpenHuman's per-hour SecurityPolicy cap, agent-loop iteration cap, OpenHuman billing exhaustion, transport failures, and config errors.
  • Detects non-retryable business 429s (plan does not include model, insufficient balance, Z.AI codes 1311/1113) so the FE can hide the retry button and route the user to billing/settings.
  • Surfaces fallback_available: false once reliable.rs::format_failure_aggregate has exhausted the model_fallbacks chain so the FE doesn't promise a fallback that doesn't exist.

Problem

Issue #2606 follows up on PR #2371. That PR landed retry-after wording inside the user-facing message text — but the structured data was thrown away at the channel-classifier boundary. WebChannelEvent still only carried message: String and error_type: String, so the frontend could not:

  • show a precise countdown (the seconds existed only as a substring like "Try again in 30 seconds")
  • decide whether to render a Retry button (no way to distinguish transient 429 from non-retryable business 429)
  • name the actual provider that throttled
  • distinguish OpenHuman's own cap from upstream provider throttling
  • decide whether to offer a fallback CTA

Users are still reporting confusing rate-limit copy because of this gap (see issue #2606's acceptance criteria).

Solution

New ClassifiedError struct returned from classify_inference_error carries the typed metadata, and the chat-error publish path populates the new WebChannelEvent fields from it.

Source error_source error_retryable Notes
Upstream provider 429 provider true retry_after_ms parsed from body Retry-After: / retry_after:
Non-retryable business 429 provider false matches plan/balance/Z.AI 1311/1113 markers
SecurityPolicy hourly cap openhuman_budget true decays gradually; no provider name implicated
Agent max-iterations agent_loop true same-thread retry once underlying cap clears
402 / insufficient credits openhuman_billing false distinguished from 429 per #2606 AC
Transport timeout transport true
401 / model unavail / context overflow config false

Provider name extracted best-effort from the \"<provider> API error (...)\" prefix that inference::provider::ops::api_error formats. Fallback-exhausted signal extracted from the "All providers/models failed" aggregate that reliable.rs::format_failure_aggregate emits.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) — 13 new tests (11 classifier unit, 2 wire-shape).
  • [x] Diff coverage ≥ 80% — every new branch has dedicated assertions; the structured fields are asserted both at the struct level and as serialized JSON keys, plus a None-omit contract test.
  • [x] Coverage matrix updated — N/A: behaviour-only change to existing classifier output and event payload; no feature row added/removed/renamed.
  • [x] All affected feature IDs from the matrix listed in ## Related — N/A: no matrix row touched.
  • [x] No new external network dependencies introduced — pure string classification + struct expansion; no IO.
  • [x] Manual smoke checklist updated if this touches release-cut surfaces — N/A: additive backend wire fields; happy-path chat behaviour unchanged.
  • [x] Linked issue closed via Closes #NNN — see ## Related.

Impact

  • Runtime/platform: backend chat error path (channels::providers::web::classify_inference_error and the chat_error publish in start_chat) plus the WebChannelEvent wire struct.
  • User-visible: no immediate UI change (FE consumer is a follow-up). The structured fields appear on every chat_error SSE/Socket.IO frame and can be picked up by the FE in a subsequent PR to render a real countdown/retry/fallback UI.
  • Performance: zero — pure string classification, no new IO.
  • Security: no new error data exposed beyond what message already carries. Provider name extraction is allow-listed to ASCII alphanumeric/_/-.
  • Migration / compatibility: error_type tokens are unchanged for existing consumers. New fields are all Option<…> with skip_serializing_if = \"Option::is_none\", so older FE clients see exactly the same JSON shape they do today.

Live verification

Beyond the unit + wire-shape tests, ran a full end-to-end live test:

  1. Node HTTP server that returns HTTP/1.1 429 Too Many Requests, Retry-After: 30, body {\"error\":{\"message\":\"...\",\"code\":\"rate_limit_exceeded\"},\"retry_after\":30} on /v1/chat/completions.
  2. openhuman-core run --port 7892 against an isolated workspace with that endpoint configured as a custom_openai provider.
  3. POST openhuman.channel_web_chat, listen to /events via curl -N.

The chat_error SSE frame received:

event: chat_error
data: {
  \"event\":\"chat_error\",
  \"message\":\"Your AI provider is rate-limiting requests. ... Try again in 30 seconds.
              > rate limited (synthetic 429 for openhuman issue #2606 test)\",
  \"error_type\":             \"rate_limited\",
  \"error_source\":           \"provider\",
  \"error_retryable\":        true,
  \"error_retry_after_ms\":   30000,
  \"error_provider\":         \"fake429\"
}

This exercises the full real path: reliable.rs::is_rate_limited → ops::api_error formatting → classify_inference_error → WebChannelEvent serialization → SSE.

Known follow-ups (out of scope)

  • inference::provider::ops::api_error currently preserves only the response BODY, not the Retry-After HTTP header. When the upstream sends only the header (no body retry_after), retry_after_ms will be None. Follow-up should thread the header into the error chain.
  • Frontend consumer for the new fields (countdown, retry button, fallback CTA) is a separate PR — this PR is backend-only per the scope discussion on #2606.

Related

  • Closes #2606
  • Follow-up to PR #2371 (which closed #2364 with message-only enrichment)
  • Follow-up PR(s)/TODOs: surface Retry-After header from ops::api_error; FE consumer for the new structured fields.

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

Linear Issue

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

Commit & Branch

  • Branch: fix/2606-structured-rate-limit-metadata (branched from origin/main after fresh fetch)
  • Commit SHA: 187dc6352158edacb7d2951df3e538124bc7fbd1

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: no frontend changes.
  • [x] pnpm typecheck — fails on 4 pre-existing errors in app/src/components/settings/panels/devices/PairPhoneModal.tsx, app/src/lib/tunnel/crypto.ts, app/src/pages/ios/PairScreen.tsx (missing iOS-only deps qrcode.react, @noble/ciphers, @tauri-apps/plugin-barcode-scanner). These exist on origin/main and are unrelated to this PR's Rust-only changes. Pushed with --no-verify per CLAUDE.md guidance.
  • [x] Focused tests: cargo test --lib openhuman::channels::providers::web::tests → 52 passed, 0 failed (39 pre-existing + 13 new).
  • [x] Full module tests: cargo test --lib openhuman::channels::providers → 834 passed, 0 failed under default parallelism (added a serial test lock for the three tests sharing TEST_FORCED_RUN_CHAT_TASK_ERROR).
  • [x] Rust fmt/check: cargo fmt --manifest-path Cargo.toml applied; cargo check --lib --bin openhuman-core clean.
  • [x] Tauri fmt/check: cargo check --manifest-path app/src-tauri/Cargo.toml clean.

Validation Blocked

  • command: N/A — full cargo test --lib had 42 pre-existing failures in openhuman::memory::tree_global::* and openhuman::memory_tree::* modules, confirmed reproducible on origin/main with this branch stashed.
  • error: pre-existing memory_tree test failures unrelated to channels work.
  • impact: none on this PR — those modules are not touched.

Behavior Changes

  • Intended behavior change: chat_error WebChannelEvent now carries structured error_source, error_retryable, error_retry_after_ms, error_provider, error_fallback_available fields.
  • User-visible effect: none until the FE consumer ships. Older FE clients see the same JSON they always did.

Parity Contract

  • Legacy behavior preserved: error_type tokens and message text are unchanged for every existing branch. New fields are additive Option<…> with skip_serializing_if. Three existing classifier tests still pass unchanged (only the destructuring shape was migrated from tuple to struct).
  • Guard/fallback/dispatch parity checks: classifier branch ORDER is unchanged (SecurityPolicy budget and max-iterations checks still precede the generic 429 branch — 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

  • New Features

    • Error responses now include structured metadata: source, retryable flag, retry-after timing, provider info, and fallback-available status; web and proactive events populate these (omitted when not applicable).
  • Bug Fixes

    • Improved inference error classification and retry guidance, with clearer handling of rate limits (distinguishing business vs provider 429s).
  • Tests

    • Expanded tests validating error classification, rate-limit metadata, and JSON/SSE wire compatibility.

Review Change Stack

CodeGhost21 avatar May 25 '26 22:05 CodeGhost21

📝 Walkthrough

Walkthrough

Adds five optional error metadata fields to WebChannelEvent, introduces a typed ClassifiedError, refactors classify_inference_error to return it (including provider, retryability, retry-after, fallback info), and updates event emissions and tests to populate or initialize the new fields.

Changes

Structured Error Metadata for Rate Limits

Layer / File(s) Summary
Wire contract: WebChannelEvent error fields
src/core/socketio.rs
WebChannelEvent struct gains five optional error metadata fields (error_source, error_retryable, error_retry_after_ms, error_provider, error_fallback_available) omitted from JSON when None.
Error classification model and helpers
src/openhuman/channels/providers/web.rs
Adds ClassifiedError and helper functions to normalize provider names and detect fallback-chain exhaustion.
Inference error classification logic
src/openhuman/channels/providers/web.rs
Refactors classify_inference_error to return ClassifiedError, implementing branches for budget, max-iterations, provider rate-limits (with Retry-After parsing and retryability detection), timeouts, auth/billing, model-unavailable, and generic inference fallback; populates provider and fallback indicators.
Chat error handling and WebChannelEvent population
src/openhuman/channels/providers/web.rs
Chat error paths bind the ClassifiedError result and populate WebChannelEvent::chat_error with message, error_type, and the new metadata fields; cancellation/error paths updated accordingly.
Progress / lifecycle event emissions
src/openhuman/channels/providers/web.rs
inference_start and iteration_start bridge events initialize new error metadata fields to None to keep wire shape consistent.
Proactive and presentation channel events
src/openhuman/channels/proactive.rs, src/openhuman/channels/providers/presentation.rs
ProactiveMessageSubscriber and presentation-layer response emissions include the new error fields, set to None for non-error messages.
Test infrastructure and structured metadata validation
src/openhuman/channels/providers/web_tests.rs
Adds a process-global async mutex to serialize forced-error tests, updates tests to destructure ClassifiedError, and adds extensive tests verifying retry_after_ms, source, provider, retryable, fallback_available, and SSE/JSON wire serialization of the new chat_error fields and classification behaviors.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • graycyrus
  • senamakel
  • fzamel3333-ai

Poem

🐰 I hopped through logs and parsed the fray,
Picking out providers that led us astray.
Retry times counted, fallbacks gently noted,
Now chat knows who paused and whether it's floated.
A rabbit's small badge: metadata, neatly coded.

🚥 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 'fix(channels): surface structured rate-limit metadata on chat_error (#2606)' clearly summarizes the main change—adding structured error metadata fields to WebChannelEvent for rate-limit handling.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from #2606 and #2364: structured rate-limit metadata fields (error_source, error_retryable, error_retry_after_ms, error_provider, error_fallback_available) are added and populated throughout the codebase, ClassifiedError distinguishes limit sources and retryability, Retry-After parsing is implemented, provider extraction is included, and comprehensive test coverage is provided.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing structured rate-limit metadata: core type definitions in socketio.rs, integrations in channels/providers (web.rs, presentation.rs, proactive.rs), and comprehensive test additions in web_tests.rs covering classification and wire-shape validation.
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 25 '26 22:05 coderabbitai[bot]