openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(inference): cap extraction max_tokens + classify provider 402 to stop the retry/Sentry storm (#3616)

Open oxoxDev opened this issue 5 months ago • 3 comments

Summary

  • Memory extraction sent chat completions with no max_tokens, so OpenRouter's credit pre-flight reserved the model's full output window (65536 for anthropic/claude-fable-5) and returned 402 Payment Required to any BYO user whose balance couldn't cover it — on every extraction call.
  • The extraction retry loop treated the permanent 402 as a transient transport failure and retried it 3×, and each failure was reported to Sentry — 12k events from a single user (TAURI-RUST-C62).
  • Fix caps extraction output at source (prevention), stops retrying permanent provider errors (de-amplification), and demotes only the residual genuinely-out-of-credits 402 (defense-in-depth).

Problem

memory_tree::extract::llm builds a ChatPrompt and routes it through the inference provider stack. The outbound NativeChatRequest had no max_tokens field, so OpenRouter priced the request against the model's entire output window during its balance check:

myopenrouter API error (402 Payment Required): This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 49732.

An extraction response is one small structured-JSON object (entities + an importance float). The 64k reservation is pure headroom the user never uses, yet it blocks every extraction for a low-balance account. Two amplifiers turned a benign user-state into a 12k-event storm:

  1. Retry of a permanent error — try_extract returned "retry" for any provider Err, so the 402 was retried 3× per call.
  2. Suppression gap — the existing insufficient-credits Sentry demotion only matches OpenHuman managed-backend bodies (errorCode: USER_INSUFFICIENT_CREDITS). A direct BYO-provider 402 has no errorCode, so it fell through every guard to error-level reporting.

Solution

  • Cap at source (prevention). Thread an optional max_tokens through ChatRequest → NativeChatRequest → the OpenAI-compatible wire. Memory extraction sets EXTRACTION_MAX_OUTPUT_TOKENS = 8192, so the provider's pre-flight is priced realistically and clears for a low-balance account. Every other call site passes None (unchanged, open-ended generation).
  • Stop retrying permanent failures (de-amplification). try_extract now returns AttemptOutcome::{Done, Retryable, Permanent}, classifying the error against the provider stack's single source of truth (reliable::is_non_retryable). A permanent 4xx (402 / rejected key / model gone) skips the backoff loop and degrades immediately with a typed cause — a 402 maps to FailureCode::BudgetExhausted, so doctor/status steers the user to top up instead of reporting "extraction is timing out". Transient failures still exhaust the retry budget.
  • Demote the residual 402 (defense-in-depth). is_provider_insufficient_credits_402 recognises the direct-provider out-of-credits shape and demotes it from Sentry error to an info log. This is the residual case once max_tokens is capped: the user's own third-party account is genuinely out of balance — a billing state with no local lever. The matcher is coupled to a verbatim-body test so a provider wording drift fails CI rather than silently leaking events. Honest degradation is preserved — the structure-degraded signal still surfaces to doctor/status; only the Sentry alarm is demoted.

RCA-vs-suppress gate: Bucket = mixed — preventable (the max_tokens cap) + real-defect (the retry of a permanent error); the residual unpreventable out-of-credits tail is the only part suppressed, and only as defense-in-depth behind the two real fixes.

Submission Checklist

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

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] Diff coverage ≥ 80% — changed lines (Vitest + cargo-llvm-cov merged via diff-cover) meet the gate enforced by .github/workflows/pr-ci.yml. Run pnpm test:coverage and pnpm test:rust locally; PRs below 80% on changed lines will not merge.
  • [x] N/A: behaviour-only change — no coverage-matrix feature rows added/removed/renamed in docs/TEST-COVERAGE-MATRIX.md.
  • [x] N/A: no feature IDs to list — behaviour-only change touches no matrix rows.
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy)
  • [x] N/A: does not touch release-cut surfaces — Manual smoke checklist unchanged.
  • [x] Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Runtime: desktop (Rust core). No frontend, mobile, or CLI surface change.
  • Behavior: memory extraction now requests at most 8192 output tokens (ample for the structured-JSON response) and no longer retries a permanent provider error or floods Sentry with BYO out-of-credits 402s. Open-ended generations (orchestrator, agent turns) are unchanged — they pass max_tokens: None.
  • Security/compat: none. The new struct field is additive and serialised only when set.

