openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(embeddings): refuse empty embed inputs at provider + caller boundaries (#13021)

Open CodeGhost21 opened this issue 5 months ago • 1 comments

Summary

  • Add a pre-flight guard on OpenAiEmbedding::embed (and mirrored on OpenHumanCloudEmbedding::embed) that refuses empty/whitespace entries before the HTTP round-trip, with a bail wording deliberately distinct from "Embedding API error" so the refusal does not re-enter the core::observability upstream-HTTP Sentry route.
  • Make the two known background sources of empty content skip the embed call entirely: memory_tree::tree::bucket_seal::seal_one_level and the doc-subtree branch (both at truncate_for_embed ≈ ""), and agent::harness::archivist::lifecycle::on_segment_closed as defence in depth.
  • Lock the new contract with focused tests at every layer — provider boundary, cloud wrapper, and bucket-seal seal path (with InertEmbedder wired so summary.embedding == None is only explainable by the new short-circuit).

Problem

Sentry TAURI-RUST-BMP — issue #13021 — fired 1547 events from 8 users across macOS (954) / Windows (589) / Linux (4) between 2026-06-09 and today. Every event was identical: model=embedding-v1, operation=openai_embed, failure=non_2xx, status=400. Backend body:

{"success":false,"error":"input must be a non-empty string or array of non-empty strings","errorCode":"BAD_REQUEST"}

The wording is the giveaway — the array was not empty; it contained an empty string. The pre-flight in OpenAiEmbedding::embed only short-circuited empty slices (texts.is_empty()), so a single-element call like embed_one("") → embed(&[""]) slipped through, the HTTP request fired with "input": [""], the backend correctly 400'd, and report_error_or_expected(...) turned it into a recurring Sentry server fault — even though the defect was on the client side.

Two upstream callers feed empty/whitespace content into that path:

  • memory_tree::tree::bucket_seal (both seal_one_level ≈ line 458 and the doc-subtree path ≈ line 1234). summarise() returns SummaryOutput::default() (content = "") when the body it builds for the LLM is all whitespace; fallback_summary joins zero parts the same way. truncate_for_embed("", 1_000) is "". This runs on background memory-tree seals — the dominant source of the per-user volume.
  • agent::harness::archivist::lifecycle::on_segment_closed — defence in depth. summarize_entries is not currently known to return empty under any branch, but the guard prevents future regressions from re-introducing the same bug.

Solution

Layer 1 — provider boundary (the bug's actual fault site). OpenAiEmbedding::embed and OpenHumanCloudEmbedding::embed reject empty/whitespace entries with a typed client-side error before any HTTP work. The bail wording is intentionally "refusing empty/whitespace input at index N of M (model=…)" — it deliberately does not contain "Embedding API error" or "(<status>", the two shapes that core::observability treats as upstream HTTP failures. So the refusal is plain anyhow::Error propagation, not a Sentry-as-server-fault event. A unit test pins this wording (embed_refuses_does_not_use_embedding_api_error_prefix).

The cloud wrapper runs the same check before resolve_bearer, so unauthenticated test contexts surface the real refusal instead of "No backend session…".

Layer 2 — caller cleanup (the actual sources of empty content). Both bucket_seal call sites short-circuit when embed_input.trim().is_empty() after truncate_for_embed, falling through to the same "embedding-less, re-embeddable later" path as the existing no-provider branch (#002 contract). The archivist guard is a parallel skip for the same reason. No wasted round-trips, no quota burn, no Sentry noise.

Why this over a classifier suppression. A single-line core::observability rule mapping "input must be a non-empty" 400s to a warning would have silenced the report, but it would have kept the wasted network call, the backend-quota debit, and the underlying mistake intact — and feedback_sentry_skip_vs_real_fix explicitly requires we ask whether a deeper code fix exists first. It does, on both layers.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy — 6 new tests, all cover the failure path that fired in production
  • [x] Diff coverage ≥ 80% — every new branch in OpenAiEmbedding::embed, OpenHumanCloudEmbedding::embed, both bucket_seal skip paths, and the archivist guard has an explicit unit test exercising it. pnpm test:rust -- -- 'embeddings::|memory_tree::tree::bucket_seal|archivist' is green locally.
  • [x] Coverage matrix updated — N/A: behaviour-only fix (failure-mode hardening on existing embedding pipelines, no new feature)
  • [x] All affected feature IDs from the matrix are listed in the PR description under ## Related — N/A: behaviour-only fix, no matrix rows touched
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy) — the bug is exactly about a wasted network call; new tests assert the guard short-circuits before any HTTP request and use http://unused as a tripwire
  • [x] Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md) — N/A: backend defence-in-depth, no UI / installer / release-cut surface change
  • [x] Linked issue closed via Closes #NNN in the ## Related section — N/A: tracked in self-hosted Sentry (TAURI-RUST-BMP / #13021), no GitHub issue exists

Impact

  • Runtime / platform: desktop (macOS / Windows / Linux). The bug fired on every shipped platform that has a memory-tree seal background loop — i.e. all of them. The fix lives entirely in openhuman-core (Rust); no Tauri shell, frontend, mobile, or CLI surface touched.
  • Performance: positive — eliminates a network round-trip plus backend quota debit for every empty seal (1547 calls in 5 days against a known-bad payload). Background memory-tree seals on heavy users complete faster.
  • Security: none — pure input validation hardening at a boundary.
  • Migration / compatibility: none. The skipped seals still produce summary nodes — they just carry embedding: None, which the read path already handles (re-embeddable later). No schema, no config, no API change.
  • Sentry blast radius: TAURI-RUST-BMP / #13021 should drop to zero new events once the release lands. Any legitimate server-side non_2xx from the embedding endpoint still reports normally (the classifier path is untouched).

Related

  • Closes: N/A — tracked in Sentry (self-hosted), not GitHub. Sentry issue: https://sentry.tinyhumans.ai/organizations/tinyhumans/issues/13021/
  • Follow-up PR(s)/TODOs: none. The two upstream callers and the boundary are the complete fix; no deferred work.

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

Linear Issue

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

Commit & Branch

  • Branch: fix/sentry-13021-empty-embed-input
  • Commit SHA: c4570b653eb34dcefd94b2f7f29723924094b60c

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A (Rust-only change, no app/ files touched)
  • [x] pnpm typecheck — N/A (Rust-only change, no TypeScript touched)
  • [x] Focused tests: cargo test --lib -- embeddings::openai (40 passed), cargo test --lib -- embeddings::cloud (4 passed including new embed_refuses_empty_string_without_auth), cargo test --lib -- memory_tree::tree::bucket_seal (15 passed including new whitespace_llm_summary_seals_without_embedding), cargo test --lib -- agent::harness::archivist (16 passed — no regressions)
  • [x] Rust fmt/check (if changed): cargo fmt --check clean; cargo check --manifest-path Cargo.toml clean (2 pre-existing warnings in src/bin/slack_backfill.rs, unrelated)
  • [x] Tauri fmt/check (if changed): N/A (no Tauri shell files touched)

Validation Blocked

  • command: N/A — nothing blocked
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: empty / whitespace-only embed inputs now bail with a typed client-side error before any HTTP round-trip; the two known background sources skip the embed entirely and seal embedding-less (re-embeddable later)
  • User-visible effect: none beyond the Sentry storm clearing. Memory-tree seals that previously produced a 400 + zero-vector now produce a summary node with embedding = None, which the existing read path already tolerates and surfaces as "semantic recall available once content is non-empty"

Parity Contract

  • Legacy behavior preserved: every existing path that fed non-empty text to the embedder behaves identically; the success path test coverage (embed_success_single, embed_success_batch, crossing_budget_triggers_seal, phase1_llm_recap_and_embedding_on_segment_close, etc.) is unchanged and still passes
  • Guard/fallback/dispatch parity checks: the empty-content branch in bucket_seal matches the existing no-provider branch — both produce embedding: None, both warn-log, both leave the summary node otherwise intact. The archivist guard mirrors its existing no-embedder branch the same way

Duplicate / Superseded PR Handling

  • Duplicate PR(s): N/A — no prior PR or local branch targets issue 13021 (verified before starting)
  • Canonical PR: this one
  • Resolution (closed/superseded/updated): N/A

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Prevented embedding calls for empty or whitespace-only text across embedding providers and recap/summary sealing flows, avoiding unnecessary requests and ensuring embeddings aren’t stored for blank content.
    • When LLM summaries return blank/whitespace, the system now reliably falls back to deterministic content and still produces the expected summary embedding.
    • Empty/whitespace embedding refusals are now treated as unrecoverable and surfaced with a new remediation message.
  • Tests

    • Added/expanded coverage for early rejection, correct fallback behavior, and verification that embedding rows are not created for blank recaps/summaries.

CodeGhost21 avatar Jun 14 '26 14:06 CodeGhost21

Review Change Stack

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: 2a6a0288-91bc-47e3-95fe-318d3abd4001

📥 Commits

Reviewing files that changed from the base of the PR and between 88b889ac8f8aa97cdf59746abc315a2b27156ed4 and f18305597cf1b874a0910746b6a6c7118fbd2416.

📒 Files selected for processing (1)
  • app/src/lib/i18n/fr.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/src/lib/i18n/fr.ts

📝 Walkthrough

Walkthrough

Pre-flight validation is added to OpenAiEmbedding::embed and OpenHumanCloudEmbedding::embed to reject empty or whitespace-only inputs before any API call or auth resolution. The same guard is applied in seal_one_level and seal_explicit_children in the memory-tree seal path, and in ArchivistHook::on_segment_closed via a new embed_segment_recap helper, all short-circuiting to produce no embedding rather than calling the embedder. Error classification is extended to recognize these refusals as a distinct unrecoverable failure cause, and i18n messages are added across all supported languages to explain the condition to users.

Changes

Empty/whitespace embedding guards and observability

Layer / File(s) Summary
Pre-flight validation in OpenAI and cloud embedders
src/openhuman/embeddings/openai.rs, src/openhuman/embeddings/openai_tests.rs, src/openhuman/embeddings/cloud.rs
OpenAiEmbedding::embed and OpenHumanCloudEmbedding::embed each gain a guard that locates the first empty/whitespace text, emits a tracing::warn!, and returns an anyhow::bail! error before any bearer-token resolution or HTTP request. Tests pin the bail message wording and confirm it fires before the "No backend session" path; four OpenAI test cases cover single empty, whitespace-only, and mixed-batch inputs.
Error classification and health failure tracking
src/openhuman/memory_tree/health/mod.rs
FailureCode::EmptyInputRefused is introduced as a new unrecoverable failure variant with stable wire string and i18n remediation key mapping. classify_embed_error_str detects the "refusing empty/whitespace" error message early (before other embedding heuristics) and maps it to EmptyInputRefused. Degradation cause encoding is extended to support the new variant for process-visible status reporting. Unit tests verify classification works both directly and through anyhow::context error chains.
Empty-summary short-circuit in memory-tree seal paths
src/openhuman/memory_tree/tree/bucket_seal.rs, src/openhuman/memory_tree/tree/bucket_seal_tests.rs
seal_one_level and seal_explicit_children both skip embedder construction and the embed() call when the truncated summary input is empty/whitespace, logging a #13021 reference and persisting the summary with embedding: None. A regression test uses an LLM output returning whitespace to trigger a seal and asserts the resulting summary has deterministic fallback content (non-empty) and a sidecar embedding record.
Empty-recap guard in archivist lifecycle
src/openhuman/agent/harness/archivist/lifecycle.rs, src/openhuman/agent/harness/archivist_tests.rs
ArchivistHook::on_segment_closed delegates recap embedding to a new embed_segment_recap helper that checks if the summary is empty or whitespace and, when true, logs a warning and returns early, skipping the embedder entirely and leaving no embedding row for that segment. Tests introduce a panic-based Embedder to assert the guard prevents any embed calls for empty or whitespace input, plus a positive control verifying non-empty recaps still produce embedding rows.
i18n remediation messages for empty-input refusal
app/src/lib/i18n/*.ts
New translation key memory.health.remediation.empty_input_refused is added across all supported language files (Arabic, Bengali, German, English, Spanish, French, Hindi, Indonesian, Italian, Korean, Polish, Portuguese, Russian, Simplified Chinese), providing localized user-facing messages explaining that memory items are skipped when text is empty and that embeddings continue normally.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🐇 A hop, a skip, a careful look, Empty strings? I close the book! No blank embeddings down the wire, Whitespace prompts? We shall not fire. The archivist guards, the seal stands tall— 🌿 No zero-vectors for us at all!

🚥 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 directly describes the main change: implementing validation to refuse empty embed inputs at provider and caller boundaries to fix issue #13021.
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.

✏️ 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 14 '26 14:06 coderabbitai[bot]