Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/1065.md
Original file line number Diff line number Diff line change
@@ -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).
40 changes: 40 additions & 0 deletions docs/agent/tasks/task-1065-failing-embedding-model-pauses-rag.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

---

Expand Down
161 changes: 139 additions & 22 deletions src/devops_cli/ai/rag/chunker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand Down
Loading
Loading