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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-25
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Design

## Context

See `proposal.md` for motivation.
`investigate_rag_context` in `src/devops_cli/ai/rag/investigator.py` uses `_INVESTIGATION_CACHE` to memoize query results for 60 seconds.
When a retrieval encounters an error, `_retrieve` returns `None` or raises an exception.
The function previously cached `(now, found)` where `found` was `None`.
This caused transient failures to be cached, preventing recovery until the cache TTL expired.

## Goals / Non-Goals

**Goals:**

- Ensure that only completed lookups are added to `_INVESTIGATION_CACHE`.
- Ensure that hits and empty results alike are cached when the lookup completes.
- Ensure that transient failures, pauses, and stops are not cached.
- Allow queries to succeed immediately once the backend recovers from a transient failure.

**Non-Goals:**

- Do not alter the cache key format or the cache TTL duration.
- Do not alter circuit breaker behavior or probe coordination.
- Do not change how empty results are formatted or represented.

## Decisions

- **Condition cache insertion on `ctx is not None`.**
When `_retrieve` succeeds, it returns a `RAGContext` instance (`ctx is not None`).
If results are empty, `ctx.has_results` is `False`, `found` is `None`, and `(now, None)` is stored in the cache.
If results are present, `found` is `ctx`, and `(now, ctx)` is stored in the cache.
When `_retrieve` fails, pauses, or stops, `ctx` is `None`, and the function skips cache insertion.
- *Rejected Alternative:* Clear cache on error. Evidence: Clearing the entire cache on an error purges valid cached lookups for other queries.
- *Rejected Alternative:* Store an explicit status in the cache tuple. Evidence: Completed empty lookups return `None`, and failures do not cache. Checking `ctx is not None` before insertion avoids changing the cache tuple format.

## Risks / Trade-offs

- Repeated failed queries will call `_retrieve` until the circuit breaker trips. → This is the intended circuit breaker design. Three consecutive failures pause lookups for 60 seconds.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Proposal

## Why

Issue #1351: `investigate_rag_context` caches a failed lookup as `None` for 60 seconds.
After a transient failure, the same query returns `None` for up to 60 seconds even after the backend recovers.
Other queries can retrieve context while the failed query cannot.
The cache must store only completed lookups.
A failure, a pause, or a stop must not enter the cache.

## What Changes

- Cache lookup results in `_INVESTIGATION_CACHE` only when the lookup completes.
- Keep failures, pauses, and stops out of `_INVESTIGATION_CACHE`.
- Serve completed empty results from `_INVESTIGATION_CACHE`.
- Add a unit test verifying that a transient failure is not cached and an empty lookup is cached.
- This change alters no behavior that a consumer observes outside cache retention of failed lookups. The change sets `skip_specs: true` in `.openspec.yaml`.
- This change fits in one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- `src/devops_cli/ai/rag/investigator.py`: `investigate_rag_context` writes to `_INVESTIGATION_CACHE` only when `ctx is not None`.
- `tests/test_rag_investigator.py`: adds `test_transient_lookup_failure_is_not_cached_and_empty_lookup_is_served_from_cache`.

## Feasibility

- Code inspection at `origin/main` commit `5d368c8bf2b1efac5f54258a7cf456df2a90068c`: line 462 of `src/devops_cli/ai/rag/investigator.py` unconditionally assigns `_INVESTIGATION_CACHE[cache_key] = (now, found)`.
- When `_retrieve` returns `None` due to a transient error, timeout, or circuit breaker pause, `ctx` is `None` and `found` is `None`.
- The cache stores `(now, None)` for 60 seconds, preventing retries after the backend recovers.
- Runtime test: on unpatched code, a transient error followed by a hit for the same query returns `[False, False]`. With the fix, it returns `[False, True]`.

## Existing Tool Considered

`pybreaker` and the in-memory cache `_INVESTIGATION_CACHE` in `src/devops_cli/ai/rag/investigator.py` manage lookup retries and caching.
No open tool or external library is required for this bug fix.
Conditioning cache insertion on completed retrievals reuses the existing cache dictionary and circuit breaker.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Tasks

## 1. Implementation

- [x] 1.1 Write the failing test `test_transient_lookup_failure_is_not_cached_and_empty_lookup_is_served_from_cache` in `tests/test_rag_investigator.py`. Verify with `uv run devops ci test tests/test_rag_investigator.py` and verify failure against base with `uv run devops ci fail-to-pass --base origin/main`.
- [x] 1.2 Update `investigate_rag_context` in `src/devops_cli/ai/rag/investigator.py` to cache in `_INVESTIGATION_CACHE` only when `ctx is not None`. Verify with `uv run devops ci test tests/test_rag_investigator.py`.
- [x] 1.3 Verify static checks and full suite with `uv run devops ci`.
3 changes: 2 additions & 1 deletion src/devops_cli/ai/rag/investigator.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,8 @@ def investigate_rag_context(
_report_lookup_failure(exc)
ctx = None
found = None if ctx is None else _recorded_results(ctx, r_span, clean_query, start_time)
_INVESTIGATION_CACHE[cache_key] = (now, found)
if ctx is not None:
_INVESTIGATION_CACHE[cache_key] = (now, found)
return found


Expand Down
42 changes: 42 additions & 0 deletions tests/test_rag_investigator.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,45 @@ def test_settings_score_threshold_reaches_qdrant_search() -> None:
mock_retriever_cls.assert_called_once()
_, kwargs = mock_retriever_cls.call_args
assert kwargs.get("default_score_threshold") == 0.5


def test_transient_lookup_failure_is_not_cached_and_empty_lookup_is_served_from_cache() -> None:
"""A transient error is not cached, so the query recovers, and an empty lookup is cached."""
clear_investigation_cache()
st = Settings()
st.ai.rag.enabled = True
st.qdrant.url = "http://192.0.2.10:6333"

search_result = SearchResult(chunk=_chunk(), score=0.95)
calls: list[str] = []
fail = True

def retrieve_context(query: str, **kwargs: Any) -> RAGContext:
calls.append(query)
if query == "transient query" and fail:
raise EmbeddingsError(f"Timeout embedding {query}", is_transient=True)
if query == "empty query":
return RAGContext(query=query, results=[], formatted_text="")
return RAGContext(
query=query,
results=[search_result],
formatted_text="<rag_context>hello</rag_context>",
)

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_cls.return_value.is_alive.return_value = True
mock_emb_cls.return_value.model = "test-embed"
mock_retriever_cls.return_value.retrieve_context.side_effect = retrieve_context

r1 = investigate_rag_context("transient query", settings=st)
fail = False
r2 = investigate_rag_context("transient query", settings=st)
assert [r1 is not None, r2 is not None] == [False, True]

r3 = investigate_rag_context("empty query", settings=st)
r4 = investigate_rag_context("empty query", settings=st)
assert (r3, r4, calls.count("empty query")) == (None, None, 1)
Loading