feat(embeddings): auto-fall back managed cloud → local on session-expiry 401 (#3312)
Summary
- When the managed cloud (Voyage-backed) backend session JWT expires mid-run, every embedding call returns
401 Invalid tokenand indexing fails hard until a manual provider switch. This adds an automatic, signature-safe fallback to a preloaded local embedder. - Detection is a process-global auth-failure latch set at the shared
OpenAiEmbedding::embedchokepoint; the memory-queue worker acts on it each tick. - The switch is persisted via
update_settings, moving the active embedding signature atomically with the provider, then adopted by the worker in-place — so it takes effect with no process restart. - Addresses 1 of the 4 robustness gaps in #3312 (the "embedding fallback on 401" item). Does not close the issue.
Problem
- On a long-running headless/Docker deployment the backend session expires after a few hours. From then on every managed-cloud embed returns 401 (every ~2 min), hard-failing indexing, with no automatic fallback even when a local embedder is preloaded. The original deployment needed a manual restart to recover.
- The constraint that makes this non-trivial: cloud (Voyage) and local (
bge-m3) are different embedding spaces, and the vector store tags every vector by a config-derived signature (#1574). Naively returning local vectors on a 401 would write them under the cloud signature and silently corrupt semantic search.
Solution
- Detect at
OpenAiEmbedding::embed— the shared chokepoint both the embeddings RPC path and the memory-tree write path bottom out in. A confirmed 401/403 latches a process-global flag; any successful embed clears it (a transient blip can't trigger a switch). - Switch in the memory-queue worker tick, only when all guards hold: configured provider is managed cloud (
cloud/managed); a local embedder is reachable (probe_ollama_reachable); and local dimensionality equals the current one (bge-m31024 == cloud 1024) so no destructive memory wipe is required. - Persisting the switch via the existing
update_settingsmoves the active embedding signature atomically with the provider and schedules the existing re-embed backfill — vectors stay correctly labelled and the corpus re-indexes under the local signature. Local vectors are never written under the cloud signature. - The worker adopts the reloaded config in-place, so the switch applies with no restart. If no local embedder is available, the latch is a no-op: the cloud failure stays surfaced (graceful degradation) rather than switching into a dead provider or auto-wiping memory.
- Design decision: settings-level switch + signature move, chosen over a per-call vector swap (would corrupt the established cloud corpus) and over a mere graceful-skip (wouldn't restore embeddings).
Submission Checklist
If a section does not apply to this change, mark the item as
N/Awith a one-line reason. Do not delete items.
- [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy —
should_switchtruth table incl. the dimension-mismatch never-auto-wipes case; gate set/clear/idempotency; no-I/O early-return branches (gate-clear, non-cloud provider). Serialized via a test lock to stay race-free. - [x] Diff coverage ≥ 80% — changed lines (Vitest + cargo-llvm-cov merged via
diff-cover) meet the gate enforced by.github/workflows/pr-ci.yml. Runpnpm test:coverageandpnpm test:rustlocally; PRs below 80% on changed lines will not merge. — Pure decision core + all early-return branches are unit-covered; the deep switch path (probe_ollama_reachable+update_settings+ config reload) is genuine I/O integration and not unit-covered. Will confirmdiff-coverin CI. - [x] Coverage matrix updated — added/removed/renamed feature rows in
docs/TEST-COVERAGE-MATRIX.mdreflect this change (orN/A: behaviour-only change) —N/A: behaviour-only robustness change. - [x] All affected feature IDs from the matrix are listed in the PR description under
## Related— N/A (no matrix rows touched). - [x] No new external network dependencies introduced (mock backend used per Testing Strategy) — reuses the existing Ollama reachability probe and embeddings RPC; no new deps.
- [x] Manual smoke checklist updated if this touches release-cut surfaces (
docs/RELEASE-MANUAL-SMOKE.md) —N/A: no release-cut UI surface, Rust core only. - [x] N/A — linked issue intentionally NOT auto-closed: this is a partial fix (1 of 4 items in #3312); maintainer closes #3312 once all land.
Impact
- Runtime/platform impact (desktop/mobile/web/CLI), if any. — Rust core (CLI/desktop/docker); no frontend changes.
- Performance, security, migration, or compatibility implications. — Per-tick cost is a single atomic load when the latch is clear (no-op). No memory wipe (dimension-matched), no migration. Switch only ever moves managed-cloud → local; BYO providers are never affected.
Related
- Closes: — none (partial fix; #3312 stays open until MCP auto-reconnect and granular health also land). Refs #3312 (embedding-fallback item), #3329 (scheduler auto-recovery, merged), #1574 (signature invariant).
- Follow-up PR(s)/TODOs: MCP server auto-reconnect; granular per-component health checks.
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/3312-embedding-cloud-local-fallback
- Commit SHA: eeb2c0f555af0b404b4838972587d784bf6c7211
Validation Run
- [x]
pnpm --filter openhuman-app format:check— passed via pre-push hook. - [x]
pnpm typecheck— passed via pre-push hook. - [x] Focused tests:
GGML_NATIVE=OFF cargo test --lib embeddings::cloud_fallback(8 passed);embeddings::suite (161 passed). - [x] Rust fmt/check (if changed):
cargo fmt --checkclean;GGML_NATIVE=OFF cargo check --bin openhuman-coreclean. - [x] Tauri fmt/check (if changed): N/A — no
app/src-taurichanges.
Validation Blocked
command:N/Aerror:N/Aimpact:N/A
Behavior Changes
- Intended behavior change: managed-cloud embedding auth expiry auto-switches to a preloaded, dimension-matched local embedder and re-indexes under the new signature; takes effect without a process restart.
- User-visible effect: indexing keeps working through a backend session expiry instead of stalling until a manual restart; no user action required.
Parity Contract
- Legacy behavior preserved: when no local embedder is preloaded, or dims differ, behavior is unchanged (cloud failure surfaced, no wipe, no switch).
- Guard/fallback/dispatch parity checks: switch gated on configured provider ==
cloud/managed; a 401 from a BYO key can set the latch but never flips the user's provider.
Duplicate / Superseded PR Handling
- Duplicate PR(s): none
- Canonical PR: this PR
- Resolution (closed/superseded/updated): N/A
Summary by CodeRabbit
-
New Features
- Automatic failover from managed cloud embeddings to a local embedder when repeated cloud auth failures occur, applied seamlessly at runtime.
-
Improvements
- Workers now detect and apply persisted provider changes without restart.
- Stronger local embedder probe that verifies model availability before switching.
-
Tests
- Added unit tests covering latch behavior, switch eligibility, model-probing, and idempotent worker behavior.
📝 Walkthrough
Walkthrough
This PR introduces an automatic embedding provider fallback mechanism that switches from managed cloud to local Ollama when confirmed HTTP 401/403 auth failures occur. A process-global latch detects failures, guard logic validates local compatibility and dimensionality, and the worker loop applies the switch without crashing or requiring a restart.
Changes
Cloud-to-Local Embedding Provider Fallback
| Layer / File(s) | Summary |
|---|---|
Cloud fallback module foundation: latch, guard logic, and public API src/openhuman/embeddings/cloud_fallback.rs, src/openhuman/embeddings/mod.rs, src/openhuman/embeddings/README.md |
Adds module docs, a process-global atomic auth-failure latch (note_embedding_auth_failure(), embedding_auth_failed(), clear_embedding_auth_gate()), a monotonic CONFIG_GENERATION counter, and a pure should_switch predicate that gates switching on auth failure, managed cloud provider, local Ollama availability, and matching embedding dimensions. Exposes cloud_fallback submodule. |
Cloud fallback async worker-side switching logic src/openhuman/embeddings/cloud_fallback.rs |
maybe_switch_cloud_to_local async function runs on each worker tick: early-exits when latch is clear, clears the latch for non-managed-cloud providers, probes local Ollama availability, persists provider switch via RPC (update_settings), bumps CONFIG_GENERATION and clears the latch only after successful persistence, and reports errors while leaving the latch set for retry. |
Cloud fallback unit tests and guard coverage src/openhuman/embeddings/cloud_fallback.rs |
Unit tests verify latch set/clear/idempotency, no-op when latch is clear, latch clearing for non-cloud providers, and should_switch truth-table combinations (auth failure required, provider must be managed cloud, local reachability required, and dimensions must match). |
OpenAI embedding auth failure detection and latch management src/openhuman/embeddings/openai.rs |
OpenAI embed method now detects 401/403 responses and latches auth failures via note_embedding_auth_failure(), and clears the latch on successful embedding computation via clear_embedding_auth_gate(). |
Memory queue worker loop calls cloud fallback switching on each tick src/openhuman/memory_queue/worker.rs |
Each worker task now maintains a mutable cfg clone and awaits maybe_switch_cloud_to_local(&cfg) on every loop iteration; when config_generation advances the worker loads a fresh persisted config and updates cfg in-place so subsequent jobs use the switched provider without restart. |
Ollama model probe and tests src/openhuman/memory_store/factories.rs |
Adds probe_ollama_model_available and ollama_tag_matches_model to verify daemon reachability and that the requested model exists in /api/tags; includes mock server helper and async tests for present/missing/unreachable cases. |
Sequence Diagram
sequenceDiagram
participant Client as Embedding Client
participant OpenAI as OpenAiEmbedding
participant Latch as Auth Failure Latch
participant Worker as Worker Loop
participant Gate as maybe_switch_cloud_to_local()
participant RPC as Settings RPC
participant Config as Config Reload
Client->>OpenAI: embed request
OpenAI-->>Client: 401 Unauthorized
OpenAI->>Latch: note_embedding_auth_failure()
loop Each worker tick
Worker->>Gate: maybe_switch_cloud_to_local(&cfg)
Gate->>Gate: check latch + guards
alt Latch set, managed cloud, local reachable, dims match
Gate->>RPC: update_settings(switch to local)
RPC-->>Gate: persisted
Gate->>Config: load_config_with_timeout()
Config-->>Gate: Some(fresh_cfg)
Gate-->>Worker: Some(fresh_cfg)
Worker->>Worker: cfg = fresh_cfg
else Guard fails or latch clear
Gate-->>Worker: None
end
end
Client->>OpenAI: embed request (now using local)
OpenAI-->>Client: embeddings (from local Ollama)
OpenAI->>Latch: clear_embedding_auth_gate()
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~25 minutes
Suggested labels
rust-core
Poem
🐰 Hops through clouds to find the ground,
When auth fails, no crash around,
Local embeddings take the stage,
A graceful fallback on the page! ✨
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title clearly describes the main change: automatic fallback from managed cloud embeddings to local on 401/403 auth failures, which aligns with the core functionality added across the changeset. |
| 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. |
| 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.
Pushed b95280c7 addressing the three Major review findings (model-availability gating, latch-until-durable, all-workers reload via a config-generation counter) — replied inline on each thread.
Re the nitpick to move cloud_fallback.rs under a cloud_fallback/ subdirectory: respectfully skipping for now. The embeddings/ domain is already a flat module with all providers/helpers as sibling .rs files (cloud.rs, openai.rs, voyage.rs, cohere.rs, ollama.rs, noop.rs, rate_limit.rs, retry_after.rs, …). The "dedicated subdirectory" guideline targets new top-level openhuman/<domain> modules, not single files within an existing flat domain. A one-file cloud_fallback/mod.rs would diverge from the established convention here; happy to promote it to a subdir if/when it grows siblings.
id' disaggree here. since changing embeedding would actually change the results. not all embeddings are the same. if we have auth changed in the middle the solution is to fix the auth. not fallback the embeddings.