Skip to content

fix(ai): a failing embedding model pauses rag lookups instead of ending rag for the run, and each embedding model gets its own prompts, cache keys, dimension and bounded chunks #1065

Closed

Description

@dan-petty

Problem

RAG gives reviews nothing today, and the RAG client has six defects that would keep it that way once an index exists. Lines are at release/v0.2.25 (e3ff98c).

1. One failed lookup turns RAG off for the whole run.

2. Cache keys ignore the prefix. The L1 key (embeddings.py:103-106) and the Valkey key (:391-395) hash the model, a query/document tag and the unprefixed text. The prefix is applied only to misses (:630), and vectors are stored under the original text (:654-655). Changing the prompt for the same model therefore keeps serving vectors made with the old prompt for the Valkey TTL of 7 days (config/defaults.py:210). That covers rag index --force too.

3. The prompts are wrong for both candidate models. Any model whose name contains qwen, bge or e5 gets query: / passage: (embeddings.py:668-680).

  • The bge-m3 card says it needs no instruction [sourced: https://huggingface.co/BAAI/bge-m3].
  • Qwen3-Embedding wants Instruct: {task}\nQuery:{query} on queries and nothing on documents. The card says that leaving out the query instruction costs about 1–5% in retrieval [sourced: https://huggingface.co/Qwen/Qwen3-Embedding-0.6B].
  • qwen3-embedding:0.6b is devops-cli's default embedding model (config/defaults.py:201).

4. The fallback dimension for qwen3-embedding is wrong. CONST_KNOWN_EMBEDDING_DIMENSIONS (config/constants.py:2096-2108) gives qwen3-embedding 768 (:2106). The model's vectors have 1024 dimensions [sourced: the card above]. EmbeddingsEngine falls back to this table when it cannot probe the model (embeddings.py:471-475), and so sizes a new collection wrongly.

5. ai.rag.top_k and ai.rag.score_threshold are never read.

  • AIRAGConfig declares them (config/settings.py:368-369), and config/options.py:60-61 names them, but the only ai.rag field anything reads is enabled (investigator.py:264, commands/rag.py:487).
  • The retriever takes top_k or DEFAULT_RAG_TOP_K and score_threshold or DEFAULT_RAG_SCORE_THRESHOLD (investigator.py:106-107).
  • No review, verification or chat lookup passes a threshold (ai/review/pipeline.py:1484, ai/review/verification.py:297, commands/ai.py:202), so the 0.35 constant (defaults.py:212) always applies. It cannot be recalibrated for a new model until the setting is read.

6. Nothing bounds a chunk's size, and one failed batch ends the index.

  • The line-window chunker counts lines, not tokens (ai/rag/chunker.py:626-630, window DEFAULT_RAG_CHUNK_SIZE = 2400 lines).
  • Run offline at this commit's chunker, uv.lock (3,741 lines) gives two chunks of 160,554 and 109,480 cl100k tokens (lines 1–2400 and 2161–3741).
  • The slow-tier plan's offline run over the repository found 17,499 chunks, 23 of them over 8,192 tokens, with a p99 of 1,557.
  • _upsert_chunks (ai/rag/indexer.py:591-611) embeds each batch with no handling, so one failed batch (up to 256 chunks, :586-587) raises out of index_workspace and ends the index.
  • Through the gateway, each batch is one request with the 30 s read timeout.
  • Ollama silently cuts bge-m3 inputs at about 2,048 tokens. Qwen3-Embedding reads up to 32K, so it embeds such chunks in full [code: Ollama v0.34.4 server/routes.go, per the plan's verification].

The Qdrant collections are effectively empty today: 76 of 76 searches returned nothing [measured: qdrant-0 log]. So these fixes come before the first index, and the switch to qwen3-embedding:0.6b (#481) comes after them.

Source: .data/slow-tier-plan-20261003.md, sections 1 and 4, and its verification pass. The cited lines were re-read at e3ff98c.

Acceptance criteria

  • Permanent errors stop RAG; transient ones pause it.
    • An EmbeddingsError from a 400 or 404 that names an unknown or unserved model is permanent. It stops RAG for the run as today, with one warning. tests/test_review_embeddings_unserved.py (five findings, at most one embedding request) keeps passing.
    • A timeout, connection error, 408, 429 or 5xx is transient. It skips that lookup only.
    • After 3 consecutive transient failures, a circuit breaker opens for 60 s. While it is open, lookups return None without sending a request. After the pause, one lookup probes. A success closes the breaker; a failure opens it again.
    • EmbeddingsError records which kind it is where it is raised. The investigator does not parse message text.
  • No failed lookup waits its turn. While no lookup has succeeded, one lookup probes. Lookups that arrive meanwhile wait for its outcome, not for their turn under _PROBE_LOCK: if it succeeds they run concurrently, and if it fails they skip.
    • A test runs 20 concurrent lookups against a stub embedder that hangs until a patched 0.2 s timeout. They finish in under 1 s in total, and the stub receives at most 2 requests. The test fails on the current code.
    • With a healthy stub, all 20 lookups get context.
  • Tests with a stub embedder and a patched clock:
    • three timeouts, then lookups during the pause send no request;
    • the probe after the pause succeeds and lookups resume;
    • a 429 "No deployments available" counts as transient.
  • Cache keys hash the text sent. The L1 and Valkey keys hash the text after its prompt is applied. A test embeds the same text for the same model under two prompts and gets two cache misses. It fails on the current code.
  • Per-model prompts. bge-m3 gets no prefix. qwen3-embedding* queries get Instruct: Given a code search query, retrieve relevant code or documentation\nQuery: and its documents get none. nomic* keeps search_query: / search_document: , e5* keeps query: / passage: , and every other model gets none. A parametrised test covers each family, for queries and for documents.
  • CONST_KNOWN_EMBEDDING_DIMENSIONS["qwen3-embedding"] is 1024, and a test pins it.
  • The ai.rag settings are read. The retriever's defaults come from ai.rag.top_k and ai.rag.score_threshold, compared with is None, so a threshold of 0 is honoured. A caller's explicit per-use top_k (3 per file in reviews, 2 per finding) still wins. Chat's lookup takes its default from ai.rag.top_k, not from the constant (commands/ai.py:196). A test sets score_threshold: 0.5 and sees it reach the Qdrant search.
  • Lockfiles are not indexed. The indexer skips uv.lock, other *.lock files, package-lock.json, pnpm-lock.yaml and go.sum.
  • No chunk sent to the embedder is over 8,192 tokens (the project's token estimate). Longer line windows are split. A test chunks a 4,000-line synthetic file and checks every chunk.
  • A failed batch still ends the index with exit 1 (fix(ai): reviews ask an unserved embedding model on every lookup and search with a hash fallback #945's rule), naming the batch's first and last file. Earlier batches stay indexed and recorded in the index cache, so devops ai rag index without --force resumes after them. A test with a stub embedder that fails the second batch pins both.
  • MESSAGES.rag gains the pause message. The investigator docstring (investigator.py:248) and the knowledge base (src/devops_cli/ai/knowledge_base/devops_cli/tasks/rag_context_indexing.md:52) describe the breaker instead of "RAG is off for the rest of the run".
  • The tests run offline with stub embedders and a fake Qdrant client, call no gateway, Ollama, Qdrant or Valkey, and each runs in under 1 s.
  • changelog.d/1065.md records the fix under ### Fixed. CHANGELOG.md is not edited.
  • uv run devops ci passes.
  • (person-run) After fix(k8s): ollama-48gib-slow keeps its embedding model and qwen3-coder loaded and leaves every interactive pool, so a review no longer evicts the embedder #1064 is applied: restart hog's Ollama pod while a multi-file review runs. The review logs the pause, RAG lookups resume once hog is back, and the review finishes. Across several multi-file reviews, no "RAG is off for the rest of this run" warning appears unless the embedding model is not served.

Key questions

Depends on: none.
Order:

Related:

Activity

  1. added
    type/bug
    scope/ai
    priority/p1-high
    on Oct 3, 2026
  2. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Review redesign (#1137, 2026-10-03): this item is a phase P0 child, kept whole. Its breaker, per-model prompts, cache keys, chunk caps and ai.rag settings serve the chat and the KB index that #1139 keeps current. Its person-run line stands until #1151 removes review-time RAG; after that, #1139's person-run covers it. (A separate consolidation proposal, that the breaker comes from a maintained library behind a reusable seam shared with #596, is left to a person.)

  3. added this to the v0.2.28 milestone on Oct 6, 2026
  4. dan-petty-bot commented on Oct 6, 2026

    @dan-petty-bot
    Collaborator

    Moved to v0.2.28: v0.2.28 started with fewer than its 12 items and was topped up to 12 from Ready items, critical fixes and P0 features first. (devops roadmap reprioritize)

  5. dan-petty commented on Oct 7, 2026

    @dan-petty
    OwnerAuthor

    Resolved by #1274.

  6. dan-petty-bot commented on Oct 7, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1274, merged into release/v0.2.28 as ad9fba0.

    Description

    Resolves #1065.

    Previously, a transient embedding model failure (e.g. 5xx status, connection timeout, rate limit 429) stopped RAG lookups for the rest of the CLI run identically to an unserved or missing model. Furthermore, lookup requests while unserved queued sequentially under a lock rather than coordinating a single probe, embedding cache keys did not differentiate between models and task prompts, `qwen3-embedding` dimension was not pinned to 1024, package manager lockfiles were unnecessarily indexed, oversized chunk line windows could exceed model context boundaries, and indexer batch failures raised unhandled errors without naming the batch files or preserving earlier batches for resume.

    This PR implements the following fixes:

    • Circuit Breaker on Transient Errors: Permanent errors (400 or 404 naming unserved/unknown models) stop RAG for the run with one warning. Transient errors (timeouts, connection resets, 408, 429, 5xx) skip only the failing lookup. After 3 consecutive transient failures, a circuit breaker opens for 60 seconds (`CONST_RAG_CIRCUIT_BREAKER_PAUSE_SECONDS`). While open, lookups immediately return `None` without dispatching requests.
    • Probe Coordination (`_ProbeCoordinator`): Instead of serializing all concurrent lookups under `_PROBE_LOCK`, lookups that arrive while no lookup has succeeded wait on a single probe lookup. If the probe succeeds, waiters run concurrently; if the probe fails, waiters skip immediately.
    • *…

    15 file(s) changed.

    How it was verified

    Check runs at ed0bfc4:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Static Analysis: pass
    • Analyze (actions): pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-1065-failing-embedding-model-pauses-rag.md:

    • Permanent errors stop RAG; transient ones pause it (circuit breaker after 3 failures pauses for 60 s; EmbeddingsError records is_transient).
    • No failed lookup waits its turn (concurrent lookups wait on single probe outcome, finishing in < 1 s with $\le 2$ requests).
    • Tests with stub embedder and patched clock verify pause, resume, and 429 transient behavior.
    • Cache keys hash prompted text; same text under two prompts yields two cache misses.
    • Per-model prompt prefixes for bge-m3, qwen3-embedding, nomic, e5, and others verified with parametrized tests.
    • CONST_KNOWN_EMBEDDING_DIMENSIONS["qwen3-embedding"] is pinned to 1024.
    • ai.rag settings for top_k and score_threshold are read and reach Qdrant search.
    • Lockfiles (uv.lock, *.lock, package-lock.json, pnpm-lock.yaml, go.sum) are skipped by indexer.
    • No chunk sent to embedder exceeds 8,192 tokens; 4,000-line synthetic file chunking verified.
    • Failed batch ends index with exit 1 naming first and last file; earlier batches stay cached for resume.
    • MESSAGES.rag.paused added, docstrings and knowledge base updated.
    • Offline tests with stub embedders run without gateway/network and each under 1 s.
    • changelog.d/1065.md records the fix under ### Fixed.
    • uv run devops ci passes.
    • Pending a person: (after fix(k8s): ollama-48gib-slow keeps its embedding model and qwen3-coder loaded and leaves every interactive pool, so a review no longer evicts the embedder #1064) restart hog's Ollama pod while a multi-file review runs to verify pause and resume live.
  7. added a commit that references this issue on Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/aitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions