openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(observability): classify OpenHuman/Embedding backend 'Invalid token' 401 as SessionExpired (TAURI-RUST-4P0 + 4K5)

Open CodeGhost21 opened this issue 6 months ago • 1 comments

Summary

Extend is_session_expired_message in src/core/observability.rs to recognise the OpenHuman backend's {"success":false,"error":"Invalid token"} 401 envelope as a session-expired condition (currently only the explicit "Session expired. Please log in again." body is recognised). Two emit-site wrapper shapes both route through the same report_error_or_expected funnel and need to be covered:

Sentry ID Emit-site prefix Wrapped by
TAURI-RUST-4P0 OpenHuman API error (401 …) chat / agent / web-channel run_chat_task
TAURI-RUST-4K5 Embedding API error (401 …) src/openhuman/embeddings/openai.rs:139

Both surface the same upstream cause — backend rejecting the bearer JWT as invalid — typically right after a [scheduler_gate] signed_out false -> true breadcrumb (visible in the 4K5 event payload). UI already drives reauth via the SessionExpired event-domain path; this stops the noise leaking into Sentry as a code bug.

Why two arms, not one

The matcher uses conjunctive anchors per arm — "<emit-site prefix> (401" AND the envelope-shaped "\"error\":\"Invalid token\"". Anchoring on the emit-site prefix is what preserves the existing #2286 BYO-key contract:

  • A third-party "OpenAI API error (401 Unauthorized): invalid_api_key" (user's own OpenAI key revoked) must NOT match — it's actionable misconfiguration.
  • A third-party "Embedding API error (401 Unauthorized): invalid_api_key" (user's own embedding-provider key revoked) must NOT match for the same reason — covered by the new does_not_classify_embedding_byo_key_401_as_session_expired polarity guard.

A single broad "any 401 + invalid token" matcher would silence both — that's why each emit-site wrapper gets its own prefix-gated arm.

Tests added

  • classifies_openhuman_invalid_token_401_as_session_expired — verbatim 4P0 wire shape (wrapped + unwrapped variants).
  • classifies_embedding_api_invalid_token_401_as_session_expired — verbatim 4K5 wire shape (direct + wrapped variants).
  • does_not_classify_embedding_byo_key_401_as_session_expired — polarity guard pinning the BYO-key contract for the embedding path.
  • Existing does_not_classify_byo_key_provider_401_as_session_expired continues to pass — #2286 contract for the chat path preserved.

Test plan

  • [x] cargo test classifies_embedding_api_invalid_token — passes (new)
  • [x] cargo test classifies_openhuman_invalid_token — passes (4P0)
  • [x] cargo test does_not_classify_embedding_byo_key — passes (new polarity guard)
  • [x] cargo test does_not_classify_byo_key_provider — passes (#2286 contract)
  • [x] cargo test core::observability — 91 tests pass, 0 regressions
  • [x] cargo check --bin openhuman-core — passes
  • [x] cargo fmt --check — clean

Related

  • Sentry-Issue: TAURI-RUST-4P0
  • Sentry-Issue: TAURI-RUST-4K5
  • Sentry-Issue: TAURI-RUST-4QP — same root cause as 4K5 (Embedding API 401 "Invalid token" envelope), different Sentry fingerprint; the conjunctive-anchor matcher in this PR demotes both shortIds.

Summary by CodeRabbit

  • Bug Fixes
    • Improved detection and classification of authentication "session expired" errors to recognize additional provider-specific 401 error formats while avoiding false positives for other 401 variants.
    • Expanded tests to cover the newly recognized error formats and to ensure other similar 401 responses remain correctly classified.

Review Change Stack

CodeGhost21 avatar May 27 '26 20:05 CodeGhost21

📝 Walkthrough

Walkthrough

Adds conjunctive matching and docs in is_session_expired_message to classify OpenHuman/Embedding 401 "Invalid token" JSON envelopes as SessionExpired, and adds regression tests covering wrapped/unwrapped and negative BYO-key cases.

Changes

OpenHuman 401 Invalid Token Classification

Layer / File(s) Summary
Session-expired classification for OpenHuman 401 invalid-token
src/core/observability.rs
Doc comment expanded to describe the OpenHuman 401 {"error":"Invalid token"} envelope and the embedding wrapper; is_session_expired_message updated to conjunctively require the "OpenHuman API error (401" or "Embedding API error (401" prefix plus the exact invalid-token envelope before returning ExpectedErrorKind::SessionExpired.
Regression tests for invalid-token classification
src/core/observability.rs
New tests assert both wrapped run_chat_task and unwrapped OpenHuman invalid-token envelopes classify as SessionExpired; verify embedding invalid-token wrapper classifies as SessionExpired; and guard that BYO-key/generic 401 variants do not classify as session-expired.

Sequence Diagram(s)

(omitted — change is a targeted classifier update and tests; no multi-component sequential flow requires visualization)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • senamakel
  • graycyrus
  • M3gA-Mind

Poem

🐰 A token slipped out of date and key,
The 401 whispered, "Invalid token" to me.
I matched prefix and envelope with care,
So sessions expire only when they truly bear.
Hooray — tests hop in, the classifier set free!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title directly summarizes the main change: classifying OpenHuman/Embedding invalid token 401 responses as SessionExpired, which is the primary purpose of the changeset.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 27 '26 20:05 coderabbitai[bot]

@oxoxDev thanks for the thorough review and the approval! Answering your two questions:

Q1 — tier / breadcrumb-leak risk. No divergence: classification routes on the kind, not the message shape. is_session_expired_message → expected_error_kind returns Some(ExpectedErrorKind::SessionExpired), and report_expected_message funnels every SessionExpired through the single match arm at src/core/observability.rs:1064, which deliberately demotes to tracing::info! ("breadcrumb survives for trace correlation but Sentry sees no error event"). All three new arms (4P0/4K5/1EE) inherit that exact treatment — there is no per-shape tier branch, so the new shapes can't drop to a different Breadcrumb/Ignore level than the existing arms. No leak risk introduced beyond the already-accepted SessionExpired behavior.

Q2 — self-hosted Sentry close directives. Added to the PR body under a new ## Related section:

Closes TAURI-RUST-4P0
Closes TAURI-RUST-4K5
Closes TAURI-RUST-1EE

One heads-up for the Phase 7 Step 4.5 sweep: PR #2692's body flagged that the post-merge resolve regex is anchored to OPENHUMAN-(TAURI|REACT|CORE) and may not match the bare TAURI-RUST-* prefix yet. If that widening hasn't landed, these may need a manual flip on merge.

Nits — all noted as follow-ups (not in this PR): the &[(prefix, envelope)] table hoist when a 4th emit-site lands, case-insensitive "invalid token" matching, and the user-paste edge case. Agreed they're worth a follow-up but not blockers here.

CodeGhost21 avatar May 28 '26 19:05 CodeGhost21

Posted #2869 with the root-cause fix: #2830's merge inadvertently reverted #2786's SessionExpired classification back to BackendUserError, so the classifies_embedding_api_invalid_token_401_as_session_expired test added by #2786 has been failing on every PR rebased onto post-#2830 main. One-line classifier fix + reconciled the stale companion test.

sanil-23 avatar May 28 '26 20:05 sanil-23