Related

  • Closes: #3616
  • Sentry-Issue: TAURI-RUST-C62
  • Closes: TAURI-RUST-4QF (same shape on deepseek native_chat — 402 Payment Required: Insufficient Balance; caught by the same is_provider_insufficient_credits_402 arm)
  • Follow-up PR(s)/TODOs: the summariser path (memory_tree::summarise) shares the same provider and could exhibit the same 402 if a low-balance user has a large per-level budget; left max_tokens: None for now (its output budget is enforced prompt-side and a hard cap risks truncating a valid large summary). Revisit if it surfaces.

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

Keep this section for AI-authored PRs. For human-only PRs, mark each field N/A.

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/3616-memory-extract-maxtokens-402
  • Commit SHA: 9f7738fcb

Validation Run

  • [x] pnpm --filter openhuman-app format:check
  • [x] pnpm typecheck
  • [x] Focused tests: cargo test --lib openhuman::memory_tree::score::extract::llm (31 pass), …::inference::provider::ops::http_error (4 pass), …::inference::provider::compatible (178 pass)
  • [x] Rust fmt/check (if changed): cargo fmt --check clean; cargo check --all-targets clean
  • [x] Tauri fmt/check (if changed): pnpm rust:check (pre-push)

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: Live BYO-low-balance 402 repro is not reproducible locally (needs a credit-limited OpenRouter key); all three facets are covered deterministically by unit tests.

Behavior Changes

  • Intended behavior change: memory extraction caps output tokens; permanent provider errors are not retried; BYO out-of-credits 402 is demoted from Sentry.
  • User-visible effect: low-balance BYO users can run memory extraction again; doctor/status reports "out of credits" instead of "timing out"; no behaviour change for users with sufficient balance.

Parity Contract

  • Legacy behavior preserved: all non-extraction call sites pass max_tokens: None (identical wire output); transient failures still retry 3×; truncated-JSON still retries; wrong-shape JSON still returns empty without retry.
  • Guard/fallback/dispatch parity checks: the 402 demotion sits before the catch-all should_report_provider_http_failure, mirroring the existing is_provider_access_policy_denied_http_403 guard shape.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none (dedupe ran — open + 30d-merged; the merged "402" PRs are the x402 crypto-payment protocol, unrelated)
  • Canonical PR: this
  • Resolution (closed/superseded/updated): N/A

Summary by CodeRabbit

  • New Features

    • Optional output-token cap for chat requests (max tokens / max output tokens), propagated across provider paths and fallbacks
    • Suppress "insufficient credits" (402) provider events from error reporting
  • Improvements

    • More robust extraction: explicit retry/outcome handling and clearer permanent vs transient failure classification
    • Summariser and memory flows now handle output budgets without truncating valid large summaries
  • Tests

    • Expanded unit and integration tests for token-cap serialization, retry behavior, and 402 handling

oxoxDev avatar Jun 12 '26 08:06 oxoxDev

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e35e7984-c326-437b-9305-a65ff3781a47

📥 Commits

Reviewing files that changed from the base of the PR and between 712df5cec612e83abfc56ff46f403dedb6d70642 and 3814d01a848641827f25a0096588b961c566b9f6.

⛔ Files ignored due to path filters (1)
  • app/src-tauri/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • src/core/observability.rs
💤 Files with no reviewable changes (1)
  • src/core/observability.rs

📝 Walkthrough

Walkthrough

This PR threads an optional max_tokens output-token cap through chat request contracts, provider implementations, and memory paths to prevent insufficient-credits 402 errors. It adds HTTP 402 detection, logs it at info level, and suppresses it from Sentry. Memory extraction is refactored to classify permanent provider errors (401/403/402) as non-retryable and treat truncated JSON as retryable, using a new AttemptOutcome enum. Callsites and tests are updated to include the new field throughout.

Changes

Max-tokens output cap and 402 insufficient-credits handling

Layer / File(s) Summary
Chat request contract and wire types
src/openhuman/inference/provider/traits.rs, src/openhuman/inference/provider/compatible_types.rs
Adds ChatRequest.max_tokens: Option<u32> with documentation, NativeChatRequest.max_tokens: Option<u32>, and ResponsesRequest.max_output_tokens: Option<u32>, all serialized only when Some(...).
Provider forwarding and fallback paths
src/openhuman/inference/provider/compatible_provider_impl.rs, src/openhuman/inference/provider/compatible_helpers.rs
Forwards request.max_tokens into native NativeChatRequest and chat_via_responses(); updates all fallback callsites (transport error, 404 responses) to pass max_tokens; adds 402 insufficient-credits detection branch in native error handling.
Reliable provider and retry classification
src/openhuman/inference/provider/reliable.rs
Preserves max_tokens field across per-attempt ChatRequest construction in retry loops; exposes is_non_retryable() as pub(crate) for shared error classification across layers.
HTTP 402 detection and logging
src/openhuman/inference/provider/ops/http_error.rs, src/openhuman/inference/provider/ops/mod.rs
Adds is_provider_insufficient_credits_402() and body_indicates_insufficient_credits() predicates matching PAYMENT_REQUIRED with credit-phrase bodies; adds log_provider_insufficient_credits_402() info logger; includes unit tests for verbatim/variant phrase matching and negative cases; rewraps ops re-exports formatting.
Sentry event suppression
src/core/observability.rs, src/main.rs
Adds is_insufficient_credits_event() filter matching 402 + insufficient-credits predicates in event.message or exception values; integrates into Sentry before_send to drop events before reporting; includes tests for message/exception paths and combined predicate validation.
Memory extraction retry and budget cap
src/openhuman/memory_tree/score/extract/llm.rs, src/openhuman/memory_tree/score/extract/llm_tests.rs
Introduces EXTRACTION_MAX_OUTPUT_TOKENS (8192) constant; refactors extract/try_extract from Option-based logic to AttemptOutcome enum (Done/Retryable/Permanent); classifies permanent client errors (401/403/402) and non-JSON responses as Permanent; treats EOF/truncated mid-JSON as Retryable; adds permanent_failure_code() mapper for error-message patterns; includes tests for cap enforcement, permanent 402 behavior, and retry exhaustion.
Chat prompt integration
src/openhuman/memory/chat.rs, src/openhuman/memory/query/walk.rs, src/openhuman/memory/query/smart_walk/tool.rs, src/openhuman/memory/schema/handlers.rs, src/openhuman/memory_tree/summarise.rs
Adds ChatPrompt.max_tokens: Option<u32> field; wires prompt.max_tokens into ChatRequest in InferenceChatProvider; updates memory adapters/handlers to set or leave max_tokens unset; summariser sets None with in-code rationale for prompt-side enforcement; updates test prompts.
Agent, harness, and provider callsites
src/bin/inference_probe.rs, src/openhuman/agent/harness/..., src/openhuman/inference/provider/claude_code/mod.rs, src/openhuman/routing/provider_tests.rs
Updates ~15 ChatRequest literals across agent loop, harness engine, checkpoint handlers, and routing tests to set max_tokens: None; updates LM Studio and Ollama factory tests.
Request serialization and type tests
src/openhuman/inference/provider/compatible_tests.rs, src/openhuman/inference/provider/traits_tests.rs
Adds unit tests asserting max_tokens/max_output_tokens serialize only when Some(...); updates serialization, frequency_penalty, include_usage, and provider-trait tests to set max_tokens: None for stable JSON assertions; updates provider-config rejection tests.
End-to-end test updates
tests/inference_agent_raw_coverage_e2e.rs, tests/inference_compatible_*.rs, tests/inference_provider_*.rs, tests/inference_round26_raw_coverage_e2e.rs, tests/owned_domain_raw_coverage_e2e.rs
Updates ~25 ChatRequest literals across provider trait tests, OpenAI-compatible streaming/content, router fallback, reliable provider exhaustion, compatible matrix tests, and owned domain tests to set max_tokens: None for consistent request shapes.

