diff --git a/olive-mcp-server/Dockerfile b/olive-mcp-server/Dockerfile index b848dc3f..3292a898 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,22 @@ WORKDIR /build COPY pyproject.toml ./ COPY olive_mcp_server/ ./olive_mcp_server/ -RUN pip install --no-cache-dir --prefix=/install . "mcp<2" +# 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 \ + --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 +# 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 +34,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 --chown=mcp:mcp /root/.cache/huggingface /home/mcp/.cache/huggingface + 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 +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/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..b8ec7e2e 100644 --- a/olive-mcp-server/olive_mcp_server/tools/docs_search.py +++ b/olive-mcp-server/olive_mcp_server/tools/docs_search.py @@ -1,11 +1,29 @@ -"""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 logging +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, +) + +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"} @@ -14,6 +32,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 or file count changes). +_KB_TEXTS: list[tuple[str, str]] = [] +_KB_EMBEDDINGS: np.ndarray | None = None +_KB_INDEX_MTIME: tuple[float, int] = (-1.0, -1) +_KB_INDEX_LOCK = threading.Lock() def _flatten(obj: Any, prefix: str = "") -> list[tuple[str, str]]: @@ -45,37 +79,142 @@ def _load_kb_text() -> list[tuple[str, str]]: return all_text +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: + continue + try: + mtimes.append(file.stat().st_mtime) + except OSError: + continue + return (max(mtimes) if mtimes else 0.0, len(mtimes)) + + +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 _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. +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 + return _keyword_search(kb_texts, terms, top_k) + 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) + + +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 + 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 - 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), _LAST_FETCH_TIME + _LIVE_FETCH_GENERATION += 1 + my_generation = _LIVE_FETCH_GENERATION try: # Lazy import: BeautifulSoup/requests are optional for local-KB-only search. @@ -86,12 +225,20 @@ 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 - except Exception: # noqa: BLE001 - pass # Keep stale cache or return empty on failure. + with _LIVE_FETCH_LOCK: + # 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: + logger.debug("Live docs fetch failed; keeping stale cache", exc_info=True) - return _LIVE_CACHE + with _LIVE_FETCH_LOCK: + return dict(_LIVE_CACHE), _LAST_FETCH_TIME def _split_live_snippets(pages: dict[str, str]) -> list[tuple[str, str]]: @@ -105,25 +252,70 @@ 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. + + 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_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_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 + _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 [] + results = semantic_search( + query, + snippets, + embeddings, + top_k, + threshold=DEFAULT_THRESHOLD, + ) + if results: + return results + return _keyword_search(snippets, terms, top_k) + 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: + logger.debug("Live-doc keyword fallback also failed", exc_info=True) 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] - except Exception: # noqa: BLE001 - return [] def search_olive_documentation(query: str, top_k: int = 5, live: bool = True) -> dict[str, Any]: @@ -136,6 +328,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 +337,37 @@ 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"]) + 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) + ) + 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..8b2416dc --- /dev/null +++ b/olive-mcp-server/olive_mcp_server/tools/embeddings.py @@ -0,0 +1,167 @@ +"""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 collections.abc import Iterable, Sequence +from typing import Any + +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: 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. + """ + 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( + texts_list, + 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..e2e3bff4 --- /dev/null +++ b/olive-mcp-server/olive_mcp_server/tools/passive_context.py @@ -0,0 +1,122 @@ +"""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 + +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.""" + 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: + logger.warning("KB retrieval failed for pipeline context", exc_info=True) + 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..ffe63767 100644 --- a/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py +++ b/olive-mcp-server/olive_mcp_server/tools/troubleshooting.py @@ -1,16 +1,27 @@ """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 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 +31,27 @@ 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]] = {} +_TS_INDEX_CACHE_MAX = 8 + def _get_frequency_key(matched_entry: str | None, error_message: str) -> str: """Derive a stable key for frequency tracking.""" @@ -69,20 +95,128 @@ 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. """ + 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) + # 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 + + +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 +242,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 +254,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 +275,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 +300,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 +314,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 +336,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 +349,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" @@ -287,28 +412,62 @@ 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 = "", 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() + freq_key = _get_frequency_key(None, error_message) + freq = _record_occurrence(freq_key) + return _build_diagnosis_payload(best, None, None, False, pass_name, freq) + resolved = _resolve_domain(domain) best: dict[str, Any] | None = None @@ -351,26 +510,7 @@ 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 { - "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( @@ -379,18 +519,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 +535,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..dc50b5ca 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,<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 new file mode 100644 index 00000000..01cd469f --- /dev/null +++ b/olive-mcp-server/tests/test_docs_search_semantic.py @@ -0,0 +1,308 @@ +"""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, -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, -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( + 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, 2)) + 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, 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 + 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"], 1) + + 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, 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, 1) + assert docs_search._KB_TEXTS[0][0] == "new.path" + + +def test_live_fetch_generation_ignores_stale_completion(monkeypatch: pytest.MonkeyPatch): + """An older in-flight fetch completing after a newer one must not win. + + 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): + i = call_i["n"] + call_i["n"] += 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"}} + + import olive_mcp_server.fetchers.official_docs_fetcher as fetcher + + monkeypatch.setattr(fetcher, "fetch_official_docs", fake_fetch) + + 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 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())) + + +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" 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..a8f6cab6 100644 --- a/olive-mcp-server/tests/test_integration.py +++ b/olive-mcp-server/tests/test_integration.py @@ -11,23 +11,15 @@ 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", - } - 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 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_tools.py b/olive-mcp-server/tests/test_tools.py index 9d2d3e73..4062c956 100644 --- a/olive-mcp-server/tests/test_tools.py +++ b/olive-mcp-server/tests/test_tools.py @@ -160,14 +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."}, - ) + 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"]) 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" diff --git a/src/components/features/BatchProcessingPanel.test.tsx b/src/components/features/BatchProcessingPanel.test.tsx index 31015204..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 @@ -180,6 +191,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/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", 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/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 54216a3f..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"]); @@ -221,10 +221,15 @@ 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) && + !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/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 +245,11 @@ export function salvageChatActionPatchFromLooseJson(parsed: unknown): ChatAction } if ( - (/convert/.test(key) || key === "onnx" || /onnx/.test(key)) && + !isNegated && + (/convert/.test(key) || + key === "onnx" || + /onnx/.test(key) || + (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; 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"); 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. */