diff --git a/changelog.d/1065.md b/changelog.d/1065.md
new file mode 100644
index 0000000000..598a128153
--- /dev/null
+++ b/changelog.d/1065.md
@@ -0,0 +1,7 @@
+### Fixed
+
+- A failing embedding model pauses RAG lookups with a circuit breaker after three consecutive transient errors instead of permanently ending RAG for the run, while permanent errors from unknown or unserved models stop RAG with one warning (#1065).
+- Route lookups concurrently once healthy while coordinating a single probe after failures, avoiding serialized wait loops across concurrent review workers (#1065).
+- Hash prompt-prefixed text for L1 and Valkey L2 embedding cache keys, supporting distinct model prompt prefixes across `qwen3-embedding`, `bge-m3`, `nomic`, and `e5` families (#1065).
+- Pin `CONST_KNOWN_EMBEDDING_DIMENSIONS["qwen3-embedding"]` to 1024, honor configured `ai.rag.top_k` and `ai.rag.score_threshold` (including threshold 0), skip package manager lockfiles, and bound semantic chunks to at most 8,192 tokens (#1065).
+- End failed indexing batches with exit 1 naming the first and last file, while retaining earlier indexed batches in cache for fast incremental resume without `--force` (#1065).
diff --git a/docs/agent/tasks/task-1065-failing-embedding-model-pauses-rag.md b/docs/agent/tasks/task-1065-failing-embedding-model-pauses-rag.md
new file mode 100644
index 0000000000..3a4143f5fd
--- /dev/null
+++ b/docs/agent/tasks/task-1065-failing-embedding-model-pauses-rag.md
@@ -0,0 +1,40 @@
+# Task: Failing Embedding Model Pauses RAG Lookups and Embedders Gain Model-Specific Configurations (#1065)
+
+**Issue**: [#1065](https://github.com/dan-petty/devops-cli/issues/1065)
+**Status**: Done
+**Milestone**: v0.2.28
+**Priority**: priority/p1-high
+**Scope**: scope/ai
+
+## Description
+
+A transient embedding model failure (e.g. 5xx status, connection timeout, rate limit 429) previously 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 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 parsed and 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 deliverable resolves all acceptance criteria for #1065:
+- **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.
+- **Prompted Cache Keys**: L1 and Valkey L2 cache keys hash the text after the prompt prefix is applied (`f"{model}\x00{sent_text}"`), ensuring queries and documents, or multiple prompts on identical text, map to distinct cache entries.
+- **Per-Model Prompts**: `bge-m3` uses no prompt prefix. `qwen3-embedding*` queries receive `CONST_QWEN3_EMBEDDING_QUERY_PREFIX` (`Instruct: Given a code search query, retrieve relevant code or documentation\nQuery:`) and documents receive none. `nomic*` uses `search_query: ` / `search_document: `, `e5*` uses `query: ` / `passage: `, and other models use none.
+- **Pinned Known Dimensions**: `CONST_KNOWN_EMBEDDING_DIMENSIONS["qwen3-embedding"] = 1024`.
+- **RAG Settings Read**: `SemanticRetriever` defaults are read from `st.ai.rag.top_k` and `st.ai.rag.score_threshold` compared with `is None`, honoring threshold `0.0`. CLI chat inherits `top_k` from settings.
+- **Lockfile Skipping**: `WorkspaceIndexer` skips `uv.lock`, other `*.lock` files, `package-lock.json`, `pnpm-lock.yaml`, and `go.sum`.
+- **Bounded Chunk Tokens**: All returned chunks are bounded to `CONST_RAG_MAX_CHUNK_TOKENS` (8,192 tokens). Longer line windows are split into sub-windows.
+- **Batch Failure Naming and Incremental Resume**: A failing batch in `_upsert_chunks` raises `EmbeddingsError` with exit code 1 naming the batch's first and last file, while earlier batches remain persisted in cache so `devops ai rag index` resumes without re-indexing.
+- **Documentation & Messages**: Added `MESSAGES.rag.paused`, updated docstrings in `investigator.py`, and updated task documentation in `rag_context_indexing.md`.
+
+## Acceptance Criteria
+- [x] Permanent errors stop RAG; transient ones pause it (circuit breaker after 3 failures pauses for 60 s; `EmbeddingsError` records `is_transient`).
+- [x] No failed lookup waits its turn (concurrent lookups wait on single probe outcome, finishing in < 1 s with $\le 2$ requests).
+- [x] Tests with stub embedder and patched clock verify pause, resume, and 429 transient behavior.
+- [x] Cache keys hash prompted text; same text under two prompts yields two cache misses.
+- [x] Per-model prompt prefixes for `bge-m3`, `qwen3-embedding`, `nomic`, `e5`, and others verified with parametrized tests.
+- [x] `CONST_KNOWN_EMBEDDING_DIMENSIONS["qwen3-embedding"]` is pinned to 1024.
+- [x] `ai.rag` settings for `top_k` and `score_threshold` are read and reach Qdrant search.
+- [x] Lockfiles (`uv.lock`, `*.lock`, `package-lock.json`, `pnpm-lock.yaml`, `go.sum`) are skipped by indexer.
+- [x] No chunk sent to embedder exceeds 8,192 tokens; 4,000-line synthetic file chunking verified.
+- [x] Failed batch ends index with exit 1 naming first and last file; earlier batches stay cached for resume.
+- [x] `MESSAGES.rag.paused` added, docstrings and knowledge base updated.
+- [x] Offline tests with stub embedders run without gateway/network and each under 1 s.
+- [x] `changelog.d/1065.md` records the fix under `### Fixed`.
+- [x] `uv run devops ci` passes.
+- Pending a person: (after #1064) restart hog's Ollama pod while a multi-file review runs to verify pause and resume live.
diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/rag_context_indexing.md b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/rag_context_indexing.md
index b118c29469..da9d3552e9 100644
--- a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/rag_context_indexing.md
+++ b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/rag_context_indexing.md
@@ -49,7 +49,7 @@ devops ai rag clear
2. **Include Structural Metadata**: Attach file path, heading hierarchy, and source repository names as metadata attributes on each indexed chunk.
3. **Re-index After Documentation Updates**: Re-run `devops ai rag index` whenever major documentation or architectural changes are merged.
4. **Grounded Inferences**: Instruct LLM prompts to cite specific document paths when answering queries based on retrieved context.
-5. **Serve the Embedding Model, or Turn RAG Off**: Embeddings come from the model configured under `ai.tasks.embedding`, or not at all. A failed request raises `EmbeddingsError`, naming the model, the endpoint or Ollama nodes, and the HTTP status or error. No stand-in vector is made. In a review, chat or analysis run, the first lookup that fails turns RAG off for the rest of the run and logs one warning that says how to fix it. Until the model has answered a lookup, lookups that run at once, such as the review workers' per-file lookups, take turns, so they send one request between them. Later lookups send no request, so a node that keeps one model loaded does not swap out the review model for the embedding model. `devops ai rag index`, `index-kb`, `query` and `drift --auto-sync`, and `devops ai ingest index-libraries` and `query-library`, exit 1 with the error, and indexing stores no vector for a text the model did not embed. To fix it, serve the model on a backend, point `ai.tasks.embedding` at a backend that serves it, or set `ai.rag.enabled: false`.
+5. **Serve the Embedding Model, or Turn RAG Off**: Embeddings come from the model configured under `ai.tasks.embedding`, or not at all. A failed request raises `EmbeddingsError`, naming the model, the endpoint or Ollama nodes, and the HTTP status or error. No stand-in vector is made. In a review, chat or analysis run, an error from an unknown or unserved embedding model turns RAG off for the rest of the run and logs one warning that says how to fix it. Transient errors (timeouts, connection resets, rate limits, 5xx) skip that lookup, and after three consecutive transient failures a circuit breaker pauses RAG lookups for 60 seconds; afterwards, a single lookup probes to resume lookups once healthy. Lookups that arrive concurrently while no lookup has succeeded wait for the probe's outcome, running concurrently on success and skipping on failure. Later lookups during a pause send no request, so a node that keeps one model loaded does not swap out the review model for the embedding model. `devops ai rag index`, `index-kb`, `query` and `drift --auto-sync`, and `devops ai ingest index-libraries` and `query-library`, exit 1 with the error, and indexing stores no vector for a text the model did not embed. To fix it, serve the model on a backend, point `ai.tasks.embedding` at a backend that serves it, or set `ai.rag.enabled: false`.
---
diff --git a/src/devops_cli/ai/rag/chunker.py b/src/devops_cli/ai/rag/chunker.py
index 32ff71f790..238e31e296 100644
--- a/src/devops_cli/ai/rag/chunker.py
+++ b/src/devops_cli/ai/rag/chunker.py
@@ -13,12 +13,69 @@
from devops_cli.ai.analyze.scanner import detect_language
from devops_cli.ai.rag.metadata import extract_code_metadata, extract_doc_metadata
from devops_cli.ai.rag.models import CodeChunk
+from devops_cli.config.constants import CONST_RAG_MAX_CHUNK_TOKENS
from devops_cli.config.defaults import DEFAULT_RAG_CHUNK_OVERLAP, DEFAULT_RAG_CHUNK_SIZE
logger = logging.getLogger(__name__)
MAX_CHUNK_FILE_SIZE_BYTES = 50 * 1024 * 1024 # 50 MiB safety cap
+
+def estimate_tokens(text: str) -> int:
+ """The project's token estimate (~4 characters per token)."""
+ return max(1, len(text) // 4) if text else 0
+
+
+def _append_sub_window(
+ sub_windows: list[tuple[int, int, str]],
+ start_line: int,
+ end_line: int,
+ content: str,
+ max_chars: int,
+) -> None:
+ """Append bounded sub-window(s) to sub_windows list."""
+ if not content:
+ return
+ if len(content) <= max_chars:
+ sub_windows.append((start_line, end_line, content))
+ else:
+ for piece in [content[i : i + max_chars] for i in range(0, len(content), max_chars)]:
+ sub_windows.append((start_line, end_line, piece))
+
+
+def _split_window_by_token_limit(
+ lines: list[str],
+ window_start_line: int,
+ max_tokens: int = CONST_RAG_MAX_CHUNK_TOKENS,
+) -> list[tuple[int, int, str]]:
+ """Split a window of lines into (start_line, end_line, content) tuples capped at max_tokens."""
+ sub_windows: list[tuple[int, int, str]] = []
+ current_lines: list[str] = []
+ current_chars = 0
+ current_start = window_start_line
+ max_chars = max_tokens * 4
+
+ for offset, line in enumerate(lines):
+ line_chars = len(line) + (1 if current_lines else 0)
+ if current_lines and (current_chars + line_chars > max_chars):
+ content = "\n".join(current_lines).strip()
+ end_line = current_start + len(current_lines) - 1
+ _append_sub_window(sub_windows, current_start, end_line, content, max_chars)
+ current_start = window_start_line + offset
+ current_lines = [line]
+ current_chars = len(line)
+ else:
+ current_lines.append(line)
+ current_chars += line_chars
+
+ if current_lines:
+ content = "\n".join(current_lines).strip()
+ end_line = current_start + len(current_lines) - 1
+ _append_sub_window(sub_windows, current_start, end_line, content, max_chars)
+
+ return sub_windows
+
+
_LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], str]] = {
"go": (
re.compile(
@@ -223,7 +280,10 @@ def chunk_file(
project_name=project_name,
)
- return chunks
+ bounded_chunks: list[CodeChunk] = []
+ for chk in chunks:
+ bounded_chunks.extend(self._split_large_chunk(chk))
+ return bounded_chunks
def _make_code_chunk(
self,
@@ -609,6 +669,64 @@ def _chunk_tech_docs(
return chunks
+ def _create_window_chunk(
+ self,
+ file_path: str,
+ start_line: int,
+ end_line: int,
+ content: str,
+ language: str,
+ category: str,
+ project_name: str,
+ ) -> CodeChunk:
+ """Create a CodeChunk from a line-window or sub-window slice."""
+ c_id = self._generate_id(file_path, start_line, end_line)
+ meta = (
+ extract_doc_metadata(content, file_path=file_path)
+ if category == "docs"
+ else extract_code_metadata(content, language=language, file_path=file_path)
+ )
+ return CodeChunk(
+ id=c_id,
+ file_path=file_path,
+ start_line=start_line,
+ end_line=end_line,
+ content=content,
+ language=language or "text",
+ doc_type="doc" if category == "docs" else "code",
+ category=category,
+ project_name=project_name,
+ symbol_names=[],
+ metadata=meta,
+ content_hash=self._hash_content(content),
+ )
+
+ def _split_large_chunk(self, chunk: CodeChunk) -> list[CodeChunk]:
+ """Split a CodeChunk that exceeds the maximum token limit into sub-chunks."""
+ if estimate_tokens(chunk.content) <= CONST_RAG_MAX_CHUNK_TOKENS:
+ return [chunk]
+ lines = chunk.content.splitlines()
+ sub_windows = _split_window_by_token_limit(
+ lines, chunk.start_line, CONST_RAG_MAX_CHUNK_TOKENS
+ )
+ return [
+ CodeChunk(
+ id=self._generate_id(chunk.file_path, s, e),
+ file_path=chunk.file_path,
+ start_line=s,
+ end_line=e,
+ content=cnt,
+ language=chunk.language,
+ doc_type=chunk.doc_type,
+ category=chunk.category,
+ project_name=chunk.project_name,
+ symbol_names=chunk.symbol_names,
+ metadata=chunk.metadata,
+ content_hash=self._hash_content(cnt),
+ )
+ for s, e, cnt in sub_windows
+ ]
+
def _chunk_line_window(
self,
content: str,
@@ -633,28 +751,27 @@ def _chunk_line_window(
if not chunk_content:
continue
- c_id = self._generate_id(file_path, start + 1, end)
- meta = (
- extract_doc_metadata(chunk_content, file_path=file_path)
- if category == "docs"
- else extract_code_metadata(chunk_content, language=language, file_path=file_path)
- )
- chunks.append(
- CodeChunk(
- id=c_id,
- file_path=file_path,
- start_line=start + 1,
- end_line=end,
- content=chunk_content,
- language=language or "text",
- doc_type="doc" if category == "docs" else "code",
- category=category,
- project_name=project_name,
- symbol_names=[],
- metadata=meta,
- content_hash=self._hash_content(chunk_content),
+ if estimate_tokens(chunk_content) > CONST_RAG_MAX_CHUNK_TOKENS:
+ for sub_start, sub_end, sub_content in _split_window_by_token_limit(
+ chunk_lines, start + 1, CONST_RAG_MAX_CHUNK_TOKENS
+ ):
+ chunks.append(
+ self._create_window_chunk(
+ file_path,
+ sub_start,
+ sub_end,
+ sub_content,
+ language,
+ category,
+ project_name,
+ )
+ )
+ else:
+ chunks.append(
+ self._create_window_chunk(
+ file_path, start + 1, end, chunk_content, language, category, project_name
+ )
)
- )
return chunks
diff --git a/src/devops_cli/ai/rag/embeddings.py b/src/devops_cli/ai/rag/embeddings.py
index a0d2d7eee4..f0d3d78c13 100644
--- a/src/devops_cli/ai/rag/embeddings.py
+++ b/src/devops_cli/ai/rag/embeddings.py
@@ -39,6 +39,7 @@
CONST_ERROR_CODE_EMBEDDINGS,
CONST_EXIT_FAILURE,
CONST_KNOWN_EMBEDDING_DIMENSIONS,
+ CONST_QWEN3_EMBEDDING_QUERY_PREFIX,
CONST_VALKEY_EMBEDDING_PREFIX,
)
from devops_cli.config.defaults import (
@@ -103,9 +104,8 @@ def __init__(self, maxsize: int = DEFAULT_RAG_EMBEDDING_CACHE_SIZE) -> None:
self.misses: int = 0
def _key(self, text: str, model: str, *, is_query: bool = False) -> str:
- """Compute deterministic SHA-256 cache key for (text, model, is_query) tuple."""
- tag = "q" if is_query else "d"
- return hashlib.sha256(f"{model}\x00{tag}\x00{text}".encode()).hexdigest()
+ """Compute deterministic SHA-256 cache key for (model, text) tuple after prompt applied."""
+ return hashlib.sha256(f"{model}\x00{text}".encode()).hexdigest()
def get(self, text: str, model: str, *, is_query: bool = False) -> list[float] | None:
"""Return cached embedding vector or None on miss."""
@@ -162,16 +162,18 @@ def __init__(
self,
message: str,
*,
+ is_transient: bool = False,
exit_code: int = CONST_EXIT_FAILURE,
error_code: str = CONST_ERROR_CODE_EMBEDDINGS,
details: dict[str, Any] | None = None,
) -> None:
+ self.is_transient = is_transient
DevOpsCLIError.__init__(
self,
message,
exit_code=exit_code,
error_code=error_code,
- details=details or {},
+ details=details,
)
@@ -206,10 +208,12 @@ def _reply_vectors(
"""One embedding reply's vectors; EmbeddingsError naming the endpoint for any other reply."""
if res.status_code != 200:
body = " ".join(res.text.split())[:CONST_EMBEDDING_REPLY_EXCERPT_CHARS]
+ is_transient = res.status_code in (408, 429) or res.status_code >= 500
raise EmbeddingsError(
ERRORS.rag.embedding_endpoint_status.format(
endpoint=endpoint, status=res.status_code, body=body
),
+ is_transient=is_transient,
details={"endpoint": endpoint, "status": res.status_code},
)
vectors = _parsed_vectors(res, parse)
@@ -218,6 +222,7 @@ def _reply_vectors(
ERRORS.rag.embedding_endpoint_malformed.format(
endpoint=endpoint, received=len(vectors), expected=expected
),
+ is_transient=False,
details={"endpoint": endpoint, "received": len(vectors), "expected": expected},
)
return vectors
@@ -233,6 +238,8 @@ def _endpoint_failure(endpoint: str, exc: Exception) -> str:
def _is_transient_embedding_error(exc: Exception) -> bool:
"""Check if an exception is a transient network, timeout, or connection reset error."""
+ if isinstance(exc, EmbeddingsError):
+ return exc.is_transient
if isinstance(exc, (httpx2.NetworkError, httpx2.TimeoutException)):
return True
if isinstance(
@@ -290,6 +297,28 @@ def _probe_ollama_show_dimension(client: httpx2.Client, base_url: str, model: st
return None
+def _apply_model_prefix(text: str, model: str, *, is_query: bool = False) -> str:
+ """Apply asymmetric task prompt prefix based on embedding model family."""
+ m = model.lower().split(":")[0].strip()
+ if m.startswith("bge-m3"):
+ return text
+ if m.startswith("qwen3-embedding") or "qwen3-embedding" in m:
+ if not is_query:
+ return text
+ if text.startswith(CONST_QWEN3_EMBEDDING_QUERY_PREFIX):
+ return text
+ return f"{CONST_QWEN3_EMBEDDING_QUERY_PREFIX} {text}"
+ if "nomic" in m:
+ prefix = "search_query: " if is_query else "search_document: "
+ return (
+ text if text.startswith(("search_query: ", "search_document: ")) else f"{prefix}{text}"
+ )
+ if "e5" in m:
+ prefix = "query: " if is_query else "passage: "
+ return text if text.startswith(("query: ", "passage: ")) else f"{prefix}{text}"
+ return text
+
+
class EmbeddingsEngine:
"""Generates dense vector embeddings using Ollama or OpenAI endpoints."""
@@ -466,9 +495,9 @@ def _record_batch_latency(self, elapsed: float) -> None:
self._apply_aimd_increase()
def _valkey_key(self, text: str, model: str, *, is_query: bool = False) -> str:
- """Generate namespaced deterministic Valkey cache key with query/doc isolation."""
- tag = "q" if is_query else "d"
- h = hashlib.sha256(f"{model}\x00{tag}\x00{text}".encode()).hexdigest()
+ """Generate namespaced deterministic Valkey cache key; hashes text after prompt is applied."""
+ sent_text = self._apply_model_prefix([text], is_query=is_query)[0]
+ h = hashlib.sha256(f"{model}\x00{sent_text}".encode()).hexdigest()
return f"{CONST_VALKEY_EMBEDDING_PREFIX}:{h}"
def _get_valkey_embedding(
@@ -674,11 +703,14 @@ def _dispatch_embed(self, prefixed_miss: list[str]) -> list[list[float]]:
details={"model": self.model, "provider": self.ai_config.provider},
)
- def _embedding_error(self, failures: list[str], *, model: str | None = None) -> EmbeddingsError:
+ def _embedding_error(
+ self, failures: list[str], *, model: str | None = None, is_transient: bool = False
+ ) -> EmbeddingsError:
"""The EmbeddingsError for a request no endpoint answered with embeddings."""
name = model or self.model
return EmbeddingsError(
ERRORS.rag.embedding_failed.format(model=name, failures="; ".join(failures)),
+ is_transient=is_transient,
details={"model": name, "provider": self.ai_config.provider, "failures": failures},
)
@@ -698,16 +730,16 @@ def embed_texts(self, texts: list[str], *, is_query: bool = False) -> list[list[
):
from devops_cli.telemetry import record_metric
+ prefixed_texts = self._apply_model_prefix(texts, is_query=is_query)
cached, miss_indices, miss_texts = self._partition_with_valkey_l2(
- texts, is_query=is_query
+ prefixed_texts, is_query=is_query
)
record_metric("devops_cli_embedding_cache_hits_total", len(cached), unit="1")
record_metric("devops_cli_embedding_cache_misses_total", len(miss_texts), unit="1")
record_metric("devops_cli_embedding_cache_size", self._cache.size, unit="1")
if miss_texts:
- prefixed_miss = self._apply_model_prefix(miss_texts, is_query=is_query)
- fresh = self._dispatch_embed(prefixed_miss)
+ fresh = self._dispatch_embed(miss_texts)
if len(fresh) != len(miss_texts):
raise EmbeddingsError(
f"Embedding provider returned {len(fresh)} vectors for {len(miss_texts)} texts",
@@ -729,34 +761,21 @@ def _populate_fresh_embeddings(
is_query: bool = False,
) -> None:
"""Store fresh embeddings into in-memory L1 and Valkey L2."""
- for miss_idx, original_text, vector in zip(miss_indices, miss_texts, fresh, strict=True):
- self._cache.put(original_text, self.model, vector, is_query=is_query)
- self._set_valkey_embedding(original_text, self.model, vector, is_query=is_query)
+ for miss_idx, sent_text, vector in zip(miss_indices, miss_texts, fresh, strict=True):
+ self._cache.put(sent_text, self.model, vector, is_query=is_query)
+ self._set_valkey_embedding(sent_text, self.model, vector, is_query=is_query)
cached[miss_idx] = vector
def embed_query(self, text: str) -> list[float]:
"""Generate vector embedding for a single search query with LRU cache acceleration."""
- hit = self._cache.get(text, self.model, is_query=True)
- if hit is not None:
- return hit
results = self.embed_texts([text], is_query=True)
if not results:
raise EmbeddingsError(f"Failed to generate embedding for query: {text[:50]}")
return results[0]
- def _apply_model_prefix(self, texts: list[str], *, is_query: bool) -> list[str]:
+ def _apply_model_prefix(self, texts: list[str], *, is_query: bool = False) -> list[str]:
"""Apply asymmetric task prefix based on embedding model architecture."""
- m = self.model.lower()
- if "nomic" in m:
- prefix = "search_query: " if is_query else "search_document: "
- return [
- t if t.startswith(("search_query: ", "search_document: ")) else f"{prefix}{t}"
- for t in texts
- ]
- elif "qwen" in m or "bge" in m or "e5" in m:
- prefix = "query: " if is_query else "passage: "
- return [t if t.startswith(("query: ", "passage: ")) else f"{prefix}{t}" for t in texts]
- return texts
+ return [_apply_model_prefix(t, self.model, is_query=is_query) for t in texts]
def _query_ollama_node_batch(self, base_url: str, batch_texts: list[str]) -> list[list[float]]:
"""Embed a batch on one Ollama node; raise when the node refuses, fails or misanswers."""
@@ -799,13 +818,16 @@ def _try_query_candidate_nodes(
) -> list[list[float]]:
"""Embed a batch on the first node that answers; raise naming each node's failure."""
failures: list[str] = []
+ is_transient_flags: list[bool] = []
for attempt, base_url in enumerate(urls):
try:
return self._try_single_candidate(base_url, batch_texts, attempt)
except Exception as exc:
logger.debug("Ollama embedding on %s failed: %s", base_url, exc)
failures.append(_endpoint_failure(_ollama_embed_endpoint(base_url), exc))
- raise self._embedding_error(failures)
+ is_transient_flags.append(_is_transient_embedding_error(exc))
+ all_transient = bool(is_transient_flags and all(is_transient_flags))
+ raise self._embedding_error(failures, is_transient=all_transient)
def _embed_batch_with_subdivision(
self, urls: list[str], batch_texts: list[str]
@@ -985,7 +1007,10 @@ def _embed_openai(self, texts: list[str]) -> list[list[float]]:
endpoint, headers, model, batches, is_gateway
)
except (DevOpsCLIError, httpx2.HTTPError) as exc:
- raise self._embedding_error([_endpoint_failure(endpoint, exc)], model=model) from exc
+ is_transient = _is_transient_embedding_error(exc)
+ raise self._embedding_error(
+ [_endpoint_failure(endpoint, exc)], model=model, is_transient=is_transient
+ ) from exc
if embs:
self._record_dimension(len(embs[0]))
return embs
diff --git a/src/devops_cli/ai/rag/indexer.py b/src/devops_cli/ai/rag/indexer.py
index e33478987f..e88498114a 100644
--- a/src/devops_cli/ai/rag/indexer.py
+++ b/src/devops_cli/ai/rag/indexer.py
@@ -11,10 +11,14 @@
from typing import Any
from devops_cli.ai.rag.chunker import SemanticChunker
-from devops_cli.ai.rag.embeddings import EmbeddingsEngine
+from devops_cli.ai.rag.embeddings import EmbeddingsEngine, EmbeddingsError
from devops_cli.ai.rag.models import CodeChunk, IndexStats
from devops_cli.ai.rag.qdrant import QdrantClient
-from devops_cli.config.constants import CONST_INDEX_CACHE_FILENAME
+from devops_cli.config.constants import (
+ CONST_EXIT_FAILURE,
+ CONST_INDEX_CACHE_FILENAME,
+ CONST_RAG_SKIPPED_LOCKFILES,
+)
from devops_cli.config.defaults import (
DEFAULT_MAX_AST_FILE_SIZE_BYTES,
DEFAULT_RAG_CACHE_DIR,
@@ -24,6 +28,7 @@
DEFAULT_RAG_DOCS_COLLECTION,
)
from devops_cli.core.repo import is_ignored_by_git
+from devops_cli.lang.en.errors import ERRORS
from devops_cli.telemetry import record_metric, trace_span
logger = logging.getLogger(__name__)
@@ -81,7 +86,20 @@ def _load_gitignore_spec(root: Path) -> Any:
return None
-def _is_indexable_file(p: Path, root: Path, *, gitignore_spec: Any = None) -> bool: # noqa: C901
+def _is_hidden_file_path(p: Path, root: Path) -> bool:
+ """Return True if path is a hidden file or inside a hidden directory."""
+ rel_parts = p.relative_to(root).parts if p.is_relative_to(root) else p.parts
+ if any(part.startswith(".") for part in rel_parts[:-1]):
+ return True
+ return p.name.startswith(".") and not p.name.endswith((".yaml", ".yml", ".json", ".toml"))
+
+
+def _is_lockfile(p: Path) -> bool:
+ """Determine if a file is a package manager lockfile or dependency checksum."""
+ return p.name.endswith(".lock") or p.name in CONST_RAG_SKIPPED_LOCKFILES
+
+
+def _is_indexable_file(p: Path, root: Path, *, gitignore_spec: Any = None) -> bool:
"""Determine if a path is an indexable code/doc file under root."""
if not p.is_file() or p.is_symlink():
return False
@@ -91,10 +109,7 @@ def _is_indexable_file(p: Path, root: Path, *, gitignore_spec: Any = None) -> bo
return False
except OSError:
return False
- rel_parts = p.relative_to(root).parts if p.is_relative_to(root) else p.parts
- if any(part.startswith(".") for part in rel_parts[:-1]):
- return False
- if p.name.startswith(".") and not p.name.endswith((".yaml", ".yml", ".json", ".toml")):
+ if _is_lockfile(p) or _is_hidden_file_path(p, root):
return False
if gitignore_spec is not None:
rel = str(p.relative_to(root)) if p.is_relative_to(root) else p.name
@@ -677,7 +692,24 @@ def _upsert_chunks(
},
):
texts = [c.content for c in batch]
- embeddings = self.embedder.embed_texts(texts)
+ try:
+ embeddings = self.embedder.embed_texts(texts)
+ except Exception as exc:
+ first_file = batch[0].file_path
+ last_file = batch[-1].file_path
+ det = dict(getattr(exc, "details", {}) or {})
+ det.setdefault("model", getattr(self.embedder, "model", ""))
+ det["first_file"] = first_file
+ det["last_file"] = last_file
+ raise EmbeddingsError(
+ ERRORS.rag.batch_failed.format(
+ first_file=first_file,
+ last_file=last_file,
+ error=str(exc),
+ ),
+ exit_code=CONST_EXIT_FAILURE,
+ details=det,
+ ) from exc
points = [
_build_chunk_point(chunk, vec)
for chunk, vec in zip(batch, embeddings, strict=False)
diff --git a/src/devops_cli/ai/rag/investigator.py b/src/devops_cli/ai/rag/investigator.py
index e27cb7e521..1d1a758d64 100644
--- a/src/devops_cli/ai/rag/investigator.py
+++ b/src/devops_cli/ai/rag/investigator.py
@@ -6,6 +6,7 @@
import logging
import threading
import time
+from collections.abc import Callable
from typing import Any
from devops_cli.ai.rag.embeddings import EmbeddingsEngine, EmbeddingsError
@@ -13,6 +14,10 @@
from devops_cli.ai.rag.qdrant import QdrantClient
from devops_cli.ai.rag.retriever import SemanticRetriever
from devops_cli.config import settings as settings_mod
+from devops_cli.config.constants import (
+ CONST_RAG_CIRCUIT_BREAKER_FAILURES,
+ CONST_RAG_CIRCUIT_BREAKER_PAUSE_SECONDS,
+)
from devops_cli.config.defaults import (
DEFAULT_RAG_COLLECTION,
DEFAULT_RAG_DOCS_COLLECTION,
@@ -31,31 +36,129 @@
_INVESTIGATION_CACHE: dict[str, tuple[float, RAGContext | None]] = {}
_RETRIEVER_CACHE: tuple[float, SemanticRetriever] | None = None
_CACHE_TTL_SECONDS = 60.0
+_CIRCUIT_BREAKER_FAILURES = CONST_RAG_CIRCUIT_BREAKER_FAILURES
+_CIRCUIT_BREAKER_PAUSE_SECONDS = CONST_RAG_CIRCUIT_BREAKER_PAUSE_SECONDS
-# Set by the first lookup the embedding model cannot embed. Each later lookup would send the
-# same failing request, and on a node that keeps one model loaded it can evict the model the
-# run is using, so RAG stays off for the rest of the process.
+# Set by the first permanent error (unserved/unknown model).
_RAG_STOPPED = threading.Event()
_STOP_LOCK = threading.Lock()
-# Set by the first lookup the embedding model answers. Until then lookups embed one at a time
-# under _PROBE_LOCK, so review workers that start together send one request to a model that
-# is not served, not one each before the first failure stops RAG.
+_RETRIEVER_LOCK = threading.Lock()
+# Set by the first lookup the embedding model answers.
_RAG_SERVED = threading.Event()
-_PROBE_LOCK = threading.Lock()
-# Set by the first lookup that fails for any other reason, such as a vector store the SSRF guard
-# refuses. That one warns, so a RAG backend that cannot be reached is not silent; later failures
-# log at debug, as each review worker's lookup would repeat the warning.
+# Set by the first lookup that fails for any non-embedding reason.
_FAILURE_REPORTED = threading.Event()
+# Circuit breaker state for transient failures
+_circuit_breaker_opened_at: float | None = None
+_consecutive_transient_failures: int = 0
+_STATE_LOCK = threading.Lock()
+
+
+class _ProbeCoordinator:
+ """Coordinates a single probe lookup while concurrent lookups wait for its outcome."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._event: threading.Event | None = None
+ self._succeeded: bool = False
+
+ def clear(self) -> None:
+ with self._lock:
+ if self._event is not None:
+ self._event.set()
+ self._event = None
+ self._succeeded = False
+
+ def coordinate(self, search_fn: Callable[[], RAGContext | None]) -> RAGContext | None:
+ with self._lock:
+ if self._event is not None:
+ event = self._event
+ is_prober = False
+ else:
+ self._event = threading.Event()
+ self._succeeded = False
+ event = self._event
+ is_prober = True
+
+ if not is_prober:
+ event.wait()
+ return search_fn() if self._succeeded else None
+
+ success = False
+ try:
+ ctx = search_fn()
+ success = ctx is not None
+ return ctx
+ finally:
+ with self._lock:
+ self._succeeded = success
+ self._event = None
+ event.set()
+
+
+_PROBE_COORDINATOR = _ProbeCoordinator()
+
+
+def _record_success() -> None:
+ """Reset transient failure accounting and mark RAG as served."""
+ global _consecutive_transient_failures, _circuit_breaker_opened_at
+ with _STATE_LOCK:
+ _consecutive_transient_failures = 0
+ _circuit_breaker_opened_at = None
+ _RAG_SERVED.set()
+
+
+def _record_transient_failure(exc: Exception) -> None:
+ """Record a transient failure; opens circuit breaker after consecutive threshold."""
+ global _consecutive_transient_failures, _circuit_breaker_opened_at
+ with _STATE_LOCK:
+ _consecutive_transient_failures += 1
+ if _consecutive_transient_failures >= _CIRCUIT_BREAKER_FAILURES:
+ _circuit_breaker_opened_at = time.monotonic()
+ err_msg = getattr(exc, "message", str(exc))
+ logger.warning(
+ MESSAGES.rag.paused.format(
+ seconds=int(_CIRCUIT_BREAKER_PAUSE_SECONDS),
+ failures=_CIRCUIT_BREAKER_FAILURES,
+ error=err_msg,
+ )
+ )
+
+
+def _is_breaker_active(now: float) -> bool:
+ """Check if the circuit breaker is currently open and pausing lookups."""
+ with _STATE_LOCK:
+ if _circuit_breaker_opened_at is None:
+ return False
+ return (now - _circuit_breaker_opened_at) < _CIRCUIT_BREAKER_PAUSE_SECONDS
+
+
+def _is_probe_required(now: float) -> bool:
+ """Check if a single probe lookup is required."""
+ with _STATE_LOCK:
+ if not _RAG_SERVED.is_set():
+ return True
+ if _circuit_breaker_opened_at is not None:
+ return (now - _circuit_breaker_opened_at) >= _CIRCUIT_BREAKER_PAUSE_SECONDS
+ return False
+
def clear_investigation_cache() -> None:
"""Clear in-memory RAG investigation and retriever caches, and lift a run-wide RAG stop."""
- global _RETRIEVER_CACHE, _INVESTIGATION_CACHE
+ global \
+ _RETRIEVER_CACHE, \
+ _INVESTIGATION_CACHE, \
+ _circuit_breaker_opened_at, \
+ _consecutive_transient_failures
_RETRIEVER_CACHE = None
_INVESTIGATION_CACHE.clear()
_RAG_STOPPED.clear()
_RAG_SERVED.clear()
_FAILURE_REPORTED.clear()
+ with _STATE_LOCK:
+ _circuit_breaker_opened_at = None
+ _consecutive_transient_failures = 0
+ _PROBE_COORDINATOR.clear()
def _stop_rag_for_run(model: str, exc: EmbeddingsError) -> None:
@@ -79,45 +182,73 @@ def _report_lookup_failure(exc: Exception) -> None:
logger.debug("RAG investigation skipped due to error: %s", redact_text(str(exc))[:256])
+def _cached_retriever_if_valid(now: float) -> SemanticRetriever | None:
+ """Return cached retriever if within TTL and healthy, else None."""
+ if _RETRIEVER_CACHE is not None:
+ last_t, retriever = _RETRIEVER_CACHE
+ if now - last_t < _CACHE_TTL_SECONDS and retriever.qdrant.is_alive():
+ return retriever
+ return None
+
+
def _get_or_create_retriever(
st: Settings, top_k: int | None, score_threshold: float | None
) -> SemanticRetriever | None:
"""Get or create cached SemanticRetriever instance."""
global _RETRIEVER_CACHE
now = time.monotonic()
- if _RETRIEVER_CACHE is not None:
- last_t, retriever = _RETRIEVER_CACHE
- if now - last_t < _CACHE_TTL_SECONDS and retriever.qdrant.is_alive():
- return retriever
+ valid = _cached_retriever_if_valid(now)
+ if valid is not None:
+ return valid
+
+ with _RETRIEVER_LOCK:
+ valid = _cached_retriever_if_valid(now)
+ if valid is not None:
+ return valid
+
+ qdrant_url = st.qdrant.url or "http://localhost:6333"
+ qdrant = QdrantClient(
+ base_url=qdrant_url,
+ api_key=settings_mod.get_qdrant_api_key(st),
+ allow_private_network=st.ai.allow_private_network,
+ timeout=st.qdrant.timeout,
+ )
+ if not qdrant.is_alive():
+ logger.debug(
+ "Qdrant vector store unreachable at %s, skipping RAG investigation", qdrant_url
+ )
+ return None
- qdrant_url = st.qdrant.url or "http://localhost:6333"
- qdrant = QdrantClient(
- base_url=qdrant_url,
- api_key=settings_mod.get_qdrant_api_key(st),
- allow_private_network=st.ai.allow_private_network,
- timeout=st.qdrant.timeout,
- )
- if not qdrant.is_alive():
- logger.debug(
- "Qdrant vector store unreachable at %s, skipping RAG investigation", qdrant_url
+ embedder = EmbeddingsEngine(ai_config=st.ai, api_key=settings_mod.get_ai_api_key(st))
+ prefix = st.qdrant.collection_prefix or "devops"
+ code_coll = f"{prefix}_code" if prefix else DEFAULT_RAG_COLLECTION
+ docs_coll = f"{prefix}_docs" if prefix else DEFAULT_RAG_DOCS_COLLECTION
+
+ cfg_rag = getattr(st.ai, "rag", None)
+ cfg_top_k = getattr(cfg_rag, "top_k", None) if cfg_rag else None
+ cfg_threshold = getattr(cfg_rag, "score_threshold", None) if cfg_rag else None
+
+ eff_top_k = (
+ top_k
+ if top_k is not None
+ else (cfg_top_k if cfg_top_k is not None else DEFAULT_RAG_TOP_K)
+ )
+ eff_threshold = (
+ score_threshold
+ if score_threshold is not None
+ else (cfg_threshold if cfg_threshold is not None else DEFAULT_RAG_SCORE_THRESHOLD)
)
- return None
- embedder = EmbeddingsEngine(ai_config=st.ai, api_key=settings_mod.get_ai_api_key(st))
- prefix = st.qdrant.collection_prefix or "devops"
- code_coll = f"{prefix}_code" if prefix else DEFAULT_RAG_COLLECTION
- docs_coll = f"{prefix}_docs" if prefix else DEFAULT_RAG_DOCS_COLLECTION
-
- retriever = SemanticRetriever(
- qdrant=qdrant,
- embedder=embedder,
- code_collection=code_coll,
- docs_collection=docs_coll,
- default_top_k=top_k or DEFAULT_RAG_TOP_K,
- default_score_threshold=score_threshold or DEFAULT_RAG_SCORE_THRESHOLD,
- )
- _RETRIEVER_CACHE = (now, retriever)
- return retriever
+ retriever = SemanticRetriever(
+ qdrant=qdrant,
+ embedder=embedder,
+ code_collection=code_coll,
+ docs_collection=docs_coll,
+ default_top_k=eff_top_k,
+ default_score_threshold=eff_threshold,
+ )
+ _RETRIEVER_CACHE = (now, retriever)
+ return retriever
def _retrieve(
@@ -133,11 +264,11 @@ def _retrieve(
file_filter: str | None,
max_chars: int,
) -> RAGContext | None:
- """Retrieve context for the query; None when the store is unreachable or RAG is off.
+ """Retrieve context for the query; None when the store is unreachable, stopped or paused."""
+ now = time.monotonic()
+ if _RAG_STOPPED.is_set() or _is_breaker_active(now):
+ return None
- Until the embedding model has answered a lookup, lookups take turns, so a model that is
- not served gets one request between them.
- """
retriever = _get_or_create_retriever(st, top_k, score_threshold)
if retriever is None:
return None
@@ -154,15 +285,9 @@ def _retrieve(
file_filter=file_filter,
max_chars=max_chars,
)
- if _RAG_SERVED.is_set():
+ if not _is_probe_required(now):
return search()
- with _PROBE_LOCK:
- if not _RAG_SERVED.is_set():
- ctx = search()
- if ctx is not None:
- _RAG_SERVED.set()
- return ctx
- return search()
+ return _PROBE_COORDINATOR.coordinate(search)
def _search(
@@ -178,12 +303,12 @@ def _search(
file_filter: str | None,
max_chars: int,
) -> RAGContext | None:
- """Search for the query's context; None when RAG is off or this lookup turns it off."""
+ """Search for the query's context; None when RAG is off, paused, or fails."""
if _RAG_STOPPED.is_set():
return None
try:
if persona:
- return retriever.retrieve_context_for_persona(
+ ctx = retriever.retrieve_context_for_persona(
search_query,
persona=persona,
top_k=top_k,
@@ -191,18 +316,28 @@ def _search(
project=project,
language=language,
)
- return retriever.retrieve_context(
- search_query,
- top_k=top_k,
- score_threshold=score_threshold,
- project=project,
- language=language,
- category=category,
- file_filter=file_filter,
- max_chars=max_chars,
- )
+ else:
+ ctx = retriever.retrieve_context(
+ search_query,
+ top_k=top_k,
+ score_threshold=score_threshold,
+ project=project,
+ language=language,
+ category=category,
+ file_filter=file_filter,
+ max_chars=max_chars,
+ )
+ if ctx is not None:
+ _record_success()
+ return ctx
except EmbeddingsError as exc:
- _stop_rag_for_run(retriever.embedder.model, exc)
+ if not exc.is_transient:
+ _stop_rag_for_run(retriever.embedder.model, exc)
+ else:
+ _record_transient_failure(exc)
+ return None
+ except Exception as exc:
+ _record_transient_failure(exc)
return None
@@ -255,19 +390,20 @@ def investigate_rag_context(
) -> RAGContext | None:
"""Execute a safe, non-blocking RAG investigation step to retrieve relevant context.
- The first lookup whose query the embedding model cannot embed turns RAG off for the rest
- of the process and logs one warning naming the model, the error and the fix. Later calls
- return None without building a retriever or sending a request, until
- `clear_investigation_cache` lifts the stop. Until the model has answered a lookup, lookups
- that run at once, such as the review workers' per-file lookups, embed one at a time, so a
- model that is not served gets one request between them.
+ A permanent error from an unknown or unserved embedding model turns RAG off for the rest of
+ the process and logs one warning naming the model, the error and the fix. Transient errors
+ (timeouts, connection resets, rate limits, 5xx) skip that lookup. After three consecutive
+ transient failures, a circuit breaker pauses RAG lookups for 60 seconds; afterwards, a single
+ lookup probes to resume lookups once healthy. Lookups that arrive concurrently while no lookup
+ has succeeded wait for the probe's outcome, running concurrently on success and skipping on
+ failure.
Returns:
RAGContext if the vector store is available and matching chunks are retrieved;
- None if RAG is disabled or stopped, unreachable, or yields zero relevant results.
+ None if RAG is disabled, stopped, paused, unreachable, or yields zero relevant results.
"""
clean_query = query.strip()
- if not clean_query or _RAG_STOPPED.is_set():
+ if not clean_query or _RAG_STOPPED.is_set() or _is_breaker_active(time.monotonic()):
return None
st = settings or settings_mod.load_settings()
diff --git a/src/devops_cli/commands/ai.py b/src/devops_cli/commands/ai.py
index 1ce0377325..50a1a9cd03 100644
--- a/src/devops_cli/commands/ai.py
+++ b/src/devops_cli/commands/ai.py
@@ -45,7 +45,6 @@
DEFAULT_AI_TEST_PROMPT,
DEFAULT_DIFF_CHUNK_BUDGET,
DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS,
- DEFAULT_RAG_TOP_K,
DEFAULT_SUBPROCESS_TIMEOUT_SECONDS,
DEFAULT_TIKTOKEN_MODEL,
)
@@ -194,7 +193,7 @@ def _try_retrieve_rag_context(
persona: str | None = None,
category: str | None = None,
project: str | None = None,
- top_k: int = DEFAULT_RAG_TOP_K,
+ top_k: int | None = None,
) -> str | None:
"""Attempt to retrieve relevant semantic context from RAG vector store."""
try:
@@ -1111,7 +1110,7 @@ def chat( # noqa: C901
effective_prompt = user_input
if rag:
- rag_snippet = _try_retrieve_rag_context(user_input, persona=persona, top_k=3)
+ rag_snippet = _try_retrieve_rag_context(user_input, persona=persona)
if rag_snippet:
effective_prompt = f"{rag_snippet}\n\nUser Question: {user_input}"
diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py
index 739780be60..58ce55b359 100644
--- a/src/devops_cli/config/constants.py
+++ b/src/devops_cli/config/constants.py
@@ -2135,10 +2135,29 @@
"text-embedding-3-large": 3072,
"text-embedding-ada-002": 1536,
"all-minilm": 384,
- "qwen3-embedding": 768,
+ "qwen3-embedding": 1024,
"embeddinggemma": 768,
}
+# Asymmetric task prefix for Qwen3-Embedding queries
+CONST_QWEN3_EMBEDDING_QUERY_PREFIX: Final[str] = (
+ "Instruct: Given a code search query, retrieve relevant code or documentation\nQuery:"
+)
+
+# Known lockfile basenames skipped by RAG indexer
+CONST_RAG_SKIPPED_LOCKFILES: Final[frozenset[str]] = frozenset(
+ {"package-lock.json", "pnpm-lock.yaml", "go.sum"}
+)
+
+# Safety limit for maximum chunk size in estimated tokens sent to embedding models
+CONST_RAG_MAX_CHUNK_TOKENS: Final[int] = 8192
+
+# Consecutive transient embedding failures before pausing RAG lookups
+CONST_RAG_CIRCUIT_BREAKER_FAILURES: Final[int] = 3
+
+# Duration in seconds to pause RAG lookups when circuit breaker opens
+CONST_RAG_CIRCUIT_BREAKER_PAUSE_SECONDS: Final[float] = 60.0
+
# Helm releases that deploy DaemonSets across all cluster nodes
CONST_HELM_DAEMONSET_RELEASES: Final[frozenset[str]] = frozenset(
{"k8s-monitoring", "dcgm-exporter"}
diff --git a/src/devops_cli/lang/en/errors.py b/src/devops_cli/lang/en/errors.py
index e8e92ccdfe..f93b61199b 100644
--- a/src/devops_cli/lang/en/errors.py
+++ b/src/devops_cli/lang/en/errors.py
@@ -249,6 +249,7 @@ class RAGErrorMessages:
"is not ollama, openai, copilot or gateway, and no Ollama URLs are set. "
"Set ai.tasks.embedding.provider"
)
+ batch_failed: str = "Failed to embed batch from '{first_file}' to '{last_file}': {error}"
@dataclass(frozen=True)
diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py
index e29db32e31..496680441e 100644
--- a/src/devops_cli/lang/en/messages.py
+++ b/src/devops_cli/lang/en/messages.py
@@ -723,6 +723,7 @@ class RAGMessages:
"RAG lookup failed, so prompts go on without retrieved context: {error}. Later failures "
"this run are logged at debug level."
)
+ paused: str = "RAG lookups paused for {seconds}s after {failures} failures: {error}."
@dataclass(frozen=True)
diff --git a/tests/test_rag_chunker.py b/tests/test_rag_chunker.py
index 9589e933cc..eb5a8fa052 100644
--- a/tests/test_rag_chunker.py
+++ b/tests/test_rag_chunker.py
@@ -114,3 +114,19 @@ def test_chunk_file_defensive_boundaries(tmp_path: Path) -> None:
chunks_oversized = chunker.chunk_file(mock_large, relative_to=inside_dir)
assert (chunks_traversal, chunks_symlink, chunks_oversized) == ([], [], [])
+
+
+def test_chunk_synthetic_file_bounds_tokens(tmp_path: Path) -> None:
+ """A 4,000-line synthetic file is chunked so that every chunk is <= 8,192 tokens."""
+ from devops_cli.ai.rag.chunker import estimate_tokens
+ from devops_cli.config.constants import CONST_RAG_MAX_CHUNK_TOKENS
+
+ lines = [f"line_{i} = 'some payload text content that spans lines'\n" for i in range(4000)]
+ synthetic_file = tmp_path / "synthetic_large.py"
+ synthetic_file.write_text("".join(lines), encoding="utf-8")
+
+ chunker = SemanticChunker()
+ chunks = chunker.chunk_file(synthetic_file, relative_to=tmp_path)
+
+ assert len(chunks) > 0
+ assert all(estimate_tokens(c.content) <= CONST_RAG_MAX_CHUNK_TOKENS for c in chunks)
diff --git a/tests/test_rag_embeddings.py b/tests/test_rag_embeddings.py
index b56ac53ab1..37915f5104 100644
--- a/tests/test_rag_embeddings.py
+++ b/tests/test_rag_embeddings.py
@@ -890,3 +890,76 @@ def mock_post(_client: Any, url: str, **kwargs: Any) -> httpx2.Response:
engine.embed_texts(["bad request"])
assert attempts == 1
+
+
+def test_qwen3_embedding_dimension_pinned() -> None:
+ """CONST_KNOWN_EMBEDDING_DIMENSIONS["qwen3-embedding"] is pinned to 1024."""
+ from devops_cli.config.constants import CONST_KNOWN_EMBEDDING_DIMENSIONS
+
+ assert CONST_KNOWN_EMBEDDING_DIMENSIONS.get("qwen3-embedding") == 1024
+
+
+@pytest.mark.parametrize(
+ ("model", "text", "is_query", "expected"),
+ [
+ ("bge-m3", "def search():", False, "def search():"),
+ ("bge-m3", "def search():", True, "def search():"),
+ (
+ "qwen3-embedding",
+ "search query",
+ True,
+ "Instruct: Given a code search query, retrieve relevant code or documentation\nQuery: search query",
+ ),
+ ("qwen3-embedding", "doc content", False, "doc content"),
+ ("nomic-embed-text", "search query", True, "search_query: search query"),
+ ("nomic-embed-text", "doc content", False, "search_document: doc content"),
+ ("e5-base", "search query", True, "query: search query"),
+ ("e5-base", "doc content", False, "passage: doc content"),
+ ("other-model", "search query", True, "search query"),
+ ("other-model", "doc content", False, "doc content"),
+ ],
+)
+def test_apply_model_prefix_families(model: str, text: str, is_query: bool, expected: str) -> None:
+ """Per-model prompt prefixes for bge-m3, qwen3, nomic, e5, and others."""
+ from devops_cli.ai.rag.embeddings import _apply_model_prefix
+
+ assert _apply_model_prefix(text, model, is_query=is_query) == expected
+
+
+def test_embedding_cache_keys_hash_prompted_text(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The L1 and Valkey keys hash the text after its prompt is applied; same text under two prompts gives two misses."""
+ mock_valkey = _MockValkey()
+ ai_cfg = AIConfig(provider="custom", ollama_urls=[])
+ ai_cfg.tasks.embedding.model = "qwen3-embedding"
+ engine = EmbeddingsEngine(ai_cfg, valkey_client=mock_valkey)
+
+ call_count = 0
+
+ def fake_dispatch(texts: list[str]) -> list[list[float]]:
+ nonlocal call_count
+ call_count += len(texts)
+ return [[0.1] * 1024 for _ in texts]
+
+ monkeypatch.setattr(engine, "_dispatch_embed", fake_dispatch)
+
+ doc_vec = engine.embed_texts(["common content"])
+ assert call_count == 1
+ assert (engine._cache.hits, engine._cache.misses) == (0, 1)
+
+ query_vec = engine.embed_query("common content")
+ assert (call_count, engine._cache.hits, engine._cache.misses) == (2, 0, 2)
+ assert doc_vec[0] == query_vec
+
+
+def test_embeddings_429_no_deployments_is_transient() -> None:
+ """A 429 'No deployments available' counts as transient."""
+ from devops_cli.ai.rag.embeddings import EmbeddingsError, _reply_vectors
+
+ res = httpx2.Response(
+ 429,
+ text="No deployments available",
+ request=httpx2.Request("POST", "http://example.com/api/embed"),
+ )
+ with pytest.raises(EmbeddingsError) as exc_info:
+ _reply_vectors(res, "http://example.com/api/embed", 1, lambda b: b)
+ assert exc_info.value.is_transient is True
diff --git a/tests/test_rag_indexer_retriever.py b/tests/test_rag_indexer_retriever.py
index 5784185586..ab1925afdd 100644
--- a/tests/test_rag_indexer_retriever.py
+++ b/tests/test_rag_indexer_retriever.py
@@ -273,3 +273,86 @@ def test_indexing_text_the_model_cannot_embed_raises_and_stores_nothing(tmp_path
[point for points in qdrant.collections.values() for point in points],
indexer._load_cache(),
) == (engine.model, [], {})
+
+
+def test_indexer_skips_lockfiles(tmp_path: Path) -> None:
+ """The indexer skips uv.lock, other *.lock files, package-lock.json, pnpm-lock.yaml and go.sum."""
+ from devops_cli.ai.rag.indexer import _is_indexable_file
+
+ lockfiles = [
+ tmp_path / "uv.lock",
+ tmp_path / "Cargo.lock",
+ tmp_path / "poetry.lock",
+ tmp_path / "package-lock.json",
+ tmp_path / "pnpm-lock.yaml",
+ tmp_path / "go.sum",
+ ]
+ for lf in lockfiles:
+ lf.write_text("lock content", encoding="utf-8")
+ assert _is_indexable_file(lf, tmp_path) is False
+
+ valid_file = tmp_path / "regular.py"
+ valid_file.write_text("print('hello')", encoding="utf-8")
+ assert _is_indexable_file(valid_file, tmp_path) is True
+
+
+def test_failed_second_batch_ends_with_exit_1_and_preserves_first_batch(tmp_path: Path) -> None:
+ """A failed batch ends index with exit 1 naming first and last file, while earlier batches stay cached for resume."""
+ from typing import Any
+
+ from devops_cli.config.constants import CONST_EXIT_FAILURE
+
+ file_a = tmp_path / "file_a.py"
+ file_b = tmp_path / "file_b.py"
+ file_c = tmp_path / "file_c.py"
+ file_a.write_text("def a(): pass\n", encoding="utf-8")
+ file_b.write_text("def b(): pass\n", encoding="utf-8")
+ file_c.write_text("def c(): pass\n", encoding="utf-8")
+
+ qdrant = FakeQdrantClient()
+ cache_dir = tmp_path / ".cache"
+ cache_dir.mkdir()
+
+ batch_calls = 0
+
+ class StubFailingSecondBatchEmbedder:
+ model = "test-model"
+ batch_size = 1
+
+ def embed_texts(self, texts: list[str], *, is_query: bool = False) -> list[list[float]]:
+ nonlocal batch_calls
+ batch_calls += 1
+ if batch_calls == 2:
+ raise RuntimeError("Gateway 504 Gateway Timeout")
+ return [[0.1] * 8 for _ in texts]
+
+ embedder = StubFailingSecondBatchEmbedder()
+ indexer = WorkspaceIndexer(qdrant=qdrant, embedder=embedder, cache_dir=cache_dir) # type: ignore[arg-type]
+
+ with pytest.raises(EmbeddingsError) as exc_info:
+ indexer.index_workspace(tmp_path, include_kb=False)
+
+ assert (
+ exc_info.value.exit_code == CONST_EXIT_FAILURE
+ and "Failed to embed batch from" in exc_info.value.message
+ and "Gateway 504 Gateway Timeout" in exc_info.value.message
+ )
+
+ cached = indexer._load_cache()
+ assert len(cached) == 1
+ assert "file_a.py" in next(iter(cached.keys()))
+
+ embedder_recovered = StubFailingSecondBatchEmbedder()
+
+ def fake_embed(texts: list[str], **kwargs: Any) -> list[list[float]]:
+ return [[0.2] * 8 for _ in texts]
+
+ embedder_recovered.embed_texts = fake_embed # type: ignore[method-assign]
+ indexer_resume = WorkspaceIndexer(
+ qdrant=qdrant,
+ embedder=embedder_recovered,
+ cache_dir=cache_dir, # type: ignore[arg-type]
+ )
+
+ result = indexer_resume.index_workspace(tmp_path, include_kb=False, force=False)
+ assert (result["indexed_files"], result["skipped_files"]) == (2, 1)
diff --git a/tests/test_rag_investigator.py b/tests/test_rag_investigator.py
index ac568258ae..1dfaed9785 100644
--- a/tests/test_rag_investigator.py
+++ b/tests/test_rag_investigator.py
@@ -3,11 +3,16 @@
from __future__ import annotations
import logging
+import threading
+import time
+from typing import Any
from unittest.mock import MagicMock, patch
import pytest
+from devops_cli.ai.rag.embeddings import EmbeddingsError
from devops_cli.ai.rag.investigator import (
+ _RAG_STOPPED,
clear_investigation_cache,
format_rag_investigation_for_prompt,
investigate_rag_context,
@@ -164,3 +169,224 @@ def test_format_rag_investigation_for_prompt() -> None:
formatted = format_rag_investigation_for_prompt(ctx, heading="Custom Architecture Context")
assert "### Custom Architecture Context" in formatted
assert "def main(): pass" in formatted
+
+
+def test_concurrent_lookups_wait_for_probe_outcome() -> None:
+ """20 concurrent lookups against a hanging stub finish in < 1s with at most 2 requests, skipping when probe fails."""
+ from concurrent.futures import ThreadPoolExecutor
+
+ clear_investigation_cache()
+ st = Settings()
+ st.ai.rag.enabled = True
+
+ request_count = 0
+ lock = threading.Lock()
+
+ def hanging_embed_query(query: str) -> list[float]:
+ nonlocal request_count
+ with lock:
+ request_count += 1
+ time.sleep(0.2)
+ raise EmbeddingsError("Timeout hanging query", is_transient=True)
+
+ with (
+ patch("devops_cli.ai.rag.investigator.QdrantClient") as mock_qdrant_cls,
+ patch("devops_cli.ai.rag.investigator.EmbeddingsEngine") as mock_emb_cls,
+ patch("devops_cli.config.settings.get_qdrant_api_key", return_value="test-key"),
+ patch("devops_cli.config.settings.get_ai_api_key", return_value="test-key"),
+ ):
+ mock_qdrant = MagicMock()
+ mock_qdrant.is_alive.return_value = True
+ mock_qdrant_cls.return_value = mock_qdrant
+
+ mock_emb = MagicMock()
+ mock_emb.model = "test-embed"
+ mock_emb.embed_query.side_effect = hanging_embed_query
+ mock_emb_cls.return_value = mock_emb
+
+ start_t = time.perf_counter()
+ with ThreadPoolExecutor(max_workers=20) as executor:
+ futures = [
+ executor.submit(investigate_rag_context, f"query {i}", settings=st)
+ for i in range(20)
+ ]
+ results = [f.result() for f in futures]
+ elapsed = time.perf_counter() - start_t
+
+ assert (elapsed < 1.0, request_count <= 2, all(r is None for r in results)) == (
+ True,
+ True,
+ True,
+ )
+
+
+def test_concurrent_lookups_healthy_stub_all_get_context() -> None:
+ """20 concurrent lookups against a healthy stub all get context."""
+ from concurrent.futures import ThreadPoolExecutor
+
+ clear_investigation_cache()
+ st = Settings()
+ st.ai.rag.enabled = True
+
+ chunk = CodeChunk(
+ id="chk-1",
+ file_path="src/main.py",
+ project_name="devops-cli",
+ language="python",
+ start_line=1,
+ end_line=10,
+ content="def hello(): pass",
+ )
+ search_result = SearchResult(chunk=chunk, score=0.95)
+
+ with (
+ patch("devops_cli.ai.rag.investigator.QdrantClient") as mock_qdrant_cls,
+ patch("devops_cli.ai.rag.investigator.EmbeddingsEngine") as mock_emb_cls,
+ patch("devops_cli.ai.rag.investigator.SemanticRetriever") as mock_retriever_cls,
+ ):
+ mock_qdrant = MagicMock()
+ mock_qdrant.is_alive.return_value = True
+ mock_qdrant_cls.return_value = mock_qdrant
+
+ mock_emb = MagicMock()
+ mock_emb.model = "test-embed"
+ mock_emb_cls.return_value = mock_emb
+
+ mock_retriever = MagicMock()
+ mock_retriever.retrieve_context.return_value = RAGContext(
+ query="test",
+ results=[search_result],
+ formatted_text="hello",
+ )
+ mock_retriever_cls.return_value = mock_retriever
+
+ with ThreadPoolExecutor(max_workers=20) as executor:
+ futures = [
+ executor.submit(investigate_rag_context, f"query {i}", settings=st)
+ for i in range(20)
+ ]
+ results = [f.result() for f in futures]
+
+ assert (len(results), all(r is not None for r in results)) == (20, True)
+
+
+def test_circuit_breaker_pause_and_resume(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Three timeouts open breaker for 60s; lookups during pause send no request; probe after pause resumes."""
+ clear_investigation_cache()
+ st = Settings()
+ st.ai.rag.enabled = True
+
+ simulated_time = 1000.0
+
+ def fake_monotonic() -> float:
+ return simulated_time
+
+ monkeypatch.setattr("time.monotonic", fake_monotonic)
+
+ request_count = 0
+ fail = True
+
+ def stub_embed_query(query: str) -> list[float]:
+ nonlocal request_count
+ request_count += 1
+ if fail:
+ raise EmbeddingsError("Timeout embedding", is_transient=True)
+ return [0.1] * 8
+
+ chunk = CodeChunk(
+ id="chk-1",
+ file_path="src/main.py",
+ project_name="devops-cli",
+ language="python",
+ start_line=1,
+ end_line=10,
+ content="def hello(): pass",
+ )
+ search_result = SearchResult(chunk=chunk, score=0.95)
+
+ with (
+ patch("devops_cli.ai.rag.investigator.QdrantClient") as mock_qdrant_cls,
+ patch("devops_cli.ai.rag.investigator.EmbeddingsEngine") as mock_emb_cls,
+ patch("devops_cli.ai.rag.investigator.SemanticRetriever") as mock_retriever_cls,
+ ):
+ mock_qdrant = MagicMock()
+ mock_qdrant.is_alive.return_value = True
+ mock_qdrant_cls.return_value = mock_qdrant
+
+ mock_emb = MagicMock()
+ mock_emb.model = "test-embed"
+ mock_emb.embed_query.side_effect = stub_embed_query
+ mock_emb_cls.return_value = mock_emb
+
+ def fake_retrieve_context(q: str, **kwargs: Any) -> RAGContext | None:
+ stub_embed_query(q)
+ return RAGContext(
+ query=q,
+ results=[search_result],
+ formatted_text="hello",
+ )
+
+ mock_retriever = MagicMock()
+ mock_retriever.retrieve_context.side_effect = fake_retrieve_context
+ mock_retriever_cls.return_value = mock_retriever
+
+ # 1. Three timeouts
+ r1 = investigate_rag_context("query 1", settings=st)
+ r2 = investigate_rag_context("query 2", settings=st)
+ r3 = investigate_rag_context("query 3", settings=st)
+ assert (r1, r2, r3, request_count) == (None, None, None, 3)
+
+ # 2. Lookups during 60s pause send 0 requests
+ simulated_time += 15.0
+ r4 = investigate_rag_context("query 4", settings=st)
+ simulated_time += 15.0
+ r5 = investigate_rag_context("query 5", settings=st)
+ assert (r4, r5, request_count) == (None, None, 3)
+
+ # 3. Probe after pause succeeds and lookups resume
+ simulated_time += 40.0
+ fail = False
+ r6 = investigate_rag_context("query 6", settings=st)
+ r7 = investigate_rag_context("query 7", settings=st)
+ assert (r6 is not None, r7 is not None, request_count) == (True, True, 5)
+
+ # 4. A 429 counts as transient and does not permanently stop RAG
+ fail = True
+
+ def stub_429(query: str, **kwargs: Any) -> RAGContext | None:
+ raise EmbeddingsError("429 No deployments available", is_transient=True)
+
+ mock_retriever.retrieve_context.side_effect = stub_429
+ r8 = investigate_rag_context("query 8", settings=st)
+ assert (r8 is None, not _RAG_STOPPED.is_set()) == (True, True)
+
+
+def test_settings_score_threshold_reaches_qdrant_search() -> None:
+ """Configured ai.rag.score_threshold reaches retriever and Qdrant search."""
+ clear_investigation_cache()
+ st = Settings()
+ st.ai.rag.enabled = True
+ st.ai.rag.score_threshold = 0.5
+
+ with (
+ patch("devops_cli.ai.rag.investigator.QdrantClient") as mock_qdrant_cls,
+ patch("devops_cli.ai.rag.investigator.EmbeddingsEngine") as mock_emb_cls,
+ patch("devops_cli.ai.rag.investigator.SemanticRetriever") as mock_retriever_cls,
+ ):
+ mock_qdrant = MagicMock()
+ mock_qdrant.is_alive.return_value = True
+ mock_qdrant_cls.return_value = mock_qdrant
+
+ mock_emb = MagicMock()
+ mock_emb.model = "test-embed"
+ mock_emb_cls.return_value = mock_emb
+
+ mock_retriever = MagicMock()
+ mock_retriever.retrieve_context.return_value = None
+ mock_retriever_cls.return_value = mock_retriever
+
+ investigate_rag_context("test query", settings=st)
+
+ mock_retriever_cls.assert_called_once()
+ _, kwargs = mock_retriever_cls.call_args
+ assert kwargs.get("default_score_threshold") == 0.5