Sequence Diagram

sequenceDiagram
  participant Extractor
  participant ChatProvider
  participant NativeAPI
  participant Observability
  Extractor->>ChatProvider: ChatRequest(max_tokens=8192)
  ChatProvider->>NativeAPI: NativeChatRequest(max_tokens=8192)
  NativeAPI-->>ChatProvider: 200 OK or HTTP error
  alt 402 Insufficient Credits
    ChatProvider->>Observability: log_provider_insufficient_credits_402()
    ChatProvider-->>Extractor: AttemptOutcome::Permanent
    Observability->>Observability: is_insufficient_credits_event drop
  else Transient Error
    ChatProvider-->>Extractor: AttemptOutcome::Retryable
    Extractor->>Extractor: retry with backoff
  else Success
    ChatProvider-->>Extractor: AttemptOutcome::Done
  end

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

The PR introduces schema changes across multiple layers (request contracts, wire types, prompt structures), refactors core extraction retry semantics with a new enum, threads a new field through provider paths and fallbacks, adds error classification and Sentry filtering logic, and updates 60+ test/callsite literals. The changes are coherent but span diverse files and require understanding the extraction refactor, provider error handling, and Sentry integration context.

Suggested reviewers

  • senamakel
  • graycyrus

Poem

🐰 With bounded tokens, balance preserved,

402s logged—no Sentry swerved.
Extraction now knows: when credits run dry,
it gracefully stops, no retry storm nigh. 🥕✨

🚥 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 PR title accurately describes the main changes: capping extraction max_tokens and classifying provider 402 errors to prevent retry/Sentry storms.
Linked Issues check ✅ Passed All objectives from issue #3616 are met: extraction max_tokens capped at 8192, permanent failures no longer retried, 402 events demoted in Sentry, and unit tests added with >80% coverage.
Out of Scope Changes check ✅ Passed All changes align with issue #3616 objectives. The PR threads max_tokens through ChatRequest infrastructure, classifies extraction errors, adds 402 classification and demotion, and covers edge cases with tests.
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 Jun 12 '26 08:06 coderabbitai[bot]

CI note: the three red checks are pre-existing failures on main, unrelated to this PR

This change is Rust-core only (inference provider + memory extraction). All three failing checks are in code this PR does not touch, and reproduce on a clean checkout of main (dca389712):

  • Rust Core Coverage — openhuman::agent::tests::auto_save_stores_messages_in_memory fails with Expected at least 2 memory entries, got 1. Verified to fail identically on main @ dca389712 with zero changes from this branch (3/3 deterministic). It's an agent auto-save regression, independent of the 402 fix here.
  • Frontend Coverage (Vitest) — src/pages/__tests__/Conversations.render.test.tsx (budget/quota-pill cases). Frontend React; untouched by this diff.
  • E2E (Playwright / web lane 1/4) — connector-gmail-composio.spec.ts. Frontend E2E; untouched by this diff.

This PR's own gates pass: Rust Quality (fmt, clippy), Rust E2E (mock backend), Rust Tauri Coverage, i18n, Frontend Quality, PR Submission Checklist, Coverage Matrix Sync, and Playwright web lanes 2–4. Happy to rebase once main is green.

oxoxDev avatar Jun 12 '26 09:06 oxoxDev

Addressed CodeRabbit's outside-diff finding (Responses API drops max_tokens) in 70080906f — added max_output_tokens to ResponsesRequest and threaded the caller's cap through chat_via_responses, forwarded from all three chat() call sites (the responses_api_primary branch + the transport/404 fallbacks). The chat_with_system/chat_with_history fallbacks have no request budget and pass None. Serialization covered by responses_request_serializes_max_output_tokens_only_when_set.

oxoxDev avatar Jun 12 '26 12:06 oxoxDev