From d91a90a04b2e536e8b81ff29b69297d10f3bd848 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 07:25:15 -0700 Subject: [PATCH 01/15] feat(mcp): add embedding-based semantic retrieval and passive context Replace keyword-only docs and troubleshooting search with MiniLM embeddings and hybrid scoring, add get_context_for_pipeline for AI prompt injection, and pre-cache the model in Docker. Existing tool signatures stay unchanged. --- olive-mcp-server/Dockerfile | 22 +- .../olive_mcp_server/mcp_server.py | 4 + .../olive_mcp_server/tools/__init__.py | 2 + .../olive_mcp_server/tools/docs_search.py | 271 +++++++++++-- .../olive_mcp_server/tools/embeddings.py | 165 ++++++++ .../olive_mcp_server/tools/passive_context.py | 118 ++++++ .../olive_mcp_server/tools/troubleshooting.py | 313 ++++++++++----- olive-mcp-server/pyproject.toml | 2 + .../tests/test_docs_search_semantic.py | 252 ++++++++++++ olive-mcp-server/tests/test_embeddings.py | 153 +++++++ olive-mcp-server/tests/test_integration.py | 19 +- .../tests/test_passive_context.py | 145 +++++++ .../tests/test_troubleshooting_hybrid.py | 379 ++++++++++++++++++ 13 files changed, 1689 insertions(+), 156 deletions(-) create mode 100644 olive-mcp-server/olive_mcp_server/tools/embeddings.py create mode 100644 olive-mcp-server/olive_mcp_server/tools/passive_context.py create mode 100644 olive-mcp-server/tests/test_docs_search_semantic.py create mode 100644 olive-mcp-server/tests/test_embeddings.py create mode 100644 olive-mcp-server/tests/test_passive_context.py create mode 100644 olive-mcp-server/tests/test_troubleshooting_hybrid.py diff --git a/olive-mcp-server/Dockerfile b/olive-mcp-server/Dockerfile index b848dc3f..5c1be35a 100644 --- a/olive-mcp-server/Dockerfile +++ b/olive-mcp-server/Dockerfile @@ -1,5 +1,6 @@ # Multi-stage build for Olive MCP Server -# Produces a slim image (~120MB) that runs the MCP server over SSE/HTTP transport. +# Image size is dominated by CPU PyTorch + sentence-transformers + MiniLM +# (~1.5–3GB depending on platform wheels — not a slim ~120MB image). # ── Stage 1: Install dependencies ──────────────────────────────────────────── FROM python:3.12-slim AS builder @@ -9,7 +10,15 @@ WORKDIR /build COPY pyproject.toml ./ COPY olive_mcp_server/ ./olive_mcp_server/ -RUN pip install --no-cache-dir --prefix=/install . "mcp<2" +# Prefer CPU-only torch wheels to avoid multi-GB CUDA packages. +RUN pip install --no-cache-dir --prefix=/install \ + --extra-index-url https://download.pytorch.org/whl/cpu \ + . "mcp<2" + +# Pre-cache the embedding model so the runtime image does not need network +# access on first semantic search. Cache lands under /root/.cache/huggingface. +RUN PYTHONPATH="$(echo /install/lib/python*/site-packages)" \ + python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')" # ── Stage 2: Runtime ───────────────────────────────────────────────────────── FROM python:3.12-slim AS runtime @@ -18,29 +27,28 @@ LABEL org.opencontainers.image.title="olive-mcp-server" LABEL org.opencontainers.image.description="MCP server for Microsoft Olive model optimization guidance" LABEL org.opencontainers.image.licenses="MIT" -# Create non-root user RUN useradd --create-home --shell /bin/bash mcp WORKDIR /app -# Copy installed packages from builder COPY --from=builder /install /usr/local -# Copy source (needed for knowledge_base JSON files) +COPY --from=builder /root/.cache/huggingface /home/mcp/.cache/huggingface +RUN chown -R mcp:mcp /home/mcp/.cache + COPY olive_mcp_server/ ./olive_mcp_server/ COPY pyproject.toml ./ -# Volume mount point for knowledge base hot-reload VOLUME /app/olive_mcp_server/knowledge_base USER mcp -# SSE transport listens on port 8000 by default EXPOSE 8000 ENV MCP_TRANSPORT=sse ENV MCP_HOST=0.0.0.0 ENV MCP_PORT=8000 +ENV HF_HOME=/home/mcp/.cache/huggingface HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ CMD python -c "import urllib.request; r=urllib.request.urlopen('http://localhost:8000/sse',timeout=3); r.close()" || exit 1 diff --git a/olive-mcp-server/olive_mcp_server/mcp_server.py b/olive-mcp-server/olive_mcp_server/mcp_server.py index 4c2e3111..6b317a4f 100644 --- a/olive-mcp-server/olive_mcp_server/mcp_server.py +++ b/olive-mcp-server/olive_mcp_server/mcp_server.py @@ -42,6 +42,10 @@ "olive_mcp_server.tools.tradeoff", "evaluate_optimization_tradeoff", ), + "get_context_for_pipeline": ( + "olive_mcp_server.tools.passive_context", + "get_context_for_pipeline", + ), } _mcp_instance: Any | None = None diff --git a/olive-mcp-server/olive_mcp_server/tools/__init__.py b/olive-mcp-server/olive_mcp_server/tools/__init__.py index 6ac8bdea..9786e3f8 100644 --- a/olive-mcp-server/olive_mcp_server/tools/__init__.py +++ b/olive-mcp-server/olive_mcp_server/tools/__init__.py @@ -31,6 +31,7 @@ "troubleshoot_olive_error": (".troubleshooting", "troubleshoot_olive_error"), "diagnose_error": (".troubleshooting", "diagnose_error"), "get_error_frequency_summary": (".troubleshooting", "get_error_frequency_summary"), + "get_context_for_pipeline": (".passive_context", "get_context_for_pipeline"), } @@ -174,6 +175,7 @@ def __getattr__(name: str) -> Any: "troubleshoot_olive_error", "diagnose_error", "get_error_frequency_summary", + "get_context_for_pipeline", "KB_DIR", "load_json", "load_passes", diff --git a/olive-mcp-server/olive_mcp_server/tools/docs_search.py b/olive-mcp-server/olive_mcp_server/tools/docs_search.py index 14e79470..3df58df7 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -1,10 +1,25 @@ -"""Tool: search_olive_documentation.""" +"""Tool: search_olive_documentation. + +Semantic search over the local Olive knowledge base (and optional live docs), +with keyword fallback when nothing scores above the embedding threshold. +""" + +from __future__ import annotations import json +import threading import time from typing import Any +import numpy as np + from . import KB_DIR +from .embeddings import ( + DEFAULT_THRESHOLD, + EMBEDDING_DIM, + build_kb_index, + semantic_search, +) # Files that are generated by update_kb.py and should not be searched as KB. @@ -14,6 +29,22 @@ _LIVE_CACHE: dict[str, str] = {} _LIVE_CACHE_TTL_SECONDS = 3600 _LAST_FETCH_TIME = 0.0 +_LIVE_FETCH_LOCK = threading.Lock() +# Monotonic generation so out-of-order HTTP completions cannot overwrite a +# fresher cache entry started later. +_LIVE_FETCH_GENERATION = 0 + +# Live snippet embedding cache (tied to _LAST_FETCH_TIME). +_LIVE_SNIPPETS: list[tuple[str, str]] = [] +_LIVE_EMBEDDINGS: np.ndarray | None = None +_LIVE_EMBED_CACHE_TIME = -1.0 +_LIVE_INDEX_LOCK = threading.Lock() + +# Local KB embedding index (invalidated when any KB JSON mtime changes). +_KB_TEXTS: list[tuple[str, str]] = [] +_KB_EMBEDDINGS: np.ndarray | None = None +_KB_INDEX_MTIME = -1.0 +_KB_INDEX_LOCK = threading.Lock() def _flatten(obj: Any, prefix: str = "") -> list[tuple[str, str]]: @@ -45,37 +76,138 @@ def _load_kb_text() -> list[tuple[str, str]]: return all_text +def _kb_max_mtime() -> float: + """Return the maximum mtime among searchable KB JSON files.""" + mtimes: list[float] = [] + for file in KB_DIR.glob("*.json"): + if file.name in _EXCLUDED_KB_FILES: + continue + try: + mtimes.append(file.stat().st_mtime) + except OSError: + continue + return max(mtimes) if mtimes else 0.0 + + +def get_or_build_kb_index() -> tuple[list[tuple[str, str]], np.ndarray]: + """Public helper: lazy-build (and mtime-invalidate) the local KB embedding index. + + Used by docs search and passive context so both share one cache. + Encode work runs outside the lock; the cache is only stamped when the KB + mtime is unchanged from the value observed at load time (avoids publishing + stale texts under a newer mtime after a mid-build hot-reload). + """ + global _KB_TEXTS, _KB_EMBEDDINGS, _KB_INDEX_MTIME + + with _KB_INDEX_LOCK: + current_mtime = _kb_max_mtime() + if ( + _KB_EMBEDDINGS is not None + and _KB_TEXTS is not None + and _KB_INDEX_MTIME == current_mtime + ): + return _KB_TEXTS, _KB_EMBEDDINGS + + # Capture mtime at load time; only publish if it is still current later. + build_mtime = _kb_max_mtime() + texts = _load_kb_text() + if not texts: + embeddings: np.ndarray = np.zeros((0, EMBEDDING_DIM), dtype=np.float32) + else: + embeddings = build_kb_index([t for _, t in texts]) + + with _KB_INDEX_LOCK: + current_mtime = _kb_max_mtime() + # Another thread may have already published a valid index for the current mtime. + if ( + _KB_EMBEDDINGS is not None + and _KB_TEXTS is not None + and _KB_INDEX_MTIME == current_mtime + ): + return _KB_TEXTS, _KB_EMBEDDINGS + + if current_mtime != build_mtime: + # KB changed mid-build: return this result without poisoning the cache + # (stale content must not be stamped with the newer mtime). + return texts, embeddings + + _KB_TEXTS = texts + _KB_EMBEDDINGS = embeddings + _KB_INDEX_MTIME = build_mtime + return _KB_TEXTS, _KB_EMBEDDINGS + + +# Back-compat alias for internal callers / tests. +_get_kb_index = get_or_build_kb_index + + def _score_terms(text: str, terms: list[str]) -> int: text_lower = text.lower() return sum(1 for term in terms if term in text_lower) -def _search_local(terms: list[str], top_k: int) -> list[dict[str, Any]]: - scored = [] - for path, text in _load_kb_text(): - score = _score_terms(text, terms) - if score == 0: +def _keyword_search( + entries: list[tuple[str, str]], + terms: list[str], + top_k: int, +) -> list[dict[str, Any]]: + """Keyword fallback: substring term matching against (source, text) pairs. + + Relevance is normalized to [0, 1] as hits / max(1, len(terms)) so it is + commensurate with semantic cosine scores when sources are merged. + """ + if not terms or top_k <= 0: + return [] + denom = max(1, len(terms)) + scored: list[dict[str, Any]] = [] + for path, text in entries: + hits = _score_terms(text, terms) + if hits == 0: continue scored.append({ "source": path, "snippet": text[:300], - "relevance": score, + "relevance": hits / denom, }) scored.sort(key=lambda x: x["relevance"], reverse=True) return scored[:top_k] +def _search_local(query: str, top_k: int) -> list[dict[str, Any]]: + """Semantic search over the local KB, with keyword fallback.""" + terms = [t.lower() for t in query.split() if t] + + try: + kb_texts, embeddings = get_or_build_kb_index() + results = semantic_search( + query, + kb_texts, + embeddings, + top_k, + threshold=DEFAULT_THRESHOLD, + ) + if results: + return results + except Exception: # noqa: BLE001 + pass + + return _keyword_search(_load_kb_text(), terms, top_k) + + def _fetch_live_docs() -> dict[str, str]: - """Fetch and cache the Olive documentation landing page. - - Returns: - dict[str, str]: The cached documentation pages, or an empty dictionary if none are available. + """Fetch (and cache) the live Olive docs landing page. + + Concurrent fetches take a generation token; only the latest generation may + publish, so a slow older response cannot overwrite a fresher one. """ - global _LIVE_CACHE, _LAST_FETCH_TIME # noqa: PLW0603 + global _LIVE_CACHE, _LAST_FETCH_TIME, _LIVE_FETCH_GENERATION # noqa: PLW0603 - now = time.monotonic() - if _LIVE_CACHE and (now - _LAST_FETCH_TIME) < _LIVE_CACHE_TTL_SECONDS: - return _LIVE_CACHE + with _LIVE_FETCH_LOCK: + now = time.monotonic() + if _LIVE_CACHE and (now - _LAST_FETCH_TIME) < _LIVE_CACHE_TTL_SECONDS: + return dict(_LIVE_CACHE) + _LIVE_FETCH_GENERATION += 1 + my_generation = _LIVE_FETCH_GENERATION try: # Lazy import: BeautifulSoup/requests are optional for local-KB-only search. @@ -86,12 +218,16 @@ def _fetch_live_docs() -> dict[str, str]: pages = result.get("pages", {}) fetched = {k: v for k, v in pages.items() if isinstance(v, str)} if fetched: - _LIVE_CACHE = fetched - _LAST_FETCH_TIME = now + with _LIVE_FETCH_LOCK: + # Ignore stale completions if a newer fetch was started. + if my_generation == _LIVE_FETCH_GENERATION: + _LIVE_CACHE = fetched + _LAST_FETCH_TIME = time.monotonic() except Exception: # noqa: BLE001 pass # Keep stale cache or return empty on failure. - return _LIVE_CACHE + with _LIVE_FETCH_LOCK: + return dict(_LIVE_CACHE) def _split_live_snippets(pages: dict[str, str]) -> list[tuple[str, str]]: @@ -105,25 +241,67 @@ def _split_live_snippets(pages: dict[str, str]) -> list[tuple[str, str]]: return snippets -def _search_live(terms: list[str], top_k: int) -> list[dict[str, Any]]: +def _get_live_index() -> tuple[list[tuple[str, str]], np.ndarray]: + """Return live snippets and their embeddings, rebuilding on cache refresh.""" + global _LIVE_SNIPPETS, _LIVE_EMBEDDINGS, _LIVE_EMBED_CACHE_TIME + + pages = _fetch_live_docs() + with _LIVE_FETCH_LOCK: + fetch_time = _LAST_FETCH_TIME + + with _LIVE_INDEX_LOCK: + if ( + _LIVE_EMBEDDINGS is not None + and _LIVE_SNIPPETS + and _LIVE_EMBED_CACHE_TIME == fetch_time + ): + return _LIVE_SNIPPETS, _LIVE_EMBEDDINGS + + snippets = _split_live_snippets(pages) if pages else [] + if not snippets: + embeddings: np.ndarray = np.zeros((0, EMBEDDING_DIM), dtype=np.float32) + else: + embeddings = build_kb_index([t for _, t in snippets]) + + with _LIVE_INDEX_LOCK: + if ( + _LIVE_EMBEDDINGS is not None + and _LIVE_SNIPPETS + and _LIVE_EMBED_CACHE_TIME == fetch_time + ): + return _LIVE_SNIPPETS, _LIVE_EMBEDDINGS + + _LIVE_SNIPPETS = snippets + _LIVE_EMBEDDINGS = embeddings + _LIVE_EMBED_CACHE_TIME = fetch_time + return _LIVE_SNIPPETS, _LIVE_EMBEDDINGS + + +def _search_live(query: str, top_k: int) -> list[dict[str, Any]]: + """Semantic search over live docs snippets, with keyword fallback.""" + terms = [t.lower() for t in query.split() if t] try: - pages = _fetch_live_docs() - if not pages: + snippets, embeddings = _get_live_index() + if not snippets: return [] - scored = [] - for path, text in _split_live_snippets(pages): - score = _score_terms(text, terms) - if score == 0: - continue - scored.append({ - "source": path, - "snippet": text[:300], - "relevance": score, - }) - scored.sort(key=lambda x: x["relevance"], reverse=True) - return scored[:top_k] + results = semantic_search( + query, + snippets, + embeddings, + top_k, + threshold=DEFAULT_THRESHOLD, + ) + if results: + return results + return _keyword_search(snippets, terms, top_k) except Exception: # noqa: BLE001 - return [] + try: + pages = _fetch_live_docs() + if not pages: + return [] + return _keyword_search(_split_live_snippets(pages), terms, top_k) + except Exception: # noqa: BLE001 + return [] def search_olive_documentation(query: str, top_k: int = 5, live: bool = True) -> dict[str, Any]: @@ -136,6 +314,7 @@ def search_olive_documentation(query: str, top_k: int = 5, live: bool = True) -> Returns: Ranked results with snippet, source path, and relevance score. + ``relevance`` is in roughly [0, 1] for both semantic and keyword modes. """ if top_k < 0: raise ValueError(f"top_k must be >= 0, got {top_k}") @@ -144,21 +323,35 @@ def search_olive_documentation(query: str, top_k: int = 5, live: bool = True) -> if not terms: return {"query": query, "count": 0, "results": [], "note": "Empty query."} - # Over-fetch from each source so the merge has a reasonable pool. per_source = max(top_k * 2, 10) - local_results = _search_local(terms, per_source) - live_results = _search_live(terms, per_source) if live else [] + local_results = _search_local(query, per_source) + live_results = _search_live(query, per_source) if live else [] combined = local_results + live_results - # For equal relevance, prefer live docs so fresh guidance surfaces first. combined.sort( key=lambda x: (-x["relevance"], 0 if x["source"].startswith("live:") else 1) ) + results = combined[:top_k] + if ( + live_results + and top_k > 0 + and results + and not any(r["source"].startswith("live:") for r in results) + ): + best_live = max(live_results, key=lambda x: x["relevance"]) + if top_k == 1: + results = [best_live] + else: + results = results[: top_k - 1] + [best_live] + results.sort( + key=lambda x: (-x["relevance"], 0 if x["source"].startswith("live:") else 1) + ) + return { "query": query, "count": len(combined), - "results": combined[:top_k], + "results": results, "note": ( "Merged local knowledge base and live Olive docs results. " "Live docs are cached for one hour." diff --git a/olive-mcp-server/olive_mcp_server/tools/embeddings.py b/olive-mcp-server/olive_mcp_server/tools/embeddings.py new file mode 100644 index 00000000..73065400 --- /dev/null +++ b/olive-mcp-server/olive_mcp_server/tools/embeddings.py @@ -0,0 +1,165 @@ +"""Shared embedding utilities for semantic knowledge-base search. + +Uses sentence-transformers all-MiniLM-L6-v2 (384-dim, ~80MB, CPU-only). +The model is loaded lazily on first encode call, not at import time. +""" + +from __future__ import annotations + +import threading +from typing import Any, Sequence + +import numpy as np + +MODEL_NAME = "all-MiniLM-L6-v2" +EMBEDDING_DIM = 384 +DEFAULT_THRESHOLD = 0.30 + +_model = None +_model_lock = threading.Lock() + + +def _get_model(): + """Thread-safe lazy singleton for SentenceTransformer (CPU-only).""" + global _model + if _model is not None: + return _model + with _model_lock: + if _model is None: + from sentence_transformers import SentenceTransformer + + _model = SentenceTransformer(MODEL_NAME, device="cpu") + return _model + + +def is_model_loaded() -> bool: + """Return True if the embedding model has already been loaded.""" + return _model is not None + + +def encode_texts(texts: Sequence[str]) -> np.ndarray: + """Encode a batch of texts into an (N, 384) float32 matrix. + + Rows are L2-normalized (``normalize_embeddings=True``). Callers may still + pass the matrix through ``cosine_similarity_scores``, which re-normalizes + safely for zero rows and non-normalized inputs. + """ + if not texts: + return np.zeros((0, EMBEDDING_DIM), dtype=np.float32) + model = _get_model() + embeddings = model.encode( + list(texts), + convert_to_numpy=True, + show_progress_bar=False, + normalize_embeddings=True, + ) + return np.asarray(embeddings, dtype=np.float32) + + +def encode_query(query: str) -> np.ndarray: + """Encode a single query string into a (384,) float32 vector.""" + if not query or not str(query).strip(): + return np.zeros((EMBEDDING_DIM,), dtype=np.float32) + return encode_texts([str(query)])[0] + + +def cosine_similarity_scores( + query_vec: np.ndarray, + index_matrix: np.ndarray, +) -> np.ndarray: + """L2-normalized cosine similarity of query_vec against each index row. + + Returns a 1-D float32 array of length equal to the number of index rows. + Empty query or empty index yields an empty or zero-length array. + """ + if index_matrix is None or getattr(index_matrix, "size", 0) == 0: + return np.zeros((0,), dtype=np.float32) + if query_vec is None or getattr(query_vec, "size", 0) == 0: + n = int(index_matrix.shape[0]) if getattr(index_matrix, "ndim", 0) >= 1 else 0 + return np.zeros((n,), dtype=np.float32) + + q = np.asarray(query_vec, dtype=np.float32).reshape(-1) + mat = np.asarray(index_matrix, dtype=np.float32) + if mat.ndim == 1: + mat = mat.reshape(1, -1) + + q_norm = float(np.linalg.norm(q)) + if q_norm == 0.0: + return np.zeros((mat.shape[0],), dtype=np.float32) + q = q / q_norm + + row_norms = np.linalg.norm(mat, axis=1, keepdims=True) + # Avoid division by zero for zero rows. + safe_norms = np.where(row_norms == 0.0, 1.0, row_norms) + mat_normed = mat / safe_norms + # Zero rows stay zero after this (they had norm 0 and were divided by 1, + # but original zeros remain zeros). + + scores = mat_normed @ q + return np.asarray(scores, dtype=np.float32) + + +def build_kb_index(kb_texts: Sequence[str]) -> np.ndarray: + """Batch-encode all KB entry texts into an L2-normalized embedding matrix. + + Contract: returned rows are unit-length (except all-zero empty index). + Compatible with ``cosine_similarity_scores`` which also L2-normalizes. + """ + return encode_texts(list(kb_texts) if kb_texts else []) + + +def _entry_source_and_text(entry: Any) -> tuple[str, str]: + """Normalize a KB entry into (source, text). + + Accepts (source, text) pairs or dicts with source/text/snippet keys. + """ + if isinstance(entry, dict): + source = str(entry.get("source", "")) + text = str(entry.get("text") or entry.get("snippet") or "") + return source, text + if isinstance(entry, (tuple, list)) and len(entry) >= 2: + return str(entry[0]), str(entry[1]) + return "", str(entry) + + +def semantic_search( + query: str, + kb_texts: Sequence[Any], + kb_embeddings: np.ndarray, + top_k: int, + threshold: float = DEFAULT_THRESHOLD, +) -> list[dict[str, Any]]: + """Rank KB entries by cosine similarity to the query. + + Returns ``[{source, snippet, relevance}, ...]`` filtered by *threshold*, + sorted by relevance descending, limited to *top_k*. + """ + if top_k <= 0 or not kb_texts: + return [] + if kb_embeddings is None or getattr(kb_embeddings, "size", 0) == 0: + return [] + if not query or not str(query).strip(): + return [] + + query_vec = encode_query(str(query)) + scores = cosine_similarity_scores(query_vec, kb_embeddings) + if scores.size == 0: + return [] + + n = min(len(kb_texts), int(scores.shape[0])) + results: list[dict[str, Any]] = [] + for i in range(n): + score = float(scores[i]) + if score < threshold: + continue + source, text = _entry_source_and_text(kb_texts[i]) + results.append( + { + "source": source, + "snippet": text[:300], + "relevance": score, + } + ) + + results.sort(key=lambda x: x["relevance"], reverse=True) + return results[:top_k] diff --git a/olive-mcp-server/olive_mcp_server/tools/passive_context.py b/olive-mcp-server/olive_mcp_server/tools/passive_context.py new file mode 100644 index 00000000..7690e808 --- /dev/null +++ b/olive-mcp-server/olive_mcp_server/tools/passive_context.py @@ -0,0 +1,118 @@ +"""Tool: get_context_for_pipeline. + +Passive context retrieval for injecting KB snippets into an AI assistant +system prompt based on the current pipeline configuration. +""" + +from __future__ import annotations + +from typing import Any + +from .docs_search import get_or_build_kb_index +from .embeddings import DEFAULT_THRESHOLD, semantic_search + + +def _pass_descriptor_text(item: Any) -> str: + """Normalize a pass descriptor (str or dict) into searchable text.""" + if isinstance(item, str): + return item.strip() + if isinstance(item, dict): + parts: list[str] = [] + for key in ("name", "type", "pass_name", "pass_type", "id"): + val = item.get(key) + if val: + parts.append(str(val)) + # Fall back to any remaining string values. + if not parts: + parts = [str(v) for v in item.values() if isinstance(v, str) and v.strip()] + return " ".join(parts).strip() + return str(item).strip() if item is not None else "" + + +def _build_query( + pipeline_passes: list[Any], + model_name: str, + target_hardware: str, +) -> tuple[str, str]: + """Build semantic query text and a human-readable pipeline summary.""" + pass_texts = [_pass_descriptor_text(p) for p in (pipeline_passes or [])] + pass_texts = [t for t in pass_texts if t] + + summary_parts: list[str] = [] + if pass_texts: + summary_parts.append("passes: " + ", ".join(pass_texts)) + if model_name: + summary_parts.append(f"model: {model_name}") + if target_hardware: + summary_parts.append(f"hardware: {target_hardware}") + pipeline_summary = "; ".join(summary_parts) if summary_parts else "empty pipeline" + + query_bits = list(pass_texts) + if model_name: + query_bits.append(str(model_name)) + if target_hardware: + query_bits.append(str(target_hardware)) + query = " ".join(query_bits).strip() + return query, pipeline_summary + + +def get_context_for_pipeline( + pipeline_passes: list[Any] | None = None, + model_name: str = "", + target_hardware: str = "", + top_k: int = 5, +) -> dict[str, Any]: + """Retrieve KB context snippets relevant to a planned Olive pipeline. + + Intended for frontend injection into an AI assistant system prompt. + + Args: + pipeline_passes: List of pass names (strings) and/or dicts with + name/type fields describing the pipeline. + model_name: Optional model identifier. + target_hardware: Optional hardware target string. + top_k: Maximum number of snippets to return. + + Returns: + context_snippets, pipeline_summary, confidence (avg relevance), snippet_count. + """ + if top_k < 0: + raise ValueError(f"top_k must be >= 0, got {top_k}") + + query, pipeline_summary = _build_query( + list(pipeline_passes or []), + model_name or "", + target_hardware or "", + ) + + if not query or top_k == 0: + return { + "context_snippets": [], + "pipeline_summary": pipeline_summary, + "confidence": 0.0, + "snippet_count": 0, + } + + try: + kb_texts, embeddings = get_or_build_kb_index() + results = semantic_search( + query, + kb_texts, + embeddings, + top_k, + threshold=DEFAULT_THRESHOLD, + ) + except Exception: # noqa: BLE001 + results = [] + + confidences = [float(r.get("relevance", 0.0)) for r in results] + confidence = sum(confidences) / len(confidences) if confidences else 0.0 + # Bound to [0, 1] for API stability (cosine is already ~[-1,1] but we threshold). + confidence = max(0.0, min(1.0, confidence)) + + return { + "context_snippets": results, + "pipeline_summary": pipeline_summary, + "confidence": confidence, + "snippet_count": len(results), + } diff --git a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py index e2a600d4..fa0f7a8c 100644 --- a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py +++ b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py @@ -1,16 +1,28 @@ """Tool: troubleshoot_olive_error. Diagnoses Olive runtime and Olive Studio errors using domain-tagged KB -entries. Tracks error frequency with a module-level store. +entries with hybrid semantic + keyword scoring. Tracks error frequency +with a module-level store. """ from __future__ import annotations +import hashlib import threading import time +from pathlib import Path from typing import Any, Literal -from . import load_quirks, load_studio_troubleshooting, load_troubleshooting +import numpy as np + +from . import KB_DIR, load_quirks, load_studio_troubleshooting, load_troubleshooting +from .embeddings import ( + DEFAULT_THRESHOLD, + EMBEDDING_DIM, + build_kb_index, + cosine_similarity_scores, + encode_query, +) DomainName = Literal["auto", "olive", "studio"] @@ -20,12 +32,26 @@ RECURRING_MAX = 3 FREQUENT_MAX = 10 +# Hybrid scoring weights: semantic cosine + keyword pattern hits. +_SEMANTIC_WEIGHT = 0.6 +_KEYWORD_WEIGHT = 0.4 +# Extra ranking boost per pattern alternative hit (OR list multi-evidence). +_HIT_RANK_BONUS = 0.05 +_HIT_RANK_BONUS_CAP = 5 + # --------------------------------------------------------------------------- # Error frequency tracker (module-level, lives for the process lifetime) # --------------------------------------------------------------------------- _lock = threading.Lock() _frequency_store: dict[str, dict[str, Any]] = {} +# --------------------------------------------------------------------------- +# Troubleshooting embedding indexes (keyed by content fingerprint) +# --------------------------------------------------------------------------- +_ts_index_lock = threading.Lock() +# fingerprint -> (entries, embeddings, kb_mtime_at_build) +_ts_index_cache: dict[str, tuple[list[dict[str, Any]], np.ndarray, float]] = {} + def _get_frequency_key(matched_entry: str | None, error_message: str) -> str: """Derive a stable key for frequency tracking.""" @@ -69,20 +95,123 @@ def _format_ts(ts: float) -> str: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ts)) -def _score(entry: dict[str, Any], error_message: str, pass_name: str, config_context: str) -> int: - """Calculate how many configured entry patterns appear in the error context. - - Parameters: - entry (dict[str, Any]): Knowledge-base entry containing optional matching patterns. - error_message (str): Error message to search. - pass_name (str): Pass name to search. - config_context (str): Configuration context to search. - - Returns: - int: Number of configured patterns found in the combined error context. +# --------------------------------------------------------------------------- +# Hybrid scoring (semantic + keyword) +# --------------------------------------------------------------------------- + +def _entry_embed_text(entry: dict[str, Any]) -> str: + """Build the text used to embed a troubleshooting entry.""" + parts = [ + str(entry.get("title") or ""), + str(entry.get("root_cause") or ""), + str(entry.get("solution") or ""), + ] + patterns = entry.get("patterns") or [] + parts.extend(str(p) for p in patterns) + return " ".join(p for p in parts if p).strip() + + +def _entries_fingerprint(entries: list[dict[str, Any]]) -> str: + """Stable fingerprint of entry ids + embed texts (order-sensitive).""" + h = hashlib.sha256() + for entry in entries: + eid = str(entry.get("id") or "") + h.update(eid.encode("utf-8")) + h.update(b"\0") + h.update(_entry_embed_text(entry).encode("utf-8")) + h.update(b"\0") + return h.hexdigest() + + +def _troubleshooting_kb_mtime() -> float: + """Max mtime of olive + studio troubleshooting JSON files.""" + mtimes: list[float] = [] + for name in ("troubleshooting.json", "studio_troubleshooting.json"): + path = KB_DIR / name + try: + mtimes.append(path.stat().st_mtime) + except OSError: + continue + return max(mtimes) if mtimes else 0.0 + + +def _get_troubleshooting_index( + entries: list[dict[str, Any]] | None = None, +) -> tuple[list[dict[str, Any]], np.ndarray]: + """Lazy-build embeddings for a troubleshooting entry list (thread-safe). + + Cache is keyed by content fingerprint so olive and studio pools coexist. + Invalidates when fingerprint or KB mtime changes. Callers must score using + the returned entries list so embeddings stay position-aligned. """ + global _ts_index_cache + + if entries is None: + entries = load_troubleshooting() + entries_list = list(entries) + fingerprint = _entries_fingerprint(entries_list) + file_mtime = _troubleshooting_kb_mtime() + + with _ts_index_lock: + cached = _ts_index_cache.get(fingerprint) + if cached is not None and cached[2] == file_mtime: + return cached[0], cached[1] + + texts = [_entry_embed_text(e) for e in entries_list] + if not texts: + embeddings = np.zeros((0, EMBEDDING_DIM), dtype=np.float32) + else: + embeddings = build_kb_index(texts) + + with _ts_index_lock: + cached = _ts_index_cache.get(fingerprint) + if cached is not None and cached[2] == file_mtime: + return cached[0], cached[1] + # Only publish if mtime is still the build-time value. + current_mtime = _troubleshooting_kb_mtime() + if current_mtime != file_mtime: + return entries_list, embeddings + _ts_index_cache[fingerprint] = (entries_list, embeddings, file_mtime) + return entries_list, embeddings + + +def _pattern_hit_count(entry: dict[str, Any], text: str) -> int: + """Count how many pattern alternatives appear in text.""" + patterns = entry.get("patterns") or [] + return sum(1 for p in patterns if str(p).lower() in text) + + +def _keyword_normalized(entry: dict[str, Any], text: str) -> float: + """Pattern OR evidence in {0.0, 1.0}.""" + return 1.0 if _pattern_hit_count(entry, text) > 0 else 0.0 + + +def _score( + entry: dict[str, Any], + error_message: str, + pass_name: str, + config_context: str, + *, + semantic_score: float = 0.0, +) -> float: + """Hybrid score: 0.6 * semantic + 0.4 * keyword_OR + small multi-hit bonus. + + Keyword text includes pass_name/config_context for pattern matching. + Semantic scores should be computed from error_message alone. + Empty error_message must not be scored via pass_name alone (callers + short-circuit before match); if called anyway, keyword on empty body + alone yields 0 when pass/context are excluded. + """ + error_only = (error_message or "").strip() + if not error_only: + return 0.0 + text = f"{error_message} {pass_name or ''} {config_context or ''}".lower() - return sum(1 for p in entry.get("patterns", []) if p.lower() in text) + hits = _pattern_hit_count(entry, text) + keyword = 1.0 if hits > 0 else 0.0 + semantic = float(semantic_score) if float(semantic_score) >= DEFAULT_THRESHOLD else 0.0 + bonus = _HIT_RANK_BONUS * min(hits, _HIT_RANK_BONUS_CAP) + return _SEMANTIC_WEIGHT * semantic + _KEYWORD_WEIGHT * keyword + bonus MAX_RELEVANT_QUIRKS = 20 @@ -108,7 +237,6 @@ def _score(entry: dict[str, Any], error_message: str, pass_name: str, config_con "multi-pass-cache-overwrite": ["pass_ordering", "quantization", "onnx_export"], "search-local-optima": ["pass_ordering"], "torchscript-export-fail": ["onnx_export"], - # New olive-domain entries "olive-module-not-found": ["pass_ordering"], "olive-ort-cuda-ep-missing": ["hardware"], "olive-hf-auth-401": ["pass_ordering"], @@ -121,7 +249,6 @@ def _score(entry: dict[str, Any], error_message: str, pass_name: str, config_con "olive-ssl-huggingface": ["pass_ordering"], "olive-pass-config-validation": ["pass_ordering"], "olive-accelerator-device-busy": ["hardware", "quantization"], - # Studio-domain entries "studio-pytorch-hf-config": ["studio", "onnx_export"], "studio-apply-fix-empty": ["studio"], "studio-venv-mcp-pin": ["studio"], @@ -143,17 +270,7 @@ def _score(entry: dict[str, Any], error_message: str, pass_name: str, config_con def _infer_quirk_categories(entry_id: str | None, pass_name: str, domain: str | None) -> set[str]: - """ - Infer relevant quirk categories from the matched entry, domain, and pass name. - - Parameters: - entry_id (str | None): Identifier of the matched knowledge-base entry. - pass_name (str): Name of the processing pass associated with the error. - domain (str | None): Troubleshooting domain used to select domain-specific categories. - - Returns: - set[str]: Inferred quirk categories, including applicable default categories when no specific categories match. - """ + """Infer relevant quirk categories from the matched entry, domain, and pass name.""" categories: set[str] = set() if entry_id: @@ -178,7 +295,11 @@ def _infer_quirk_categories(entry_id: str | None, pass_name: str, domain: str | categories.add("studio") if not categories: - categories = {"pass_ordering", "quantization", "studio"} if domain == "studio" else {"pass_ordering", "quantization"} + categories = ( + {"pass_ordering", "quantization", "studio"} + if domain == "studio" + else {"pass_ordering", "quantization"} + ) return categories @@ -188,17 +309,7 @@ def _build_relevant_quirks( pass_name: str, domain: str | None = None, ) -> list[str]: - """ - Builds a deduplicated list of relevant quirk titles for an error context. - - Parameters: - entry_id (str | None): Knowledge-base entry identifier associated with the error. - pass_name (str): Name of the processing pass associated with the error. - domain (str | None): Troubleshooting domain used to infer relevant quirk categories. - - Returns: - list[str]: Relevant quirk titles, limited to the configured maximum. - """ + """Build a deduplicated list of relevant quirk titles for an error context.""" categories = _infer_quirk_categories(entry_id, pass_name, domain) quirks_db = load_quirks() titles: list[str] = [] @@ -220,12 +331,11 @@ def _build_relevant_quirks( def _pool_for_domain(domain: DomainName) -> list[dict[str, Any]]: - """Load troubleshooting entries for the requested domain only (auto loads both, Olive first).""" + """Load troubleshooting entries for the requested domain only.""" if domain == "olive": return load_troubleshooting() if domain == "studio": return load_studio_troubleshooting() - # auto: olive first for stable olive-first scoring when ties break by search order return load_troubleshooting() + load_studio_troubleshooting() @@ -234,37 +344,47 @@ def _best_match( error_message: str, pass_name: str, config_context: str, -) -> tuple[dict[str, Any] | None, int]: - """Selects the highest-scoring troubleshooting entry for the provided error context. - - Parameters: - entries (list[dict[str, Any]]): Candidate troubleshooting entries. - error_message (str): Error message to match. - pass_name (str): Pass associated with the error. - config_context (str): Configuration context associated with the error. - - Returns: - tuple[dict[str, Any] | None, int]: The best matching entry and its score, or `(None, 0)` when no entry matches. +) -> tuple[dict[str, Any] | None, float]: + """Select the highest-scoring troubleshooting entry (hybrid semantic+keyword). + + Empty/whitespace error_message never matches — pass_name/config_context alone + must not diagnose (pattern-token pass names like TensorRT/AWQ). """ if not entries: - return None, 0 - scored = [(entry, _score(entry, error_message, pass_name, config_context)) for entry in entries] - scored.sort(key=lambda x: x[1], reverse=True) - best_entry, best_score = scored[0] + return None, 0.0 + + error_only = (error_message or "").strip() + if not error_only: + return None, 0.0 + + try: + index_entries, embeddings = _get_troubleshooting_index(entries) + query_vec = encode_query(error_only) + semantic_scores = cosine_similarity_scores(query_vec, embeddings) + # Prefer the index pair for position-aligned scoring. + score_entries = index_entries + except Exception: # noqa: BLE001 + score_entries = list(entries) + semantic_scores = np.zeros((len(score_entries),), dtype=np.float32) + + keyword_text = f"{error_message} {pass_name or ''} {config_context or ''}".lower() + scored: list[tuple[dict[str, Any], float, int]] = [] + for i, entry in enumerate(score_entries): + sem = float(semantic_scores[i]) if i < len(semantic_scores) else 0.0 + hybrid = _score( + entry, error_message, pass_name, config_context, semantic_score=sem + ) + hits = _pattern_hit_count(entry, keyword_text) + scored.append((entry, hybrid, hits)) + scored.sort(key=lambda x: (x[1], x[2]), reverse=True) + best_entry, best_score, _hits = scored[0] if best_score <= 0: - return None, 0 + return None, 0.0 return best_entry, best_score def _resolve_domain(domain: str | None) -> DomainName: - """Resolve a requested troubleshooting domain to a supported domain. - - Parameters: - domain (str | None): The requested domain name. - - Returns: - DomainName: The requested domain when supported; otherwise, ``"auto"``. - """ + """Resolve a requested troubleshooting domain to a supported domain.""" if domain in ("olive", "studio", "auto"): return domain # type: ignore[return-value] return "auto" @@ -293,22 +413,46 @@ def troubleshoot_olive_error( config_context: str = "", domain: str = "auto", ) -> dict[str, Any]: - """ - Diagnose an Olive or Olive Studio error using the selected knowledge base. - + """Diagnose an Olive or Olive Studio error using the selected knowledge base. + Args: error_message: Error message or traceback snippet to diagnose. pass_name: Name of the pass where the error occurred, if known. config_context: Additional configuration context used for matching. domain: Knowledge-base domain to search: ``"auto"``, ``"olive"``, or ``"studio"``. Invalid values default to ``"auto"``. - + Returns: A diagnosis containing the matched entry, domain, title, root cause, workaround, updated configuration, applicability, related entry, - relevant quirks, and occurrence frequency metadata. If no entry matches, - the response contains generic guidance and is marked non-applicable. + relevant quirks, and occurrence frequency metadata. """ + # Empty body: never match from pass_name/config_context alone (TensorRT/AWQ/…). + if not (error_message or "").strip(): + best = _no_match_payload() + matched_entry = None + matched_domain = None + applyable = False + freq_key = _get_frequency_key(matched_entry, error_message) + freq = _record_occurrence(freq_key) + return { + "matched_entry": matched_entry, + "domain": matched_domain, + "applyable": applyable, + "title": best["title"], + "root_cause": best["root_cause"], + "workaround": best["solution"], + "updated_config": best["updated_config"], + "relevant_quirks": _build_relevant_quirks(matched_entry, pass_name, matched_domain), + "related_olive_entry": None, + "frequency": { + "occurrence_count": freq["occurrence_count"], + "first_seen": _format_ts(freq["first_seen"]), + "last_seen": _format_ts(freq["last_seen"]), + "label": _frequency_label(freq["occurrence_count"]), + }, + } + resolved = _resolve_domain(domain) best: dict[str, Any] | None = None @@ -351,7 +495,6 @@ def troubleshoot_olive_error( freq_key = _get_frequency_key(matched_entry, error_message) freq = _record_occurrence(freq_key) - # Keep updated_config for display even when applyable is false (UI Apply stays gated by applyable). updated_config = best.get("updated_config", {}) or {} return { @@ -379,18 +522,7 @@ def diagnose_error( config_context: str = "", domain: str = "auto", ) -> dict[str, Any]: - """ - Diagnose an Olive or Olive Studio error using the configured knowledge base. - - Parameters: - error_message (str): The error message to diagnose - pass_name (str): The processing pass associated with the error - config_context (str): Configuration context relevant to the error - domain (str): The domain to search: "auto", "olive", or "studio" - - Returns: - dict[str, Any]: Diagnosis details, including the root cause, workaround, applicability, relevant quirks, and frequency metadata - """ + """Alias for troubleshoot_olive_error.""" return troubleshoot_olive_error( error_message=error_message, pass_name=pass_name, @@ -406,18 +538,7 @@ def reset_frequency_store() -> None: def get_error_frequency_summary(limit: int = 10) -> dict[str, Any]: - """ - Summarize tracked errors by occurrence frequency. - - Parameters: - limit (int): Maximum number of error entries to include. Must be greater than or equal to zero. - - Returns: - dict[str, Any]: A summary containing the total tracked count, requested limit, and error entries with occurrence counts, timestamps, frequency labels, and identifiers. - - Raises: - ValueError: If `limit` is negative. - """ + """Summarize tracked errors by occurrence frequency.""" if limit < 0: raise ValueError("limit must be non-negative") diff --git a/olive-mcp-server/pyproject.toml b/olive-mcp-server/pyproject.toml index a03d307c..155b711f 100644 --- a/olive-mcp-server/pyproject.toml +++ b/olive-mcp-server/pyproject.toml @@ -11,6 +11,8 @@ dependencies = [ "mcp>=1.0.0,<2", "requests>=2.32.0", "beautifulsoup4>=4.12.0", + "sentence-transformers>=3.0.0", + "numpy>=1.24.0", ] [project.optional-dependencies] diff --git a/olive-mcp-server/tests/test_docs_search_semantic.py b/olive-mcp-server/tests/test_docs_search_semantic.py new file mode 100644 index 00000000..089b5b88 --- /dev/null +++ b/olive-mcp-server/tests/test_docs_search_semantic.py @@ -0,0 +1,252 @@ +"""Tests for semantic upgrade of search_olive_documentation.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from olive_mcp_server.tools import docs_search +from olive_mcp_server.tools.docs_search import search_olive_documentation + + +@pytest.fixture(autouse=True) +def _reset_kb_index_cache(): + """Ensure each test starts with a clean KB embedding cache.""" + docs_search._KB_TEXTS = [] + docs_search._KB_EMBEDDINGS = None + docs_search._KB_INDEX_MTIME = -1.0 + yield + docs_search._KB_TEXTS = [] + docs_search._KB_EMBEDDINGS = None + docs_search._KB_INDEX_MTIME = -1.0 + + +def _install_fake_semantic( + monkeypatch: pytest.MonkeyPatch, + *, + results_for_query: dict[str, list] | None = None, + default_results: list | None = None, +): + """Mock semantic_search and index build so tests need no real model.""" + + def fake_build(texts): + n = len(list(texts)) if texts else 0 + return np.zeros((n, 384), dtype=np.float32) + + def fake_semantic(query, kb_texts, kb_embeddings, top_k, threshold=0.30): + if results_for_query and query in results_for_query: + return results_for_query[query][:top_k] + if default_results is not None: + return default_results[:top_k] + return [] + + monkeypatch.setattr(docs_search, "build_kb_index", fake_build) + monkeypatch.setattr(docs_search, "semantic_search", fake_semantic) + + +def test_fuzzy_query_finds_quantization_related(monkeypatch: pytest.MonkeyPatch): + """Semantic hits for a fuzzy quantization query should surface.""" + fake_hits = [ + { + "source": "passes.OnnxQuantization.description", + "snippet": "Static quantization with calibration data.", + "relevance": 0.72, + }, + { + "source": "quirks.quantization[0].title", + "snippet": "Use representative calibration samples.", + "relevance": 0.61, + }, + ] + _install_fake_semantic( + monkeypatch, + default_results=fake_hits, + ) + + result = search_olive_documentation( + query="how do I reduce model size with int8", + top_k=3, + live=False, + ) + assert result["count"] > 0 + assert result["query"] == "how do I reduce model size with int8" + sources = " ".join(r["source"] for r in result["results"]).lower() + snippets = " ".join(r["snippet"] for r in result["results"]).lower() + assert "quant" in sources or "quant" in snippets or "calibration" in snippets + + +def test_keyword_fallback_when_semantic_empty(monkeypatch: pytest.MonkeyPatch): + """When semantic returns nothing above threshold, keyword fallback runs.""" + _install_fake_semantic(monkeypatch, default_results=[]) + + result = search_olive_documentation( + query="calibration data", + top_k=3, + live=False, + ) + assert result["count"] > 0 + assert len(result["results"]) <= 3 + # Keyword relevance is normalized to [0, 1] + assert all(isinstance(r["relevance"], (int, float)) for r in result["results"]) + assert all(0.0 < float(r["relevance"]) <= 1.0 for r in result["results"]) + + +def test_keyword_fallback_when_semantic_raises(monkeypatch: pytest.MonkeyPatch): + def boom(*_a, **_k): + raise RuntimeError("model unavailable") + + monkeypatch.setattr(docs_search, "get_or_build_kb_index", boom) + + result = search_olive_documentation( + query="calibration data", + top_k=3, + live=False, + ) + assert result["count"] > 0 + + +def test_kb_mtime_invalidation_rebuilds_index(monkeypatch: pytest.MonkeyPatch): + """Changing the tracked mtime must force a rebuild of embeddings.""" + build_calls: list[int] = [] + + sample_texts = [ + ("passes.foo", "quantization calibration"), + ("passes.bar", "onnx conversion"), + ] + + def fake_load(): + return list(sample_texts) + + def fake_build(texts): + build_calls.append(len(list(texts))) + return np.ones((len(list(texts)), 384), dtype=np.float32) + + def fake_semantic(query, kb_texts, kb_embeddings, top_k, threshold=0.30): + return [ + { + "source": kb_texts[0][0], + "snippet": kb_texts[0][1][:300], + "relevance": 0.9, + } + ][:top_k] + + monkeypatch.setattr(docs_search, "_load_kb_text", fake_load) + monkeypatch.setattr(docs_search, "build_kb_index", fake_build) + monkeypatch.setattr(docs_search, "semantic_search", fake_semantic) + + # First build + monkeypatch.setattr(docs_search, "_kb_max_mtime", lambda: 100.0) + docs_search._search_local("quantization", 3) + assert len(build_calls) == 1 + + # Same mtime → cache hit + docs_search._search_local("quantization", 3) + assert len(build_calls) == 1 + + # mtime change → rebuild + monkeypatch.setattr(docs_search, "_kb_max_mtime", lambda: 200.0) + docs_search._search_local("quantization", 3) + assert len(build_calls) == 2 + + +def test_empty_query_unchanged(): + result = search_olive_documentation(query=" ", top_k=5, live=False) + assert result["count"] == 0 + assert result["results"] == [] + assert "Empty query" in result["note"] + + +def test_return_shape_preserved(monkeypatch: pytest.MonkeyPatch): + _install_fake_semantic( + monkeypatch, + default_results=[ + {"source": "x", "snippet": "y", "relevance": 0.5}, + ], + ) + result = search_olive_documentation(query="quantization", top_k=2, live=False) + assert set(result.keys()) == {"query", "count", "results", "note"} + for r in result["results"]: + assert set(r.keys()) >= {"source", "snippet", "relevance"} + + +def test_kb_stale_build_does_not_poison_cache(monkeypatch: pytest.MonkeyPatch): + """If mtime advances mid-build, do not stamp stale texts with the new mtime.""" + sample_old = [("old.path", "old calibration text")] + sample_new = [("new.path", "new calibration text")] + mtime_box = {"v": 100.0} + load_calls: list[str] = [] + + def fake_mtime(): + return mtime_box["v"] + + def fake_load(): + if mtime_box["v"] >= 200.0: + load_calls.append("new") + return list(sample_new) + load_calls.append("old") + return list(sample_old) + + def fake_build(texts): + texts = list(texts) + # Simulate hot-reload while encoding. + mtime_box["v"] = 200.0 + return np.ones((len(texts), 384), dtype=np.float32) + + monkeypatch.setattr(docs_search, "_kb_max_mtime", fake_mtime) + monkeypatch.setattr(docs_search, "_load_kb_text", fake_load) + monkeypatch.setattr(docs_search, "build_kb_index", fake_build) + + texts1, _emb1 = docs_search.get_or_build_kb_index() + # Stale build returned locally but must not poison global cache at mtime 200. + assert texts1[0][0] == "old.path" + assert docs_search._KB_INDEX_MTIME != 200.0 or docs_search._KB_TEXTS[0][0] != "old.path" + + # Next call with mtime 200 should load fresh content and cache it. + texts2, _emb2 = docs_search.get_or_build_kb_index() + assert texts2[0][0] == "new.path" + assert docs_search._KB_INDEX_MTIME == 200.0 + assert docs_search._KB_TEXTS[0][0] == "new.path" + + +def test_live_fetch_generation_ignores_stale_completion(monkeypatch: pytest.MonkeyPatch): + """Older in-flight fetch must not overwrite a newer generation's cache.""" + docs_search._LIVE_CACHE = {} + docs_search._LAST_FETCH_TIME = 0.0 + docs_search._LIVE_FETCH_GENERATION = 0 + + results_queue = [ + {"status": "ok", "pages": {"index": "OLDER live page content calibration"}}, + {"status": "ok", "pages": {"index": "NEWER live page content calibration"}}, + ] + call_i = {"n": 0} + + def fake_fetch(pages=None): + # First call is gen 1 (older), second is gen 2 (newer) — complete out of order. + i = call_i["n"] + call_i["n"] += 1 + return results_queue[min(i, len(results_queue) - 1)] + + # Patch the lazy import path used inside _fetch_live_docs. + import olive_mcp_server.fetchers.official_docs_fetcher as fetcher + + monkeypatch.setattr(fetcher, "fetch_official_docs", fake_fetch) + + # Start gen1 and gen2 by forcing TTL miss; manually exercise publish races. + with docs_search._LIVE_FETCH_LOCK: + docs_search._LIVE_FETCH_GENERATION = 1 + gen1 = 1 + docs_search._LIVE_FETCH_GENERATION = 2 + gen2 = 2 + + # Apply gen2 first (newer). + with docs_search._LIVE_FETCH_LOCK: + if gen2 == docs_search._LIVE_FETCH_GENERATION: + docs_search._LIVE_CACHE = {"index": "NEWER"} + docs_search._LAST_FETCH_TIME = 999.0 + # Stale gen1 must not overwrite. + with docs_search._LIVE_FETCH_LOCK: + if gen1 == docs_search._LIVE_FETCH_GENERATION: + docs_search._LIVE_CACHE = {"index": "OLDER"} + docs_search._LAST_FETCH_TIME = 1000.0 + + assert docs_search._LIVE_CACHE == {"index": "NEWER"} diff --git a/olive-mcp-server/tests/test_embeddings.py b/olive-mcp-server/tests/test_embeddings.py new file mode 100644 index 00000000..d3851a47 --- /dev/null +++ b/olive-mcp-server/tests/test_embeddings.py @@ -0,0 +1,153 @@ +"""Unit tests for olive_mcp_server.tools.embeddings.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from olive_mcp_server.tools import embeddings as emb + + +def test_lazy_loading_model_not_loaded_at_import(): + """Importing the module must not load the SentenceTransformer model.""" + import subprocess + import sys + + # Fresh interpreter: import package graph without calling encode. + code = ( + "from olive_mcp_server.tools import embeddings as e; " + "from olive_mcp_server.tools import docs_search as d; " # noqa: F841 + "assert e.is_model_loaded() is False, 'model loaded at import'" + ) + proc = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, proc.stderr or proc.stdout + assert hasattr(emb, "_model") + assert callable(emb.is_model_loaded) + + +def test_cosine_identity(): + """Identical vectors should have cosine similarity ~1.0.""" + v = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32) + mat = np.stack([v, v * 2.0]) # second row is collinear → also ~1.0 + scores = emb.cosine_similarity_scores(v, mat) + assert scores.shape == (2,) + assert scores[0] == pytest.approx(1.0, abs=1e-5) + assert scores[1] == pytest.approx(1.0, abs=1e-5) + + +def test_cosine_orthogonal(): + a = np.array([1.0, 0.0], dtype=np.float32) + b = np.array([[0.0, 1.0], [1.0, 0.0]], dtype=np.float32) + scores = emb.cosine_similarity_scores(a, b) + assert scores[0] == pytest.approx(0.0, abs=1e-5) + assert scores[1] == pytest.approx(1.0, abs=1e-5) + + +def test_cosine_empty_index(): + q = np.ones((4,), dtype=np.float32) + empty = np.zeros((0, 4), dtype=np.float32) + scores = emb.cosine_similarity_scores(q, empty) + assert scores.shape == (0,) + + +def test_cosine_zero_query(): + q = np.zeros((3,), dtype=np.float32) + mat = np.ones((2, 3), dtype=np.float32) + scores = emb.cosine_similarity_scores(q, mat) + assert scores.shape == (2,) + assert np.allclose(scores, 0.0) + + +def test_threshold_filtering(): + """semantic_search must drop entries below threshold.""" + kb_texts = [ + ("src_a", "alpha document about apples"), + ("src_b", "beta document about bananas"), + ("src_c", "gamma document about grapes"), + ] + # Hand-crafted embeddings: query aligns strongly with row 0 only. + # Note: L2-normalization is applied before cosine, so collinear rows + # (e.g. [0.2,0,0] vs [1,0,0]) would both score 1.0 — use true angles. + index = np.array( + [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.3, 0.9539, 0.0], # cosine with [1,0,0] ≈ 0.30 < 0.50 threshold + ], + dtype=np.float32, + ) + + def fake_encode_query(_query: str) -> np.ndarray: + return np.array([1.0, 0.0, 0.0], dtype=np.float32) + + original = emb.encode_query + emb.encode_query = fake_encode_query # type: ignore[assignment] + try: + results = emb.semantic_search( + "apples", + kb_texts, + index, + top_k=5, + threshold=0.50, + ) + finally: + emb.encode_query = original # type: ignore[assignment] + + assert len(results) == 1 + assert results[0]["source"] == "src_a" + assert results[0]["relevance"] == pytest.approx(1.0, abs=1e-5) + assert "snippet" in results[0] + + +def test_semantic_search_empty_index(): + results = emb.semantic_search( + "anything", + [], + np.zeros((0, 384), dtype=np.float32), + top_k=5, + ) + assert results == [] + + +def test_semantic_search_empty_query(): + kb_texts = [("s", "text")] + index = np.ones((1, 4), dtype=np.float32) + assert emb.semantic_search("", kb_texts, index, top_k=3) == [] + assert emb.semantic_search(" ", kb_texts, index, top_k=3) == [] + + +def test_encode_texts_empty(): + out = emb.encode_texts([]) + assert out.shape == (0, emb.EMBEDDING_DIM) + assert out.dtype == np.float32 + + +def test_encode_shape_mocked(monkeypatch: pytest.MonkeyPatch): + """encode_texts returns (N, 384) when the model is mocked.""" + + class FakeModel: + def encode(self, texts, **_kwargs): + return np.random.randn(len(texts), emb.EMBEDDING_DIM).astype(np.float32) + + monkeypatch.setattr(emb, "_model", FakeModel()) + out = emb.encode_texts(["hello", "world"]) + assert out.shape == (2, emb.EMBEDDING_DIM) + assert out.dtype == np.float32 + + q = emb.encode_query("hello") + assert q.shape == (emb.EMBEDDING_DIM,) + + +def test_build_kb_index_mocked(monkeypatch: pytest.MonkeyPatch): + class FakeModel: + def encode(self, texts, **_kwargs): + return np.ones((len(texts), emb.EMBEDDING_DIM), dtype=np.float32) + + monkeypatch.setattr(emb, "_model", FakeModel()) + mat = emb.build_kb_index(["a", "b", "c"]) + assert mat.shape == (3, emb.EMBEDDING_DIM) diff --git a/olive-mcp-server/tests/test_integration.py b/olive-mcp-server/tests/test_integration.py index 7cf5697d..49e34be9 100644 --- a/olive-mcp-server/tests/test_integration.py +++ b/olive-mcp-server/tests/test_integration.py @@ -11,23 +11,14 @@ def _run(coro): def test_server_lists_all_tools(): + from olive_mcp_server.mcp_server import _TOOL_IMPORTS + tools = _run(mcp.list_tools()) names = {t.name for t in tools} - expected = { - "get_olive_passes", - "get_pass_config_template", - "get_quantization_strategy", - "get_hardware_optimization_guide", - "get_pass_chain", - "troubleshoot_olive_error", - "get_model_compatibility", - "get_cli_command", - "get_data_config_template", - "search_olive_documentation", - "get_pass_parameters", - "evaluate_optimization_tradeoff", - } + expected = set(_TOOL_IMPORTS.keys()) assert expected <= names + assert "get_context_for_pipeline" in names + assert "diagnose_error" in names def test_get_olive_passes_via_server(): diff --git a/olive-mcp-server/tests/test_passive_context.py b/olive-mcp-server/tests/test_passive_context.py new file mode 100644 index 00000000..521f2c68 --- /dev/null +++ b/olive-mcp-server/tests/test_passive_context.py @@ -0,0 +1,145 @@ +"""Tests for get_context_for_pipeline passive context tool.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from olive_mcp_server.tools import docs_search +from olive_mcp_server.tools.passive_context import get_context_for_pipeline + + +@pytest.fixture(autouse=True) +def _reset_kb_cache(): + docs_search._KB_TEXTS = [] + docs_search._KB_EMBEDDINGS = None + docs_search._KB_INDEX_MTIME = -1.0 + yield + docs_search._KB_TEXTS = [] + docs_search._KB_EMBEDDINGS = None + docs_search._KB_INDEX_MTIME = -1.0 + + +def test_empty_pipeline(): + result = get_context_for_pipeline(pipeline_passes=[], top_k=5) + assert result["snippet_count"] == 0 + assert result["context_snippets"] == [] + assert result["confidence"] == 0.0 + assert "pipeline_summary" in result + + +def test_empty_pipeline_none(): + result = get_context_for_pipeline(pipeline_passes=None, top_k=5) + assert result["snippet_count"] == 0 + assert result["confidence"] == 0.0 + + +def test_quantization_pipeline_returns_relevant_snippets(monkeypatch: pytest.MonkeyPatch): + fake_results = [ + { + "source": "passes.OnnxQuantization", + "snippet": "Post-training static quantization guidance.", + "relevance": 0.77, + }, + { + "source": "quirks.quantization", + "snippet": "Calibration sample selection tips.", + "relevance": 0.65, + }, + ] + + def fake_index(): + texts = [("a", "quant"), ("b", "other")] + return texts, np.zeros((2, 384), dtype=np.float32) + + def fake_semantic(query, kb_texts, kb_embeddings, top_k, threshold=0.30): + assert "OnnxQuantization" in query or "quant" in query.lower() + return fake_results[:top_k] + + monkeypatch.setattr( + "olive_mcp_server.tools.passive_context.get_or_build_kb_index", + fake_index, + ) + monkeypatch.setattr( + "olive_mcp_server.tools.passive_context.semantic_search", + fake_semantic, + ) + + result = get_context_for_pipeline( + pipeline_passes=["OnnxConversion", "OnnxQuantization"], + model_name="phi-4", + target_hardware="NVIDIA RTX 4090", + top_k=5, + ) + assert result["snippet_count"] == 2 + assert len(result["context_snippets"]) == 2 + assert 0.0 <= result["confidence"] <= 1.0 + assert result["confidence"] == pytest.approx((0.77 + 0.65) / 2) + assert "OnnxQuantization" in result["pipeline_summary"] + assert "phi-4" in result["pipeline_summary"] + + +def test_confidence_bounded_0_1(monkeypatch: pytest.MonkeyPatch): + def fake_index(): + return [("s", "t")], np.ones((1, 384), dtype=np.float32) + + def fake_semantic(*_a, **_k): + # Even if relevance is slightly out of range, API clamps confidence. + return [{"source": "s", "snippet": "t", "relevance": 1.2}] + + monkeypatch.setattr( + "olive_mcp_server.tools.passive_context.get_or_build_kb_index", + fake_index, + ) + monkeypatch.setattr( + "olive_mcp_server.tools.passive_context.semantic_search", + fake_semantic, + ) + + result = get_context_for_pipeline( + pipeline_passes=[{"name": "OnnxQuantization", "type": "quantization"}], + top_k=3, + ) + assert 0.0 <= result["confidence"] <= 1.0 + + +def test_dict_and_string_pass_descriptors(monkeypatch: pytest.MonkeyPatch): + seen_query: dict[str, str] = {} + + def fake_index(): + return [("s", "t")], np.ones((1, 384), dtype=np.float32) + + def fake_semantic(query, *_a, **_k): + seen_query["q"] = query + return [{"source": "s", "snippet": "t", "relevance": 0.5}] + + monkeypatch.setattr( + "olive_mcp_server.tools.passive_context.get_or_build_kb_index", + fake_index, + ) + monkeypatch.setattr( + "olive_mcp_server.tools.passive_context.semantic_search", + fake_semantic, + ) + + result = get_context_for_pipeline( + pipeline_passes=[ + "OnnxConversion", + {"name": "OnnxQuantization", "type": "quantization"}, + ], + top_k=2, + ) + assert result["snippet_count"] == 1 + assert "OnnxConversion" in seen_query["q"] + assert "OnnxQuantization" in seen_query["q"] + assert "quantization" in seen_query["q"] + + +def test_return_shape(): + result = get_context_for_pipeline(pipeline_passes=[], top_k=1) + assert set(result.keys()) == { + "context_snippets", + "pipeline_summary", + "confidence", + "snippet_count", + } diff --git a/olive-mcp-server/tests/test_troubleshooting_hybrid.py b/olive-mcp-server/tests/test_troubleshooting_hybrid.py new file mode 100644 index 00000000..289d1867 --- /dev/null +++ b/olive-mcp-server/tests/test_troubleshooting_hybrid.py @@ -0,0 +1,379 @@ +"""Tests for hybrid semantic+keyword scoring in troubleshoot_olive_error.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from olive_mcp_server.tools import troubleshooting as ts +from olive_mcp_server.tools.troubleshooting import ( + reset_frequency_store, + troubleshoot_olive_error, +) + + +@pytest.fixture(autouse=True) +def _clean_state(): + reset_frequency_store() + # Clear embedding index cache between tests + ts._ts_index_cache = {} + yield + reset_frequency_store() + ts._ts_index_cache = {} + + +def _mock_embeddings( + monkeypatch: pytest.MonkeyPatch, + *, + scores_by_entry_id: dict[str, float] | None = None, + default_score: float = 0.0, +): + """Make cosine scores deterministic without loading the real model.""" + + def fake_index(entries=None): + if entries is None: + from olive_mcp_server.tools import load_troubleshooting + + entries = load_troubleshooting() + entries_list = list(entries) + n = len(entries_list) + embeddings = np.zeros((n, 384), dtype=np.float32) + # Stash for cosine lookup by this pool's fingerprint key + fake_index._last_entries = entries_list # type: ignore[attr-defined] + return entries_list, embeddings + + def fake_encode_query(query: str) -> np.ndarray: + if not query or not str(query).strip(): + return np.zeros((384,), dtype=np.float32) + return np.ones((384,), dtype=np.float32) + + def fake_cosine(query_vec, index_matrix): + entries = getattr(fake_index, "_last_entries", []) or [] + n = ( + int(index_matrix.shape[0]) + if index_matrix is not None and getattr(index_matrix, "size", 0) + else len(entries) + ) + if query_vec is None or float(np.linalg.norm(query_vec)) == 0.0: + return np.zeros((n,), dtype=np.float32) + out = np.full((n,), default_score, dtype=np.float32) + for i, entry in enumerate(list(entries)[:n]): + eid = entry.get("id", "") + if scores_by_entry_id and eid in scores_by_entry_id: + out[i] = scores_by_entry_id[eid] + return out + + monkeypatch.setattr(ts, "_get_troubleshooting_index", fake_index) + monkeypatch.setattr(ts, "encode_query", fake_encode_query) + monkeypatch.setattr(ts, "cosine_similarity_scores", fake_cosine) + + +def test_semantic_match_without_exact_pattern(monkeypatch: pytest.MonkeyPatch): + """High semantic score should match even when no pattern substring hits.""" + _mock_embeddings( + monkeypatch, + scores_by_entry_id={"oom-quantization": 0.85}, + default_score=0.05, + ) + + # Avoid exact pattern hits for oom-quantization; use paraphrased wording. + result = troubleshoot_olive_error( + error_message="Process killed while running weight-only packing due to insufficient device memory", + pass_name="OnnxQuantization", + ) + assert result["matched_entry"] == "oom-quantization" + assert "root_cause" in result + assert "workaround" in result + + +def test_paraphrased_oom_realistic_score_vector(monkeypatch: pytest.MonkeyPatch): + """Regression: realistic MiniLM-like scores must rank oom-quantization first. + + Freezes approximate cosine values observed when encoding error_message only + (without pass_name contamination). + """ + _mock_embeddings( + monkeypatch, + scores_by_entry_id={ + "oom-quantization": 0.4037, + "onnx-export-external-data": 0.3113, + "int4-perplexity": 0.1989, + "openvino-fallback": 0.1912, + "ep-fallback-cpu": 0.1544, + }, + default_score=0.10, + ) + result = troubleshoot_olive_error( + error_message=( + "Process killed while running weight-only packing " + "due to insufficient device memory" + ), + pass_name="OnnxQuantization", + ) + assert result["matched_entry"] == "oom-quantization" + + +@pytest.mark.parametrize( + "pass_name", + [ + "OnnxQuantization", + "TensorRT", + "AWQ", + "QNN", + "LoRA", + "OpenVINO", + ], +) +def test_empty_error_with_pass_name_no_match( + monkeypatch: pytest.MonkeyPatch, + pass_name: str, +): + """Empty error_message must not match from pass_name alone (incl. pattern tokens).""" + _mock_embeddings( + monkeypatch, + scores_by_entry_id={ + "ep-fallback-cpu": 0.90, + "oom-quantization": 0.85, + "tensorrt-build-slow": 0.95, + "awq-slow-calibration": 0.95, + "qnn-layer-not-supported": 0.95, + "lora-target-modules": 0.95, + "openvino-fallback": 0.95, + }, + default_score=0.50, + ) + result = troubleshoot_olive_error( + error_message="", + pass_name=pass_name, + ) + assert result["matched_entry"] is None + assert result["title"] == "No exact match found" + + # Whitespace-only is also empty for matching purposes. + result_ws = troubleshoot_olive_error(error_message=" \t", pass_name=pass_name) + assert result_ws["matched_entry"] is None + + +def test_weak_error_with_pass_name_no_false_positive(monkeypatch: pytest.MonkeyPatch): + """Weak error text + pass_name must not match via pass-name-driven cosine.""" + # Production encodes error_message only; mock returns low scores for weak text. + _mock_embeddings(monkeypatch, default_score=0.12) + result = troubleshoot_olive_error( + error_message="hello world error", + pass_name="OnnxQuantization", + ) + assert result["matched_entry"] is None + + +def test_exact_pattern_still_scores_high(monkeypatch: pytest.MonkeyPatch): + """Classic keyword/pattern match must still win (or at least match).""" + # Mild semantic noise on a wrong entry must not beat exact pattern OR=1.0. + _mock_embeddings( + monkeypatch, + scores_by_entry_id={"ep-fallback-cpu": 0.40}, + default_score=0.0, + ) + + result = troubleshoot_olive_error( + error_message="The ONNX model is larger than 2GB", + pass_name="OnnxConversion", + ) + assert result["matched_entry"] == "onnx-export-external-data" + assert "external" in result["workaround"].lower() + + +def test_keyword_or_not_diluted(): + """A single pattern hit among many is full keyword evidence (not hits/len).""" + entry = { + "patterns": [ + "never-match-alpha", + "never-match-beta", + "never-match-gamma", + "never-match-delta", + "2GB", + ], + "title": "t", + "root_cause": "r", + "solution": "s", + } + text = "model larger than 2GB".lower() + assert ts._keyword_normalized(entry, text) == 1.0 + # Not diluted to 1/5 — full OR keyword weight + one-hit bonus + score = ts._score(entry, "model larger than 2GB", "", "", semantic_score=0.0) + assert score == pytest.approx(0.4 * 1.0 + ts._HIT_RANK_BONUS * 1) + # Contrast: diluted formula would be 0.4 * (1/5) = 0.08 + assert score > 0.4 * (1 / 5) + 0.1 + + +def test_keyword_or_beats_mild_semantic(): + """Exact pattern hybrid must beat mild semantic-only neighbors (~0.21).""" + entry_kw = { + "id": "kw-hit", + "patterns": ["exact-unique-token-zz"], + "title": "keyword entry", + "root_cause": "r", + "solution": "s", + } + entry_sem = { + "id": "sem-only", + "patterns": ["never-matches-this"], + "title": "semantic entry", + "root_cause": "r", + "solution": "s", + } + kw = ts._score(entry_kw, "exact-unique-token-zz failed", "", "", semantic_score=0.0) + sem = ts._score(entry_sem, "exact-unique-token-zz failed", "", "", semantic_score=0.35) + assert kw >= 0.4 + assert sem == pytest.approx(0.6 * 0.35) + assert kw > sem + + +def test_response_shape_preserved(monkeypatch: pytest.MonkeyPatch): + _mock_embeddings(monkeypatch, default_score=0.0) + result = troubleshoot_olive_error( + error_message="The ONNX model is larger than 2GB", + ) + expected_keys = { + "matched_entry", + "title", + "root_cause", + "workaround", + "updated_config", + "relevant_quirks", + "frequency", + } + assert expected_keys <= set(result.keys()) + assert "occurrence_count" in result["frequency"] + assert "label" in result["frequency"] + assert "first_seen" in result["frequency"] + assert "last_seen" in result["frequency"] + + +def test_unknown_error_still_unmatched(monkeypatch: pytest.MonkeyPatch): + """Low semantic noise must not create false-positive matches.""" + _mock_embeddings(monkeypatch, default_score=0.15) # below DEFAULT_THRESHOLD 0.30 + + result = troubleshoot_olive_error( + error_message="Some random unique unknown failure message 12345", + ) + assert result["matched_entry"] is None + assert result["title"] == "No exact match found" + + +def test_score_returns_float(): + entry = { + "patterns": ["2GB", "external data"], + "title": "t", + "root_cause": "r", + "solution": "s", + } + score = ts._score( + entry, + "model larger than 2GB", + "", + "", + semantic_score=0.0, + ) + assert isinstance(score, float) + assert score > 0.0 + + +def test_hybrid_weights(): + """Both semantic and keyword components contribute to the score.""" + entry = { + "patterns": ["exact-token-xyz"], + "title": "t", + "root_cause": "r", + "solution": "s", + } + kw_only = ts._score(entry, "exact-token-xyz appeared", "", "", semantic_score=0.0) + sem_only = ts._score(entry, "totally different wording", "", "", semantic_score=0.80) + both = ts._score(entry, "exact-token-xyz appeared", "", "", semantic_score=0.80) + + assert kw_only == pytest.approx(0.4 * 1.0 + ts._HIT_RANK_BONUS) + assert sem_only == pytest.approx(0.6 * 0.80) + assert both == pytest.approx(0.6 * 0.80 + 0.4 * 1.0 + ts._HIT_RANK_BONUS) + assert both > kw_only + assert both > sem_only + + +def test_index_invalidates_on_reorder(monkeypatch: pytest.MonkeyPatch): + """Same-length reordered entries must rebuild embeddings (fingerprint).""" + from olive_mcp_server.tools import load_troubleshooting + + build_calls: list[int] = [] + + def counting_build(texts): + texts = list(texts) + build_calls.append(len(texts)) + n = len(texts) + mat = np.zeros((n, 384), dtype=np.float32) + for i in range(n): + mat[i, i % 384] = 1.0 + return mat + + monkeypatch.setattr(ts, "build_kb_index", counting_build) + monkeypatch.setattr(ts, "_troubleshooting_kb_mtime", lambda: 1.0) + + entries = load_troubleshooting() + e1, _emb1 = ts._get_troubleshooting_index(entries) + assert len(build_calls) == 1 + e2, _emb2 = ts._get_troubleshooting_index(entries) + assert len(build_calls) == 1 # cache hit + assert e1[0].get("id") == e2[0].get("id") + + reversed_entries = list(reversed(entries)) + e3, _emb3 = ts._get_troubleshooting_index(reversed_entries) + assert len(build_calls) == 2 # fingerprint changed + assert e3[0].get("id") == reversed_entries[0].get("id") + assert e3[0].get("id") != e1[0].get("id") or len(entries) <= 1 + + +def test_scoring_uses_index_entry_list(monkeypatch: pytest.MonkeyPatch): + """_best_match scores the entries returned with embeddings.""" + from olive_mcp_server.tools import load_troubleshooting + + base = load_troubleshooting() + custom = [ + { + "id": "custom-first", + "patterns": ["zz-unique-pattern-99"], + "title": "Custom first", + "root_cause": "custom root", + "solution": "custom solution", + "updated_config": {}, + "domain": "olive", + "applyable": False, + }, + *base, + ] + + def fake_index(entries=None): + mat = np.zeros((len(custom), 384), dtype=np.float32) + return custom, mat + + monkeypatch.setattr(ts, "_get_troubleshooting_index", fake_index) + monkeypatch.setattr(ts, "encode_query", lambda q: np.zeros((384,), dtype=np.float32)) + monkeypatch.setattr( + ts, + "cosine_similarity_scores", + lambda q, m: np.zeros((m.shape[0],), dtype=np.float32), + ) + + result = troubleshoot_olive_error(error_message="hit zz-unique-pattern-99 now") + assert result["matched_entry"] == "custom-first" + + +def test_real_minilm_paraphrased_oom_optional(): + """Real-model check when sentence-transformers is installed: paraphrased OOM.""" + pytest.importorskip("sentence_transformers") + ts._ts_index_cache = {} + + result = troubleshoot_olive_error( + error_message=( + "Process killed while running weight-only packing " + "due to insufficient device memory" + ), + pass_name="OnnxQuantization", + ) + assert result["matched_entry"] == "oom-quantization" From f94ee3260030f478ff4b1de80fffcfaa6a50b50b Mon Sep 17 00:00:00 2001 From: "qodo-code-review[bot]" <151058649+qodo-code-review[bot]@users.noreply.github.com> Date: Sat, 1 Aug 2026 14:29:45 +0000 Subject: [PATCH 02/15] fix: Snapshot live docs and fetch time atomically --- .../olive_mcp_server/tools/docs_search.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/olive-mcp-server/olive_mcp_server/tools/docs_search.py b/olive-mcp-server/olive_mcp_server/tools/docs_search.py index 3df58df7..f17f52a7 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -194,7 +194,7 @@ def _search_local(query: str, top_k: int) -> list[dict[str, Any]]: return _keyword_search(_load_kb_text(), terms, top_k) -def _fetch_live_docs() -> dict[str, str]: +def _fetch_live_docs() -> tuple[dict[str, str], float]: """Fetch (and cache) the live Olive docs landing page. Concurrent fetches take a generation token; only the latest generation may @@ -205,7 +205,7 @@ def _fetch_live_docs() -> dict[str, str]: with _LIVE_FETCH_LOCK: now = time.monotonic() if _LIVE_CACHE and (now - _LAST_FETCH_TIME) < _LIVE_CACHE_TTL_SECONDS: - return dict(_LIVE_CACHE) + return dict(_LIVE_CACHE), _LAST_FETCH_TIME _LIVE_FETCH_GENERATION += 1 my_generation = _LIVE_FETCH_GENERATION @@ -227,7 +227,7 @@ def _fetch_live_docs() -> dict[str, str]: pass # Keep stale cache or return empty on failure. with _LIVE_FETCH_LOCK: - return dict(_LIVE_CACHE) + return dict(_LIVE_CACHE), _LAST_FETCH_TIME def _split_live_snippets(pages: dict[str, str]) -> list[tuple[str, str]]: @@ -245,9 +245,7 @@ def _get_live_index() -> tuple[list[tuple[str, str]], np.ndarray]: """Return live snippets and their embeddings, rebuilding on cache refresh.""" global _LIVE_SNIPPETS, _LIVE_EMBEDDINGS, _LIVE_EMBED_CACHE_TIME - pages = _fetch_live_docs() - with _LIVE_FETCH_LOCK: - fetch_time = _LAST_FETCH_TIME + pages, fetch_time = _fetch_live_docs() with _LIVE_INDEX_LOCK: if ( @@ -296,7 +294,7 @@ def _search_live(query: str, top_k: int) -> list[dict[str, Any]]: return _keyword_search(snippets, terms, top_k) except Exception: # noqa: BLE001 try: - pages = _fetch_live_docs() + pages, _ = _fetch_live_docs() if not pages: return [] return _keyword_search(_split_live_snippets(pages), terms, top_k) From 7e4185e683f6e3defc0e0b4e32b808fa3afdbd35 Mon Sep 17 00:00:00 2001 From: "qodo-code-review[bot]" <151058649+qodo-code-review[bot]@users.noreply.github.com> Date: Sat, 1 Aug 2026 14:29:49 +0000 Subject: [PATCH 03/15] fix: Materialize text iterables before encoding --- olive-mcp-server/olive_mcp_server/tools/embeddings.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/olive-mcp-server/olive_mcp_server/tools/embeddings.py b/olive-mcp-server/olive_mcp_server/tools/embeddings.py index 73065400..9af95d30 100644 --- a/olive-mcp-server/olive_mcp_server/tools/embeddings.py +++ b/olive-mcp-server/olive_mcp_server/tools/embeddings.py @@ -7,7 +7,7 @@ from __future__ import annotations import threading -from typing import Any, Sequence +from typing import Any, Iterable import numpy as np @@ -37,18 +37,19 @@ def is_model_loaded() -> bool: return _model is not None -def encode_texts(texts: Sequence[str]) -> np.ndarray: +def encode_texts(texts: Iterable[str]) -> np.ndarray: """Encode a batch of texts into an (N, 384) float32 matrix. Rows are L2-normalized (``normalize_embeddings=True``). Callers may still pass the matrix through ``cosine_similarity_scores``, which re-normalizes safely for zero rows and non-normalized inputs. """ - if not texts: + texts_list = list(texts) if texts is not None else [] + if not texts_list: return np.zeros((0, EMBEDDING_DIM), dtype=np.float32) model = _get_model() embeddings = model.encode( - list(texts), + texts_list, convert_to_numpy=True, show_progress_bar=False, normalize_embeddings=True, From 57919e8f4e82561277277acf1474a21992de2445 Mon Sep 17 00:00:00 2001 From: "qodo-code-review[bot]" <151058649+qodo-code-review[bot]@users.noreply.github.com> Date: Sat, 1 Aug 2026 14:29:53 +0000 Subject: [PATCH 04/15] fix: Remove unused Path import --- olive-mcp-server/olive_mcp_server/tools/troubleshooting.py | 1 - 1 file changed, 1 deletion(-) diff --git a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py index fa0f7a8c..d5046379 100644 --- a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py +++ b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py @@ -10,7 +10,6 @@ import hashlib import threading import time -from pathlib import Path from typing import Any, Literal import numpy as np From d27dd9eb85e07493d087e7cb0075c443668abdc1 Mon Sep 17 00:00:00 2001 From: Anthony Thompson Date: Sat, 1 Aug 2026 07:34:54 -0700 Subject: [PATCH 05/15] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- olive-mcp-server/tests/test_integration.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/olive-mcp-server/tests/test_integration.py b/olive-mcp-server/tests/test_integration.py index 49e34be9..a8f6cab6 100644 --- a/olive-mcp-server/tests/test_integration.py +++ b/olive-mcp-server/tests/test_integration.py @@ -15,8 +15,9 @@ def test_server_lists_all_tools(): tools = _run(mcp.list_tools()) names = {t.name for t in tools} - expected = set(_TOOL_IMPORTS.keys()) - assert expected <= names + assert set(_TOOL_IMPORTS.keys()) <= names + required = {"get_olive_passes", "search_olive_documentation", "troubleshoot_olive_error"} + assert required <= names assert "get_context_for_pipeline" in names assert "diagnose_error" in names From 448d630b7929d0adc6f0cecb37ee24fa8dd95da1 Mon Sep 17 00:00:00 2001 From: Anthony Thompson Date: Sat, 1 Aug 2026 07:35:13 -0700 Subject: [PATCH 06/15] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- olive-mcp-server/olive_mcp_server/tools/docs_search.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/olive-mcp-server/olive_mcp_server/tools/docs_search.py b/olive-mcp-server/olive_mcp_server/tools/docs_search.py index f17f52a7..bd2adf31 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -188,10 +188,9 @@ def _search_local(query: str, top_k: int) -> list[dict[str, Any]]: ) if results: return results + return _keyword_search(kb_texts, terms, top_k) except Exception: # noqa: BLE001 - pass - - return _keyword_search(_load_kb_text(), terms, top_k) + return _keyword_search(_load_kb_text(), terms, top_k) def _fetch_live_docs() -> tuple[dict[str, str], float]: From c0786d9b50d10937544ed0b5a0a583b939cf54fe Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 07:39:07 -0700 Subject: [PATCH 07/15] fix: repair CI failures on PR #73 - Add cu130/cu132 to UIState.cudaVersion type to match auditAutofix's CUDA_VERSIONS set (TS2769 build failure) - Fix test_search_olive_documentation_with_live_source: _fetch_live_docs now returns (pages, fetch_time) tuple, test mock still returned bare dict Co-Authored-By: Claude Sonnet 5 --- olive-mcp-server/tests/test_tools.py | 5 ++++- src/types.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/olive-mcp-server/tests/test_tools.py b/olive-mcp-server/tests/test_tools.py index 9d2d3e73..1e25e0bc 100644 --- a/olive-mcp-server/tests/test_tools.py +++ b/olive-mcp-server/tests/test_tools.py @@ -166,7 +166,10 @@ def test_search_olive_documentation_with_live_source(monkeypatch: pytest.MonkeyP monkeypatch.setattr( docs_search, "_fetch_live_docs", - lambda: {"index": "Live docs mention calibration data and quantization."}, + lambda: ( + {"index": "Live docs mention calibration data and quantization."}, + 0.0, + ), ) result = search_olive_documentation(query="calibration data", top_k=3, live=True) assert result["count"] > 0 diff --git a/src/types.ts b/src/types.ts index 60ec6c97..850ec561 100644 --- a/src/types.ts +++ b/src/types.ts @@ -92,7 +92,7 @@ export interface UIState { /** Hugging Face load_kwargs device_map — GPU + host RAM when auto. */ memoryOffload: "gpu_only" | "auto"; /** Only tags with full dep resolution (torch index + ORT 1.26 + cu12 runtime). */ - cudaVersion: "auto" | "cpu" | "cu118" | "cu121" | "cu124" | "cu126" | "cu128"; + cudaVersion: "auto" | "cpu" | "cu118" | "cu121" | "cu124" | "cu126" | "cu128" | "cu130" | "cu132"; cacheDir: string; azureStr: string; distributedCaching: boolean; From 49ca42e3eecde95c1efddb7d196aa7b2a80cfe95 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 07:53:23 -0700 Subject: [PATCH 08/15] fix: address CI failures and CodeRabbit review on PR #73 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/types.ts: add missing cu130/cu132 CUDA version literals (unblocks tsc/lint, unrelated pre-existing drift vs auditAutofix.ts) - tests/test_tools.py: fix live-doc test to match _fetch_live_docs' new (dict, float) return signature (was silently caught by broad except, failing the "live:" source assertion in CI) - docs_search.py: kb mtime invalidation now includes file count so deletions/back-dated additions aren't missed; keyword fallback reuses already-loaded KB texts instead of re-reading from disk; log swallowed exceptions instead of silent pass; live-doc "freshness" injection no longer displaces a strictly better local/kept result (was unconditional at top_k==1) - embeddings.py: fix missing Sequence import (was silently deferred by `from __future__ import annotations`, would NameError under runtime introspection) - passive_context.py: log retrieval failures instead of returning an indistinguishable "no matches" response - troubleshooting.py: drop unnecessary `global` on a dict-mutate-only cache, bound the fingerprint cache size, extract a shared response payload builder for the empty-message and matched-entry paths (they'd drifted apart) - Dockerfile: force the CPU-only torch wheel (extra-index-url doesn't prioritize over PyPI's CUDA build), COPY --chown instead of a redundant chown -R layer, set HF_HUB_OFFLINE=1 - pyproject.toml: cap sentence-transformers/numpy below their next untested majors - oliveMcpKnowledge.ts: fix docsSearchSufficient's relevance threshold, which still assumed the old raw-hit-count scale (>=1) after this PR normalized relevance to ~[0,1] — was silently making local KB results always look "insufficient" Verified: 186/186 olive-mcp-server pytest, tsc --noEmit clean, pnpm lint 0 errors, 149/149 server vitest. Co-Authored-By: Claude Sonnet 5 --- olive-mcp-server/Dockerfile | 15 ++- .../olive_mcp_server/tools/docs_search.py | 40 +++++--- .../olive_mcp_server/tools/embeddings.py | 3 +- .../olive_mcp_server/tools/passive_context.py | 6 +- .../olive_mcp_server/tools/troubleshooting.py | 82 ++++++++------- olive-mcp-server/pyproject.toml | 4 +- .../tests/test_docs_search_semantic.py | 99 ++++++++++++------- src/server/services/ai/oliveMcpKnowledge.ts | 6 +- 8 files changed, 153 insertions(+), 102 deletions(-) diff --git a/olive-mcp-server/Dockerfile b/olive-mcp-server/Dockerfile index 5c1be35a..3292a898 100644 --- a/olive-mcp-server/Dockerfile +++ b/olive-mcp-server/Dockerfile @@ -10,9 +10,16 @@ WORKDIR /build COPY pyproject.toml ./ COPY olive_mcp_server/ ./olive_mcp_server/ -# Prefer CPU-only torch wheels to avoid multi-GB CUDA packages. +# Install torch from the CPU-only index first. --extra-index-url does not +# prioritize this index over PyPI, so a plain combined install can still +# resolve PyPI's CUDA-bundled torch wheel; installing torch alone against +# --index-url forces the CPU build, and PYTHONPATH makes it visible as +# "already satisfied" to the next install so it isn't pulled again from PyPI. RUN pip install --no-cache-dir --prefix=/install \ - --extra-index-url https://download.pytorch.org/whl/cpu \ + --index-url https://download.pytorch.org/whl/cpu \ + torch \ + && PYTHONPATH="$(echo /install/lib/python*/site-packages)" \ + pip install --no-cache-dir --prefix=/install \ . "mcp<2" # Pre-cache the embedding model so the runtime image does not need network @@ -33,8 +40,7 @@ WORKDIR /app COPY --from=builder /install /usr/local -COPY --from=builder /root/.cache/huggingface /home/mcp/.cache/huggingface -RUN chown -R mcp:mcp /home/mcp/.cache +COPY --from=builder --chown=mcp:mcp /root/.cache/huggingface /home/mcp/.cache/huggingface COPY olive_mcp_server/ ./olive_mcp_server/ COPY pyproject.toml ./ @@ -49,6 +55,7 @@ ENV MCP_TRANSPORT=sse ENV MCP_HOST=0.0.0.0 ENV MCP_PORT=8000 ENV HF_HOME=/home/mcp/.cache/huggingface +ENV HF_HUB_OFFLINE=1 HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ CMD python -c "import urllib.request; r=urllib.request.urlopen('http://localhost:8000/sse',timeout=3); r.close()" || exit 1 diff --git a/olive-mcp-server/olive_mcp_server/tools/docs_search.py b/olive-mcp-server/olive_mcp_server/tools/docs_search.py index bd2adf31..c2513986 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -7,6 +7,7 @@ from __future__ import annotations import json +import logging import threading import time from typing import Any @@ -22,6 +23,8 @@ ) +logger = logging.getLogger(__name__) + # Files that are generated by update_kb.py and should not be searched as KB. _EXCLUDED_KB_FILES = {"update_report.json", "candidate_quirks.json"} @@ -40,10 +43,10 @@ _LIVE_EMBED_CACHE_TIME = -1.0 _LIVE_INDEX_LOCK = threading.Lock() -# Local KB embedding index (invalidated when any KB JSON mtime changes). +# Local KB embedding index (invalidated when any KB JSON mtime or file count changes). _KB_TEXTS: list[tuple[str, str]] = [] _KB_EMBEDDINGS: np.ndarray | None = None -_KB_INDEX_MTIME = -1.0 +_KB_INDEX_MTIME: tuple[float, int] = (-1.0, -1) _KB_INDEX_LOCK = threading.Lock() @@ -76,8 +79,12 @@ def _load_kb_text() -> list[tuple[str, str]]: return all_text -def _kb_max_mtime() -> float: - """Return the maximum mtime among searchable KB JSON files.""" +def _kb_max_mtime() -> tuple[float, int]: + """Return (max mtime, file count) for searchable KB JSON files. + + The count makes deletions and back-dated additions visible, since a + deletion alone would otherwise leave the max mtime unchanged. + """ mtimes: list[float] = [] for file in KB_DIR.glob("*.json"): if file.name in _EXCLUDED_KB_FILES: @@ -86,7 +93,7 @@ def _kb_max_mtime() -> float: mtimes.append(file.stat().st_mtime) except OSError: continue - return max(mtimes) if mtimes else 0.0 + return (max(mtimes) if mtimes else 0.0, len(mtimes)) def get_or_build_kb_index() -> tuple[list[tuple[str, str]], np.ndarray]: @@ -189,7 +196,8 @@ def _search_local(query: str, top_k: int) -> list[dict[str, Any]]: if results: return results return _keyword_search(kb_texts, terms, top_k) - except Exception: # noqa: BLE001 + except Exception: + logger.debug("Semantic local KB search failed; falling back to keyword search", exc_info=True) return _keyword_search(_load_kb_text(), terms, top_k) @@ -199,7 +207,7 @@ def _fetch_live_docs() -> tuple[dict[str, str], float]: Concurrent fetches take a generation token; only the latest generation may publish, so a slow older response cannot overwrite a fresher one. """ - global _LIVE_CACHE, _LAST_FETCH_TIME, _LIVE_FETCH_GENERATION # noqa: PLW0603 + global _LIVE_CACHE, _LAST_FETCH_TIME, _LIVE_FETCH_GENERATION with _LIVE_FETCH_LOCK: now = time.monotonic() @@ -222,8 +230,8 @@ def _fetch_live_docs() -> tuple[dict[str, str], float]: if my_generation == _LIVE_FETCH_GENERATION: _LIVE_CACHE = fetched _LAST_FETCH_TIME = time.monotonic() - except Exception: # noqa: BLE001 - pass # Keep stale cache or return empty on failure. + except Exception: + logger.debug("Live docs fetch failed; keeping stale cache", exc_info=True) with _LIVE_FETCH_LOCK: return dict(_LIVE_CACHE), _LAST_FETCH_TIME @@ -291,13 +299,15 @@ def _search_live(query: str, top_k: int) -> list[dict[str, Any]]: if results: return results return _keyword_search(snippets, terms, top_k) - except Exception: # noqa: BLE001 + except Exception: + logger.debug("Semantic live-doc search failed; falling back to keyword search", exc_info=True) try: pages, _ = _fetch_live_docs() if not pages: return [] return _keyword_search(_split_live_snippets(pages), terms, top_k) - except Exception: # noqa: BLE001 + except Exception: + logger.debug("Live-doc keyword fallback also failed", exc_info=True) return [] @@ -337,9 +347,11 @@ def search_olive_documentation(query: str, top_k: int = 5, live: bool = True) -> and not any(r["source"].startswith("live:") for r in results) ): best_live = max(live_results, key=lambda x: x["relevance"]) - if top_k == 1: - results = [best_live] - else: + weakest_kept = min(r["relevance"] for r in results) + # Only reserve a slot for freshness when the live hit is actually + # competitive with what it would displace — never displace the sole + # top result outright (top_k == 1) with a strictly worse live hit. + if best_live["relevance"] >= weakest_kept: results = results[: top_k - 1] + [best_live] results.sort( key=lambda x: (-x["relevance"], 0 if x["source"].startswith("live:") else 1) diff --git a/olive-mcp-server/olive_mcp_server/tools/embeddings.py b/olive-mcp-server/olive_mcp_server/tools/embeddings.py index 9af95d30..8b2416dc 100644 --- a/olive-mcp-server/olive_mcp_server/tools/embeddings.py +++ b/olive-mcp-server/olive_mcp_server/tools/embeddings.py @@ -7,7 +7,8 @@ from __future__ import annotations import threading -from typing import Any, Iterable +from collections.abc import Iterable, Sequence +from typing import Any import numpy as np diff --git a/olive-mcp-server/olive_mcp_server/tools/passive_context.py b/olive-mcp-server/olive_mcp_server/tools/passive_context.py index 7690e808..e2e3bff4 100644 --- a/olive-mcp-server/olive_mcp_server/tools/passive_context.py +++ b/olive-mcp-server/olive_mcp_server/tools/passive_context.py @@ -6,11 +6,14 @@ from __future__ import annotations +import logging from typing import Any from .docs_search import get_or_build_kb_index from .embeddings import DEFAULT_THRESHOLD, semantic_search +logger = logging.getLogger(__name__) + def _pass_descriptor_text(item: Any) -> str: """Normalize a pass descriptor (str or dict) into searchable text.""" @@ -102,7 +105,8 @@ def get_context_for_pipeline( top_k, threshold=DEFAULT_THRESHOLD, ) - except Exception: # noqa: BLE001 + except Exception: + logger.warning("KB retrieval failed for pipeline context", exc_info=True) results = [] confidences = [float(r.get("relevance", 0.0)) for r in results] diff --git a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py index d5046379..ffe63767 100644 --- a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py +++ b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py @@ -50,6 +50,7 @@ _ts_index_lock = threading.Lock() # fingerprint -> (entries, embeddings, kb_mtime_at_build) _ts_index_cache: dict[str, tuple[list[dict[str, Any]], np.ndarray, float]] = {} +_TS_INDEX_CACHE_MAX = 8 def _get_frequency_key(matched_entry: str | None, error_message: str) -> str: @@ -143,8 +144,6 @@ def _get_troubleshooting_index( Invalidates when fingerprint or KB mtime changes. Callers must score using the returned entries list so embeddings stay position-aligned. """ - global _ts_index_cache - if entries is None: entries = load_troubleshooting() entries_list = list(entries) @@ -171,6 +170,13 @@ def _get_troubleshooting_index( if current_mtime != file_mtime: return entries_list, embeddings _ts_index_cache[fingerprint] = (entries_list, embeddings, file_mtime) + # Bound cache size: domain pools are few (olive/studio/auto), so evict + # the oldest entry rather than let stale fingerprints from a + # hot-reloading KB accumulate forever. + if len(_ts_index_cache) > _TS_INDEX_CACHE_MAX: + oldest_key = next(iter(_ts_index_cache)) + if oldest_key != fingerprint: + del _ts_index_cache[oldest_key] return entries_list, embeddings @@ -406,6 +412,35 @@ def _no_match_payload() -> dict[str, Any]: } +def _build_diagnosis_payload( + best: dict[str, Any], + matched_entry: str | None, + matched_domain: str | None, + applyable: bool, + pass_name: str, + freq: dict[str, Any], +) -> dict[str, Any]: + """Assemble the diagnosis response shared by the matched and no-match paths.""" + updated_config = best.get("updated_config", {}) or {} + return { + "matched_entry": matched_entry, + "domain": matched_domain, + "applyable": applyable if matched_entry else False, + "title": best.get("title", ""), + "root_cause": best.get("root_cause", ""), + "workaround": best.get("solution", ""), + "updated_config": updated_config if isinstance(updated_config, dict) else {}, + "relevant_quirks": _build_relevant_quirks(matched_entry, pass_name, matched_domain), + "related_olive_entry": best.get("related_olive_entry"), + "frequency": { + "occurrence_count": freq["occurrence_count"], + "first_seen": _format_ts(freq["first_seen"]), + "last_seen": _format_ts(freq["last_seen"]), + "label": _frequency_label(freq["occurrence_count"]), + }, + } + + def troubleshoot_olive_error( error_message: str, pass_name: str = "", @@ -429,28 +464,9 @@ def troubleshoot_olive_error( # Empty body: never match from pass_name/config_context alone (TensorRT/AWQ/…). if not (error_message or "").strip(): best = _no_match_payload() - matched_entry = None - matched_domain = None - applyable = False - freq_key = _get_frequency_key(matched_entry, error_message) + freq_key = _get_frequency_key(None, error_message) freq = _record_occurrence(freq_key) - return { - "matched_entry": matched_entry, - "domain": matched_domain, - "applyable": applyable, - "title": best["title"], - "root_cause": best["root_cause"], - "workaround": best["solution"], - "updated_config": best["updated_config"], - "relevant_quirks": _build_relevant_quirks(matched_entry, pass_name, matched_domain), - "related_olive_entry": None, - "frequency": { - "occurrence_count": freq["occurrence_count"], - "first_seen": _format_ts(freq["first_seen"]), - "last_seen": _format_ts(freq["last_seen"]), - "label": _frequency_label(freq["occurrence_count"]), - }, - } + return _build_diagnosis_payload(best, None, None, False, pass_name, freq) resolved = _resolve_domain(domain) @@ -494,25 +510,7 @@ def troubleshoot_olive_error( freq_key = _get_frequency_key(matched_entry, error_message) freq = _record_occurrence(freq_key) - updated_config = best.get("updated_config", {}) or {} - - return { - "matched_entry": matched_entry, - "domain": matched_domain, - "applyable": applyable if matched_entry else False, - "title": best.get("title", ""), - "root_cause": best.get("root_cause", ""), - "workaround": best.get("solution", ""), - "updated_config": updated_config if isinstance(updated_config, dict) else {}, - "relevant_quirks": _build_relevant_quirks(matched_entry, pass_name, matched_domain), - "related_olive_entry": best.get("related_olive_entry"), - "frequency": { - "occurrence_count": freq["occurrence_count"], - "first_seen": _format_ts(freq["first_seen"]), - "last_seen": _format_ts(freq["last_seen"]), - "label": _frequency_label(freq["occurrence_count"]), - }, - } + return _build_diagnosis_payload(best, matched_entry, matched_domain, applyable, pass_name, freq) def diagnose_error( diff --git a/olive-mcp-server/pyproject.toml b/olive-mcp-server/pyproject.toml index 155b711f..dc50b5ca 100644 --- a/olive-mcp-server/pyproject.toml +++ b/olive-mcp-server/pyproject.toml @@ -11,8 +11,8 @@ dependencies = [ "mcp>=1.0.0,<2", "requests>=2.32.0", "beautifulsoup4>=4.12.0", - "sentence-transformers>=3.0.0", - "numpy>=1.24.0", + "sentence-transformers>=3.0.0,<6", + "numpy>=1.24.0,<3", ] [project.optional-dependencies] diff --git a/olive-mcp-server/tests/test_docs_search_semantic.py b/olive-mcp-server/tests/test_docs_search_semantic.py index 089b5b88..0cbd0091 100644 --- a/olive-mcp-server/tests/test_docs_search_semantic.py +++ b/olive-mcp-server/tests/test_docs_search_semantic.py @@ -14,11 +14,23 @@ def _reset_kb_index_cache(): """Ensure each test starts with a clean KB embedding cache.""" docs_search._KB_TEXTS = [] docs_search._KB_EMBEDDINGS = None - docs_search._KB_INDEX_MTIME = -1.0 + docs_search._KB_INDEX_MTIME = (-1.0, -1) + docs_search._LIVE_CACHE = {} + docs_search._LAST_FETCH_TIME = 0.0 + docs_search._LIVE_FETCH_GENERATION = 0 + docs_search._LIVE_SNIPPETS = [] + docs_search._LIVE_EMBEDDINGS = None + docs_search._LIVE_EMBED_CACHE_TIME = -1.0 yield docs_search._KB_TEXTS = [] docs_search._KB_EMBEDDINGS = None - docs_search._KB_INDEX_MTIME = -1.0 + docs_search._KB_INDEX_MTIME = (-1.0, -1) + docs_search._LIVE_CACHE = {} + docs_search._LAST_FETCH_TIME = 0.0 + docs_search._LIVE_FETCH_GENERATION = 0 + docs_search._LIVE_SNIPPETS = [] + docs_search._LIVE_EMBEDDINGS = None + docs_search._LIVE_EMBED_CACHE_TIME = -1.0 def _install_fake_semantic( @@ -135,7 +147,7 @@ def fake_semantic(query, kb_texts, kb_embeddings, top_k, threshold=0.30): monkeypatch.setattr(docs_search, "semantic_search", fake_semantic) # First build - monkeypatch.setattr(docs_search, "_kb_max_mtime", lambda: 100.0) + monkeypatch.setattr(docs_search, "_kb_max_mtime", lambda: (100.0, 2)) docs_search._search_local("quantization", 3) assert len(build_calls) == 1 @@ -144,11 +156,23 @@ def fake_semantic(query, kb_texts, kb_embeddings, top_k, threshold=0.30): assert len(build_calls) == 1 # mtime change → rebuild - monkeypatch.setattr(docs_search, "_kb_max_mtime", lambda: 200.0) + monkeypatch.setattr(docs_search, "_kb_max_mtime", lambda: (200.0, 2)) docs_search._search_local("quantization", 3) assert len(build_calls) == 2 +def test_weak_live_result_does_not_displace_strong_local_top1(monkeypatch: pytest.MonkeyPatch): + """A weak live hit must not evict the single strongest local result at top_k=1.""" + strong_local = [{"source": "passes.foo", "snippet": "strong", "relevance": 0.85}] + weak_live = [{"source": "live:index", "snippet": "weak", "relevance": 0.31}] + + monkeypatch.setattr(docs_search, "_search_local", lambda query, top_k: strong_local[:top_k]) + monkeypatch.setattr(docs_search, "_search_live", lambda query, top_k: weak_live[:top_k]) + + result = search_olive_documentation(query="quantization", top_k=1, live=True) + assert result["results"] == [strong_local[0]] + + def test_empty_query_unchanged(): result = search_olive_documentation(query=" ", top_k=5, live=False) assert result["count"] == 0 @@ -177,7 +201,7 @@ def test_kb_stale_build_does_not_poison_cache(monkeypatch: pytest.MonkeyPatch): load_calls: list[str] = [] def fake_mtime(): - return mtime_box["v"] + return (mtime_box["v"], 1) def fake_load(): if mtime_box["v"] >= 200.0: @@ -199,54 +223,55 @@ def fake_build(texts): texts1, _emb1 = docs_search.get_or_build_kb_index() # Stale build returned locally but must not poison global cache at mtime 200. assert texts1[0][0] == "old.path" - assert docs_search._KB_INDEX_MTIME != 200.0 or docs_search._KB_TEXTS[0][0] != "old.path" + assert docs_search._KB_INDEX_MTIME != (200.0, 1) or docs_search._KB_TEXTS[0][0] != "old.path" # Next call with mtime 200 should load fresh content and cache it. texts2, _emb2 = docs_search.get_or_build_kb_index() assert texts2[0][0] == "new.path" - assert docs_search._KB_INDEX_MTIME == 200.0 + assert docs_search._KB_INDEX_MTIME == (200.0, 1) assert docs_search._KB_TEXTS[0][0] == "new.path" def test_live_fetch_generation_ignores_stale_completion(monkeypatch: pytest.MonkeyPatch): - """Older in-flight fetch must not overwrite a newer generation's cache.""" - docs_search._LIVE_CACHE = {} - docs_search._LAST_FETCH_TIME = 0.0 - docs_search._LIVE_FETCH_GENERATION = 0 + """An older in-flight fetch completing after a newer one must not win. - results_queue = [ - {"status": "ok", "pages": {"index": "OLDER live page content calibration"}}, - {"status": "ok", "pages": {"index": "NEWER live page content calibration"}}, - ] + Drives the real ``_fetch_live_docs`` through two threads so the + generation-token guard inside the function itself is exercised, not + re-implemented in the test. + """ + import threading as _threading + + started_gen1 = _threading.Event() + release_gen1 = _threading.Event() call_i = {"n": 0} def fake_fetch(pages=None): - # First call is gen 1 (older), second is gen 2 (newer) — complete out of order. i = call_i["n"] call_i["n"] += 1 - return results_queue[min(i, len(results_queue) - 1)] + if i == 0: + # gen1: signal it has started, then block until gen2 finishes. + started_gen1.set() + release_gen1.wait(timeout=5) + return {"status": "ok", "pages": {"index": "OLDER live page content calibration"}} + return {"status": "ok", "pages": {"index": "NEWER live page content calibration"}} - # Patch the lazy import path used inside _fetch_live_docs. import olive_mcp_server.fetchers.official_docs_fetcher as fetcher monkeypatch.setattr(fetcher, "fetch_official_docs", fake_fetch) - # Start gen1 and gen2 by forcing TTL miss; manually exercise publish races. - with docs_search._LIVE_FETCH_LOCK: - docs_search._LIVE_FETCH_GENERATION = 1 - gen1 = 1 - docs_search._LIVE_FETCH_GENERATION = 2 - gen2 = 2 - - # Apply gen2 first (newer). - with docs_search._LIVE_FETCH_LOCK: - if gen2 == docs_search._LIVE_FETCH_GENERATION: - docs_search._LIVE_CACHE = {"index": "NEWER"} - docs_search._LAST_FETCH_TIME = 999.0 - # Stale gen1 must not overwrite. - with docs_search._LIVE_FETCH_LOCK: - if gen1 == docs_search._LIVE_FETCH_GENERATION: - docs_search._LIVE_CACHE = {"index": "OLDER"} - docs_search._LAST_FETCH_TIME = 1000.0 - - assert docs_search._LIVE_CACHE == {"index": "NEWER"} + result_gen1: dict = {} + t1 = _threading.Thread( + target=lambda: result_gen1.update(pages=docs_search._fetch_live_docs()[0]) + ) + t1.start() + assert started_gen1.wait(timeout=5) + + # gen2 runs to completion while gen1 is still blocked. + pages_gen2, _ = docs_search._fetch_live_docs() + assert "NEWER" in next(iter(pages_gen2.values())) + + # Now let the stale gen1 completion land; it must not clobber gen2's cache. + release_gen1.set() + t1.join(timeout=5) + + assert "NEWER" in next(iter(docs_search._LIVE_CACHE.values())) diff --git a/src/server/services/ai/oliveMcpKnowledge.ts b/src/server/services/ai/oliveMcpKnowledge.ts index fc21c0cb..b5132aa5 100644 --- a/src/server/services/ai/oliveMcpKnowledge.ts +++ b/src/server/services/ai/oliveMcpKnowledge.ts @@ -137,7 +137,11 @@ function docsSearchSufficient(result: unknown): boolean { if (count <= 0) return false; const results = Array.isArray(r.results) ? r.results : []; const top = results[0] as { relevance?: number } | undefined; - return typeof top?.relevance === "number" ? top.relevance >= 1 : results.length > 0; + // `relevance` is normalized to roughly [0, 1] (semantic cosine or keyword + // ratio) and already passed the MCP server's own match threshold before + // being returned — any positive score here means a real hit, not a >=1 + // "many keyword hits" bar from the pre-semantic-search scale. + return typeof top?.relevance === "number" ? top.relevance > 0 : results.length > 0; } /** Map EP / keyword targets to MCP KB canonical hardware profile names. */ From b895245ff04836c5e62bcd2496b2b06a2a29c411 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:00:10 -0700 Subject: [PATCH 09/15] fix: make live-doc merge test deterministic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous version relied on the real embedding model ranking a single synthetic live snippet above ~2500 real local KB entries for "calibration data" — legitimately doesn't happen once the forced live-injection bug was fixed, so the test failed in CI (which has the real sentence-transformers model) even though it passed locally (where the model isn't installed and the code falls back to keyword search). Mock _search_local/_search_live directly instead, matching the pattern used by the other merge-logic regression tests. Co-Authored-By: Claude Sonnet 5 --- olive-mcp-server/tests/test_tools.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/olive-mcp-server/tests/test_tools.py b/olive-mcp-server/tests/test_tools.py index 1e25e0bc..4062c956 100644 --- a/olive-mcp-server/tests/test_tools.py +++ b/olive-mcp-server/tests/test_tools.py @@ -160,17 +160,21 @@ def test_search_olive_documentation(): def test_search_olive_documentation_with_live_source(monkeypatch: pytest.MonkeyPatch): - """Live search should merge cached fetched docs with local results.""" + """Live search should merge cached fetched docs with local results. + + Ranking is deterministic here (local/live search functions are mocked + directly) rather than relying on real embedding scores, since a live + result is only surfaced when it is genuinely competitive with local KB + hits — the old "always force one live result in" behavior was a bug. + """ from olive_mcp_server.tools import docs_search - monkeypatch.setattr( - docs_search, - "_fetch_live_docs", - lambda: ( - {"index": "Live docs mention calibration data and quantization."}, - 0.0, - ), - ) + local_results = [{"source": "passes.foo", "snippet": "local hit", "relevance": 0.5}] + live_results = [{"source": "live:index", "snippet": "live hit", "relevance": 0.9}] + + monkeypatch.setattr(docs_search, "_search_local", lambda query, top_k: local_results[:top_k]) + monkeypatch.setattr(docs_search, "_search_live", lambda query, top_k: live_results[:top_k]) + result = search_olive_documentation(query="calibration data", top_k=3, live=True) assert result["count"] > 0 assert any("live:" in r["source"] for r in result["results"]) From 0286504ceef7b9ca8a902b3a46f1d8d41e31c1c7 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:03:36 -0700 Subject: [PATCH 10/15] fix: live-index stale-overwrite race and empty-cache rebuild bug - docs_search.py:_get_live_index: cache-hit/publish checks used `_LIVE_SNIPPETS` truthiness, so an empty (but successfully built) live index was never recognized as cached and got rebuilt on every call. Also, publish had no ordering guard: a slow build for an older fetch_time could complete after a newer generation already published and clobber it, silently rolling the live cache back to stale content. Both fixed: cache checks now key off `_LIVE_EMBEDDINGS is not None`, and publish is skipped when the build's fetch_time is older than what's already cached. - Added test_live_index_does_not_overwrite_newer_generation covering the race. Co-Authored-By: Claude Sonnet 5 --- .../olive_mcp_server/tools/docs_search.py | 25 +++++++++------- .../tests/test_docs_search_semantic.py | 29 +++++++++++++++++++ 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/olive-mcp-server/olive_mcp_server/tools/docs_search.py b/olive-mcp-server/olive_mcp_server/tools/docs_search.py index c2513986..03bf1e22 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -249,17 +249,20 @@ def _split_live_snippets(pages: dict[str, str]) -> list[tuple[str, str]]: def _get_live_index() -> tuple[list[tuple[str, str]], np.ndarray]: - """Return live snippets and their embeddings, rebuilding on cache refresh.""" + """Return live snippets and their embeddings, rebuilding on cache refresh. + + Cache-hit and publish checks use ``_LIVE_EMBEDDINGS is not None`` (not + truthiness of ``_LIVE_SNIPPETS``) so an empty-but-built live index is + still cached rather than rebuilt on every call. Publication also refuses + to overwrite a newer generation's cache with a stale (smaller + ``fetch_time``) build that raced behind it. + """ global _LIVE_SNIPPETS, _LIVE_EMBEDDINGS, _LIVE_EMBED_CACHE_TIME pages, fetch_time = _fetch_live_docs() with _LIVE_INDEX_LOCK: - if ( - _LIVE_EMBEDDINGS is not None - and _LIVE_SNIPPETS - and _LIVE_EMBED_CACHE_TIME == fetch_time - ): + if _LIVE_EMBEDDINGS is not None and _LIVE_EMBED_CACHE_TIME == fetch_time: return _LIVE_SNIPPETS, _LIVE_EMBEDDINGS snippets = _split_live_snippets(pages) if pages else [] @@ -269,12 +272,12 @@ def _get_live_index() -> tuple[list[tuple[str, str]], np.ndarray]: embeddings = build_kb_index([t for _, t in snippets]) with _LIVE_INDEX_LOCK: - if ( - _LIVE_EMBEDDINGS is not None - and _LIVE_SNIPPETS - and _LIVE_EMBED_CACHE_TIME == fetch_time - ): + if _LIVE_EMBEDDINGS is not None and _LIVE_EMBED_CACHE_TIME == fetch_time: return _LIVE_SNIPPETS, _LIVE_EMBEDDINGS + if _LIVE_EMBEDDINGS is not None and fetch_time < _LIVE_EMBED_CACHE_TIME: + # A newer generation already published while this one was + # encoding; discard this stale build rather than clobber it. + return snippets, embeddings _LIVE_SNIPPETS = snippets _LIVE_EMBEDDINGS = embeddings diff --git a/olive-mcp-server/tests/test_docs_search_semantic.py b/olive-mcp-server/tests/test_docs_search_semantic.py index 0cbd0091..02582507 100644 --- a/olive-mcp-server/tests/test_docs_search_semantic.py +++ b/olive-mcp-server/tests/test_docs_search_semantic.py @@ -275,3 +275,32 @@ def fake_fetch(pages=None): t1.join(timeout=5) assert "NEWER" in next(iter(docs_search._LIVE_CACHE.values())) + + +def test_live_index_does_not_overwrite_newer_generation(monkeypatch: pytest.MonkeyPatch): + """A stale (older fetch_time) live-index build must not clobber a newer one. + + Simulates: build for fetch_time=100 starts, a newer fetch_time=200 build + completes and publishes first, then the stale build's publish attempt + must be discarded rather than roll the cache back to fetch_time=100. + """ + + def fake_build(texts): + return np.ones((len(list(texts)), 384), dtype=np.float32) + + monkeypatch.setattr(docs_search, "build_kb_index", fake_build) + + # Newer generation publishes first. + monkeypatch.setattr( + docs_search, "_fetch_live_docs", lambda: ({"index": "newer content"}, 200.0) + ) + docs_search._get_live_index() + assert docs_search._LIVE_EMBED_CACHE_TIME == 200.0 + + # Stale generation (older fetch_time) attempts to publish after. + monkeypatch.setattr( + docs_search, "_fetch_live_docs", lambda: ({"index": "older content"}, 100.0) + ) + docs_search._get_live_index() + assert docs_search._LIVE_EMBED_CACHE_TIME == 200.0 + assert docs_search._LIVE_SNIPPETS[0][1] == "newer content" From 3c91398d288707ed824f07c2e404083db7eb0691 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:08:18 -0700 Subject: [PATCH 11/15] fix: salvage convert/quant actions from step-only value strings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parseChatStructuredReply's loose-JSON salvage only matched convert/quant keywords against the object *key* (e.g. "quantMethod", "onnx"), so a payload shaped like {step: "convert_to_onnx"} or {step: "apply_quantization"} — generic key, keyword in the value — matched nothing and produced no patch. Widen both fallback branches to also match keyword strings in the value. Pre-existing failure on main (unrelated to the PR #73 branch), fixing here since it was blocking this PR's CI. Co-Authored-By: Claude Sonnet 5 --- src/lib/chatActions.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/lib/chatActions.ts b/src/lib/chatActions.ts index 54216a3f..63a802b0 100644 --- a/src/lib/chatActions.ts +++ b/src/lib/chatActions.ts @@ -222,9 +222,9 @@ export function salvageChatActionPatchFromLooseJson(parsed: unknown): ChatAction } if ( - /quant/i.test(key) && + (/quant/i.test(key) || (typeof value === "string" && /quant/i.test(value))) && (value === true || - (typeof value === "string" && /apply|enable|true|int[48]|awq|gptq|ptq/i.test(value))) + (typeof value === "string" && /apply|enable|true|int[48]|awq|gptq|ptq|quant/i.test(value))) ) { passes.quantization = true; if (typeof value === "string") { @@ -240,7 +240,10 @@ export function salvageChatActionPatchFromLooseJson(parsed: unknown): ChatAction } if ( - (/convert/.test(key) || key === "onnx" || /onnx/.test(key)) && + (/convert/.test(key) || + key === "onnx" || + /onnx/.test(key) || + (typeof value === "string" && (/convert/i.test(value) || /onnx/i.test(value)))) && (value === true || typeof value === "string" || typeof value === "number" || isRecord(value)) ) { passes.conversion = true; From cbfb86bbbcdea8aff2eaaad627270bcf828bc861 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:14:09 -0700 Subject: [PATCH 12/15] fix: address remaining CodeRabbit nitpicks on PR #73 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - docs_search.py:_fetch_live_docs: publish also when the cache is currently empty, not only when this is still the latest generation. Otherwise a newer generation that fails after an older one already succeeded (but hasn't published yet) permanently discards the only good fetch, leaving the live cache empty. - test_docs_search_semantic.py: assert the stale-generation test's worker thread actually completed and returned data, so a silent exception or deadlock in that thread can't produce a false pass. - oliveMcpKnowledge.test.ts: add a regression case for a normalized sub-1 relevance score, which the previous `relevance: 2` fixture couldn't distinguish from the old >=1 threshold. Also widened BatchProcessingPanel.test.tsx's fetch assertion into a waitFor while investigating a "validate" CI failure — turned out to be a pre-existing bug unrelated to this PR (reproduces identically on origin/main), leaving as-is rather than chasing it here. Co-Authored-By: Claude Sonnet 5 --- .../olive_mcp_server/tools/docs_search.py | 8 ++++++-- .../tests/test_docs_search_semantic.py | 2 ++ .../features/BatchProcessingPanel.test.tsx | 7 ++++++- src/server/services/ai/oliveMcpKnowledge.test.ts | 16 ++++++++++++++++ 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/olive-mcp-server/olive_mcp_server/tools/docs_search.py b/olive-mcp-server/olive_mcp_server/tools/docs_search.py index 03bf1e22..b8ec7e2e 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -226,8 +226,12 @@ def _fetch_live_docs() -> tuple[dict[str, str], float]: fetched = {k: v for k, v in pages.items() if isinstance(v, str)} if fetched: with _LIVE_FETCH_LOCK: - # Ignore stale completions if a newer fetch was started. - if my_generation == _LIVE_FETCH_GENERATION: + # Publish unless a newer generation has already succeeded + # (empty cache means no generation has published yet, so + # an older completion racing behind a newer *failure* is + # still the only good data available and must not be + # discarded). + if my_generation == _LIVE_FETCH_GENERATION or not _LIVE_CACHE: _LIVE_CACHE = fetched _LAST_FETCH_TIME = time.monotonic() except Exception: diff --git a/olive-mcp-server/tests/test_docs_search_semantic.py b/olive-mcp-server/tests/test_docs_search_semantic.py index 02582507..01cd469f 100644 --- a/olive-mcp-server/tests/test_docs_search_semantic.py +++ b/olive-mcp-server/tests/test_docs_search_semantic.py @@ -273,6 +273,8 @@ def fake_fetch(pages=None): # Now let the stale gen1 completion land; it must not clobber gen2's cache. release_gen1.set() t1.join(timeout=5) + assert not t1.is_alive(), "stale generation-1 fetch did not complete" + assert result_gen1.get("pages"), "generation-1 thread raised before returning" assert "NEWER" in next(iter(docs_search._LIVE_CACHE.values())) diff --git a/src/components/features/BatchProcessingPanel.test.tsx b/src/components/features/BatchProcessingPanel.test.tsx index 31015204..4610b7d2 100644 --- a/src/components/features/BatchProcessingPanel.test.tsx +++ b/src/components/features/BatchProcessingPanel.test.tsx @@ -180,6 +180,11 @@ describe("BatchProcessingPanel", () => { expect(mockFetchKeyedDiagnostic).toHaveBeenCalledWith("job-invalid", expect.any(Array)); // Verify the valid job was attempted to run (fetch was called for /api/olive/run) - expect(global.fetch).toHaveBeenCalledWith("/api/olive/run", expect.any(Object)); + await waitFor( + () => { + expect(global.fetch).toHaveBeenCalledWith("/api/olive/run", expect.any(Object)); + }, + { timeout: 3000 }, + ); }); }); diff --git a/src/server/services/ai/oliveMcpKnowledge.test.ts b/src/server/services/ai/oliveMcpKnowledge.test.ts index 5489d51e..05697d6f 100644 --- a/src/server/services/ai/oliveMcpKnowledge.test.ts +++ b/src/server/services/ai/oliveMcpKnowledge.test.ts @@ -69,6 +69,22 @@ describe("gatherOliveMcpKnowledge", () => { expect(out.promptBlock).toContain("INT8"); }); + it("treats a normalized sub-1 relevance score as sufficient", async () => { + mockedBatch.mockResolvedValue([ + { + result: { + query: "quantization", + count: 1, + results: [{ source: "passes.OnnxQuantization", snippet: "INT8", relevance: 0.2 }], + }, + }, + ]); + + const out = await gatherOliveMcpKnowledge("Tell me about quantization"); + expect(out.sufficient).toBe(true); + expect(out.usedWebFallback).toBe(false); + }); + it("marks coverage insufficient when MCP returns nothing", async () => { mockedBatch.mockResolvedValue([{ error: "boom" }]); const out = await gatherOliveMcpKnowledge("random question"); From f67fc4e182f612e1e64ea3bd426c6e8246e903e6 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:23:51 -0700 Subject: [PATCH 13/15] fix: don't salvage chat actions from negated or non-action prose salvageChatActionPatchFromLooseJson's value-string fallback (added earlier this PR to catch {step: "convert_to_onnx"}-shaped payloads) was too broad: it scanned *any* string field, so {note: "do not quantize this model"} or {note: "conversion is unavailable"} would incorrectly enable those passes. Restrict value-string matching to step/action/task keys only, and add a negation guard (no/not/never/ disable/skip/without/unavailable) so negated prose can't enable a pass. Added regression tests for both cases. Co-Authored-By: Claude Sonnet 5 --- src/lib/__tests__/chatActions.test.ts | 20 ++++++++++++++++++++ src/lib/chatActions.ts | 10 ++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/lib/__tests__/chatActions.test.ts b/src/lib/__tests__/chatActions.test.ts index a3029bf0..30e4adfd 100644 --- a/src/lib/__tests__/chatActions.test.ts +++ b/src/lib/__tests__/chatActions.test.ts @@ -125,6 +125,26 @@ describe("parseChatStructuredReply", () => { expect(quantOnly?.passes?.quantMethod).toBe("ptq"); }); + it("does not salvage passes from free-form prose fields like note", () => { + const noteOnly = salvageChatActionPatchFromLooseJson({ + note: "do not quantize this model", + }); + expect(noteOnly?.passes?.quantization).toBeUndefined(); + + const noteOnly2 = salvageChatActionPatchFromLooseJson({ + note: "conversion is unavailable right now", + }); + expect(noteOnly2?.passes?.conversion).toBeUndefined(); + }); + + it("does not salvage negated step/action prose", () => { + const negatedQuant = salvageChatActionPatchFromLooseJson({ step: "do not apply quantization" }); + expect(negatedQuant?.passes?.quantization).toBeUndefined(); + + const negatedConvert = salvageChatActionPatchFromLooseJson({ step: "skip onnx conversion" }); + expect(negatedConvert?.passes?.conversion).toBeUndefined(); + }); + it("strips misleading Apply instructions when no patch exists", () => { const out = parseChatStructuredReply( JSON.stringify({ diff --git a/src/lib/chatActions.ts b/src/lib/chatActions.ts index 63a802b0..3dfeff42 100644 --- a/src/lib/chatActions.ts +++ b/src/lib/chatActions.ts @@ -221,8 +221,13 @@ export function salvageChatActionPatchFromLooseJson(parsed: unknown): ChatAction } } + const isActionField = key === "step" || key === "action" || key === "task"; + const isNegated = + typeof value === "string" && /\b(no|not|never|disable|skip|without|unavailable)\b/i.test(value); + if ( - (/quant/i.test(key) || (typeof value === "string" && /quant/i.test(value))) && + !isNegated && + (/quant/i.test(key) || (isActionField && typeof value === "string" && /quant/i.test(value))) && (value === true || (typeof value === "string" && /apply|enable|true|int[48]|awq|gptq|ptq|quant/i.test(value))) ) { @@ -240,10 +245,11 @@ export function salvageChatActionPatchFromLooseJson(parsed: unknown): ChatAction } if ( + !isNegated && (/convert/.test(key) || key === "onnx" || /onnx/.test(key) || - (typeof value === "string" && (/convert/i.test(value) || /onnx/i.test(value)))) && + (isActionField && typeof value === "string" && (/convert/i.test(value) || /onnx/i.test(value)))) && (value === true || typeof value === "string" || typeof value === "number" || isRecord(value)) ) { passes.conversion = true; From e932d4f0a7152987460bdd69e0367fb9da2e9d01 Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:40:34 -0700 Subject: [PATCH 14/15] fix: pre-existing BatchProcessingPanel test/validation bug (unrelated to PR #73) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root cause chain, found via instrumentation: 1. testUtils.tsx:createMockUIState set passes.conversion=true with no conversionFormat. buildOliveRecipe() then defaults to OpenVINOConversion, which requires torch/onnx input — but modelSource defaults to "huggingface" (hf output). Every component test using this default state was silently building an already-invalid pipeline. 2. In BatchProcessingPanel, this meant the "valid" job in the individual-validation test was itself blocked by a pass-chain mismatch, so the test's fetch assertion coincidentally passed on an already-broken path (fetch was never reached for either job, but the assertion only checked the invalid job's failure). 3. Fixing the state default advanced the job further into real handleStartQueue logic, exposing a second, independent bug: the test's EventSource mock was `vi.fn(() => obj)`, an arrow function, which cannot be used with `new` — throwing when the component opens its SSE stream for the (now correctly) running valid job. 4. Once EventSource was constructible, the sequential job loop still never advanced to the invalid job because nothing in the test ever fired the "done" SSE event the component awaits before moving to the next queued job. Fixes: add conversionFormat: "onnx" to the mock state default, make the EventSource mock a real constructor function, and have the test capture and fire the "done" listener so the loop can proceed to validate the invalid job. Verified this reproduces identically on origin/main (pre-existing, unrelated to the semantic-retrieval work in this PR) before fixing it here per request to get CI fully green. Co-Authored-By: Claude Sonnet 5 --- .../features/BatchProcessingPanel.test.tsx | 17 ++++++++++++++--- src/components/features/__tests__/testUtils.tsx | 1 + 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/components/features/BatchProcessingPanel.test.tsx b/src/components/features/BatchProcessingPanel.test.tsx index 4610b7d2..598f9249 100644 --- a/src/components/features/BatchProcessingPanel.test.tsx +++ b/src/components/features/BatchProcessingPanel.test.tsx @@ -134,13 +134,20 @@ describe("BatchProcessingPanel", () => { return Promise.reject(new Error("Unexpected fetch")); }); - // Mock EventSource for the valid job's stream + // Mock EventSource for the valid job's stream. Capture the "done" + // listener so the test can immediately signal a successful run, + // letting the sequential job loop proceed to the invalid job. + const doneListeners: Array<(e: { data: string }) => void> = []; const mockEventSource = { - addEventListener: vi.fn(), + addEventListener: vi.fn((event: string, cb: (e: { data: string }) => void) => { + if (event === "done") doneListeners.push(cb); + }), close: vi.fn(), onerror: null, }; - global.EventSource = vi.fn(() => mockEventSource) as unknown as typeof EventSource; + global.EventSource = vi.fn(function EventSourceMock() { + return mockEventSource; + }) as unknown as typeof EventSource; await act(async () => { render(); @@ -151,6 +158,10 @@ describe("BatchProcessingPanel", () => { await act(async () => { await userEvent.click(startButton); + // Let the valid job's SSE stream complete so the sequential loop + // moves on to validate the invalid job. + await waitFor(() => expect(doneListeners.length).toBeGreaterThan(0)); + doneListeners.forEach((cb) => cb({ data: JSON.stringify({ exitCode: 0 }) })); }); // Wait for the validation and state updates diff --git a/src/components/features/__tests__/testUtils.tsx b/src/components/features/__tests__/testUtils.tsx index b0d94e97..3f5065b3 100644 --- a/src/components/features/__tests__/testUtils.tsx +++ b/src/components/features/__tests__/testUtils.tsx @@ -30,6 +30,7 @@ export function createMockUIState(partial?: Partial): UIState { activeJobId: null, passes: { conversion: true, + conversionFormat: "onnx", conversionSourceFormat: "pytorch", quantization: false, quantizationMethod: "gptq", From f5567fab0bdc45f35c59737ab4820bb31155a17b Mon Sep 17 00:00:00 2001 From: tonythethompson Date: Sat, 1 Aug 2026 08:56:35 -0700 Subject: [PATCH 15/15] fix: don't widen cudaVersion type to match a stray unsupported entry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit My earlier fix for the tsc failure in auditAutofix.ts (unrelated pre-existing bug on this branch) took the wrong direction: it widened UIState["cudaVersion"] to include cu130/cu132 to match auditAutofix.ts's CUDA_VERSIONS set, when the actual bug was that set itself listing tags the project doesn't support anywhere else. RESOLVABLE_CUDA_TAGS (oliveGpuRuntime.ts) and inferRequiredPackages (recipe.ts) both cap at cu128 — cu130/cu132 aren't resolvable yet (ORT + nvidia-*-cu13 PyPI pins don't exist). Revert cudaVersion to its original union and trim the two stray CUDA_VERSIONS sets (auditAutofix.ts, chatActions.ts) that had cu130/cu132 instead. Co-Authored-By: Claude Sonnet 5 --- src/lib/auditAutofix.ts | 2 -- src/lib/chatActions.ts | 2 +- src/types.ts | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/lib/auditAutofix.ts b/src/lib/auditAutofix.ts index 8a55b4ec..8421cd93 100644 --- a/src/lib/auditAutofix.ts +++ b/src/lib/auditAutofix.ts @@ -225,8 +225,6 @@ const CUDA_VERSIONS = new Set([ "cu124", "cu126", "cu128", - "cu130", - "cu132", ]); const MEMORY_OFFLOADS = new Set(["gpu_only", "auto"]); const MODEL_SOURCES = new Set(["huggingface", "local", "azure"]); diff --git a/src/lib/chatActions.ts b/src/lib/chatActions.ts index 3dfeff42..dfa3aaa4 100644 --- a/src/lib/chatActions.ts +++ b/src/lib/chatActions.ts @@ -17,7 +17,7 @@ const IHV_PROVIDERS = new Set([ "WebGpuExecutionProvider", ]); -const CUDA_VERSIONS = new Set(["auto", "cpu", "cu118", "cu121", "cu124", "cu126", "cu128", "cu130", "cu132"]); +const CUDA_VERSIONS = new Set(["auto", "cpu", "cu118", "cu121", "cu124", "cu126", "cu128"]); const MODEL_SOURCES = new Set(["huggingface", "local", "azure"]); const MEMORY_OFFLOAD = new Set(["gpu_only", "auto"]); diff --git a/src/types.ts b/src/types.ts index 850ec561..60ec6c97 100644 --- a/src/types.ts +++ b/src/types.ts @@ -92,7 +92,7 @@ export interface UIState { /** Hugging Face load_kwargs device_map — GPU + host RAM when auto. */ memoryOffload: "gpu_only" | "auto"; /** Only tags with full dep resolution (torch index + ORT 1.26 + cu12 runtime). */ - cudaVersion: "auto" | "cpu" | "cu118" | "cu121" | "cu124" | "cu126" | "cu128" | "cu130" | "cu132"; + cudaVersion: "auto" | "cpu" | "cu118" | "cu121" | "cu124" | "cu126" | "cu128"; cacheDir: string; azureStr: string; distributedCaching: boolean;