diff --git a/docs-agent-mcp/mcp-server/citations.py b/docs-agent-mcp/mcp-server/citations.py index 141467a0..70d10097 100644 --- a/docs-agent-mcp/mcp-server/citations.py +++ b/docs-agent-mcp/mcp-server/citations.py @@ -14,6 +14,24 @@ def sanitize_evidence_text(value: object) -> str: return BARE_HTTP_URL.sub("", text) +CONTEXT_DELIMITER = "\n\n" +_SENTINEL_MARKER = "" + + +def extract_clean_content(text: object) -> str: + """Extract original clean content by stripping the breadcrumb envelope. + + Only splits on the sentinel when the text actually starts with a breadcrumb + header (``Document:`` or ``Section:`` prefix). This prevents false splits + on code or prose chunks that happen to contain the sentinel string verbatim + (e.g. a code-RAG hit that documents the ingestion pipeline itself). + """ + raw = str(text or "") + if raw.startswith(("Document:", "Section:")) and _SENTINEL_MARKER in raw: + return raw.split(_SENTINEL_MARKER, 1)[1].strip() + return raw + + def format_release_date(value: object) -> str: """Milvus stores release_date as epoch seconds; models misread raw integers.""" try: @@ -38,7 +56,8 @@ def format_docs_hits(hits: list[dict]) -> tuple[str, list[dict]]: release_date = entity.get("release_date") if release_date is not None: entry += f"\n**Release date:** {format_release_date(release_date)}" - entry += f"\n\n{sanitize_evidence_text(entity.get('content_text', ''))}\n" + content = extract_clean_content(entity.get("content_text", "")) + entry += f"\n\n{sanitize_evidence_text(content)}\n" results.append(entry) citation: dict = { @@ -84,7 +103,8 @@ def format_issues_hits(hits: list[dict]) -> tuple[str, list[dict]]: if labels: entry += f"\n**Labels:** {labels}" - entry += f"\n\n{sanitize_evidence_text(entity.get('content_text', ''))}\n" + issue_content = extract_clean_content(entity.get("content_text", "")) + entry += f"\n\n{sanitize_evidence_text(issue_content)}\n" results.append(entry) citation: dict = { @@ -126,7 +146,8 @@ def format_code_hits(hits: list[dict]) -> tuple[str, list[dict]]: if ftype: entry += f"\n**Type:** {ftype}" - entry += f"\n\n```\n{sanitize_evidence_text(entity.get('content_text', ''))}\n```\n" + code_content = extract_clean_content(entity.get("content_text", "")) + entry += f"\n\n```\n{sanitize_evidence_text(code_content)}\n```\n" results.append(entry) citation: dict = { diff --git a/docs-agent-mcp/mcp-server/compressor.py b/docs-agent-mcp/mcp-server/compressor.py index 7c43eae2..a75fd85b 100644 --- a/docs-agent-mcp/mcp-server/compressor.py +++ b/docs-agent-mcp/mcp-server/compressor.py @@ -4,6 +4,8 @@ import re +from citations import extract_clean_content + # Common English stop words to ignore during lexical term matching STOP_WORDS = { "a", @@ -250,8 +252,10 @@ def compress_hits(query: str, hits: list[dict], max_chars: int) -> list[dict]: if not hits or max_chars <= 0: return hits - # Early exit pass-through if all hits already fit within budget - total_chars = sum(len(hit.get("entity", {}).get("content_text", "")) for hit in hits) + # Early exit pass-through if all hits already fit within budget. + # Measure only the clean body text (excluding the breadcrumb envelope) so + # the fixed header does not trigger unnecessary compression when the body fits. + total_chars = sum(len(extract_clean_content(hit.get("entity", {}).get("content_text", ""))) for hit in hits) if total_chars <= max_chars: return hits @@ -262,7 +266,7 @@ def compress_hits(query: str, hits: list[dict], max_chars: int) -> list[dict]: surplus_budget = 0 for hit_idx, hit in enumerate(hits): - content = hit.get("entity", {}).get("content_text", "") + content = extract_clean_content(hit.get("entity", {}).get("content_text", "")) if not content: continue diff --git a/docs-agent-mcp/pipelines/utils/canonical_rag_ingest.py b/docs-agent-mcp/pipelines/utils/canonical_rag_ingest.py index 20f6e98c..9604cfa4 100644 --- a/docs-agent-mcp/pipelines/utils/canonical_rag_ingest.py +++ b/docs-agent-mcp/pipelines/utils/canonical_rag_ingest.py @@ -22,6 +22,9 @@ DEFAULT_TARGET_TOKENS = 350 DEFAULT_OVERLAP_TOKENS = 50 MAX_CONTENT_TEXT_CHARS = 2000 +CONTEXT_DELIMITER = "\n\n" +MAX_BREADCRUMB_HEADER_CHARS = 300 +MAX_CHUNK_BODY_CHARS = MAX_CONTENT_TEXT_CHARS - MAX_BREADCRUMB_HEADER_CHARS # 1700 CHARS_PER_TOKEN = 4 HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$") @@ -487,31 +490,28 @@ def _chunk_block( *, target_tokens: int, overlap_tokens: int, + max_body_chars: int = MAX_CHUNK_BODY_CHARS, ) -> list[tuple[str, str, list[LinkRef]]]: """Return (chunk_type, content_text, links) tuples for one canonical block.""" - heading_prefix = "" - if section.heading: - heading_prefix = f"{section.section_path}\n\n" - if block.block_type == "code_fence": content = block.content.strip() - if len(content) > MAX_CONTENT_TEXT_CHARS: - content = content[:MAX_CONTENT_TEXT_CHARS] + if len(content) > max_body_chars: + content = content[:max_body_chars] return [("code", content, block.links)] if block.block_type == "table": pieces = _split_table_by_tokens(block.content, target_tokens) if len(pieces) == 1 and estimate_tokens(pieces[0]) <= target_tokens: content = pieces[0] - if len(content) > MAX_CONTENT_TEXT_CHARS: - content = content[: MAX_CONTENT_TEXT_CHARS] + if len(content) > max_body_chars: + content = content[:max_body_chars] return [("table", content, block.links)] rows: list[tuple[str, str, list[LinkRef]]] = [] for piece in pieces: content = piece - if len(content) > MAX_CONTENT_TEXT_CHARS: - content = content[: MAX_CONTENT_TEXT_CHARS] + if len(content) > max_body_chars: + content = content[:max_body_chars] rows.append(("table_row", content, block.links)) return rows @@ -523,16 +523,16 @@ def _chunk_block( ) output: list[tuple[str, str, list[LinkRef]]] = [] for piece in prose_chunks: - content = heading_prefix + piece if heading_prefix else piece - if len(content) > MAX_CONTENT_TEXT_CHARS: - content = content[: MAX_CONTENT_TEXT_CHARS] + content = piece + if len(content) > max_body_chars: + content = content[:max_body_chars] chunk_type = "admonition" if content.lstrip().startswith(("NOTE:", "WARNING:")) else "text" output.append((chunk_type, content, block.links)) return output content = block.content.strip() - if len(content) > MAX_CONTENT_TEXT_CHARS: - content = content[: MAX_CONTENT_TEXT_CHARS] + if len(content) > max_body_chars: + content = content[:max_body_chars] chunk_type = "admonition" if block.block_type == "admonition" else "text" return [(chunk_type, content, block.links)] @@ -590,6 +590,104 @@ def chunk_canonical_document( return chunks +def build_document_breadcrumb(file_path: str, title: str = "") -> str: + """Build a human-readable document breadcrumb path from repository path and title. + + Examples: + content/en/docs/components/katib/early-stopping.md -> + 'Kubeflow Documentation > Components > Katib > Early Stopping' + """ + parts = ["Kubeflow Documentation"] + normalized = file_path.replace("\\", "/") + if "content/en/docs" in normalized: + rel = normalized.split("content/en/docs", 1)[1].lstrip("/") + rel = re.sub(r"(/_index)?\.(md|html)$", "", rel) + segments = [s.strip() for s in rel.split("/") if s.strip()] + if segments: + nice_segments = [ + re.sub(r"[-_]+", " ", s).strip().title() + for s in segments + ] + if title and title.strip(): + nice_segments[-1] = title.strip() + parts.extend(nice_segments) + elif title and title.strip(): + parts.append(title.strip()) + elif title and title.strip(): + parts.append(title.strip()) + elif file_path: + base = os.path.basename(normalized) + clean_base = re.sub(r"\.(md|html)$", "", base) + parts.append(re.sub(r"[-_]+", " ", clean_base).strip().title()) + + return SECTION_PATH_SEP.join(parts) + + +def _build_contextual_header(document_breadcrumb: str, section_heading: str) -> str: + """Build a Document/Section header bounded by MAX_BREADCRUMB_HEADER_CHARS.""" + doc_crumb = (document_breadcrumb or "").strip() + heading = (section_heading or "").strip() + if heading == doc_crumb: + heading = "" + + doc_line = f"Document: {doc_crumb}" if doc_crumb else "" + sec_line = f"Section: {heading}" if heading else "" + if not doc_line and not sec_line: + return "" + + metadata_budget = MAX_BREADCRUMB_HEADER_CHARS - len(CONTEXT_DELIMITER) + if doc_line and sec_line: + if len(doc_line) + 1 + len(sec_line) > metadata_budget: + avail = metadata_budget - 1 + sec_budget = min(len(sec_line), max(90, avail - len(doc_line))) + sec_line = sec_line[:sec_budget].rstrip() + doc_budget = avail - len(sec_line) + doc_line = doc_line[:doc_budget].rstrip() + elif doc_line: + doc_line = doc_line[:metadata_budget].rstrip() + else: + sec_line = sec_line[:metadata_budget].rstrip() + + lines = [line for line in (doc_line, sec_line) if line] + return "\n".join(lines) + CONTEXT_DELIMITER + + +def format_contextual_text( + content: str, + *, + document_breadcrumb: str, + section_heading: str = "", +) -> str: + """Prepend document breadcrumb and section heading to chunk content. + + Creates structured context: + Document: Kubeflow Documentation > Katib > Early Stopping + Section: Configuring the Median Stopping Rule + + [clean chunk content] + """ + clean_content = content.strip() + if not clean_content: + return "" + + header = _build_contextual_header(document_breadcrumb, section_heading) + + if len(header) + len(clean_content) <= MAX_CONTENT_TEXT_CHARS: + return f"{header}{clean_content}" + + budget = max(50, MAX_CONTENT_TEXT_CHARS - len(header)) + return f"{header}{clean_content[:budget]}" + + +def strip_context_delimiter(text: str) -> str: + """Remove the context delimiter sentinel before dense embedding.""" + if CONTEXT_DELIMITER in text: + return text.replace(CONTEXT_DELIMITER, "\n", 1) + if "" in text: + return text.replace("", "", 1).strip() + return text + + def build_citation_url(file_path: str, base_url: str) -> str: """Build a Kubeflow docs citation URL from a repository path.""" path_parts = file_path.split("/") @@ -762,7 +860,23 @@ def build_milvus_records( doc_status = infer_doc_status(file_path) records: list[dict[str, Any]] = [] + doc_breadcrumb = build_document_breadcrumb(file_path, parsed.title) + for chunk_idx, chunk in enumerate(chunks): + clean_text = chunk["content_text"].strip() + raw_section = (chunk.get("section_path") or chunk.get("heading") or "").strip() + prefix = f"{title}{SECTION_PATH_SEP}" + if raw_section.startswith(prefix): + section_heading = raw_section[len(prefix) :].strip() + else: + section_heading = raw_section + + contextual_text = format_contextual_text( + clean_text, + document_breadcrumb=doc_breadcrumb, + section_heading=section_heading, + ) + records.append( { "file_unique_id": file_unique_id, @@ -771,7 +885,7 @@ def build_milvus_records( "file_name": file_name, "citation_url": citation_url, "chunk_index": chunk_idx, - "content_text": chunk["content_text"][:MAX_CONTENT_TEXT_CHARS], + "content_text": contextual_text[:MAX_CONTENT_TEXT_CHARS], "title": title[:256], "weight": parsed.weight, "doc_type": doc_type[:32], @@ -830,13 +944,16 @@ def dumps_jsonl(records: Iterable[dict[str, Any]]) -> str: "CanonicalDocument", "CanonicalSection", "build_citation_url", + "build_document_breadcrumb", "build_milvus_records", "is_badge_only_chunk", "chunk_canonical_document", "extract_release_date", "dumps_jsonl", "estimate_tokens", + "format_contextual_text", "parse_and_chunk_file", "parse_canonical_document", "split_prose_by_tokens", + "strip_context_delimiter", ] diff --git a/docs-agent-mcp/pipelines/utils/milvus_store.py b/docs-agent-mcp/pipelines/utils/milvus_store.py index 434364b8..5dd0b1ac 100644 --- a/docs-agent-mcp/pipelines/utils/milvus_store.py +++ b/docs-agent-mcp/pipelines/utils/milvus_store.py @@ -16,6 +16,7 @@ DEFAULT_OVERLAP_TOKENS, DEFAULT_TARGET_TOKENS, build_milvus_records, + strip_context_delimiter, ) from utils import DEFAULT_EMBEDDING_BATCH_SIZE, DOCS_COLLECTION, embed_texts, truncate_for_tei @@ -232,7 +233,10 @@ def embed_chunk_records( return records batch_size = max(1, int(embedding_batch_size)) - texts = [truncate_for_tei(record["content_text"]) for record in records] + texts = [ + truncate_for_tei(strip_context_delimiter(record["content_text"])) + for record in records + ] vectors = embed_texts( texts, embeddings_service_url, diff --git a/tests/test_pipeline_utils.py b/tests/test_pipeline_utils.py index acccb5d8..0716b345 100644 --- a/tests/test_pipeline_utils.py +++ b/tests/test_pipeline_utils.py @@ -249,3 +249,242 @@ def fake_post(url, json, headers, timeout): long = "x" * 5000 embed_texts([long], "http://embeddings/embed", batch_size=1) assert len(sent[0]) == 1000 + + +class TestContextualRetrievalChunks: + """Tests for contextual chunk prefixing and breadcrumbs.""" + + def test_build_document_breadcrumb_from_docs_path(self): + from canonical_rag_ingest import build_document_breadcrumb + + path = "content/en/docs/components/katib/early-stopping.md" + breadcrumb = build_document_breadcrumb(path, title="Early Stopping") + assert breadcrumb == "Kubeflow Documentation > Components > Katib > Early Stopping" + + def test_build_document_breadcrumb_index_page(self): + from canonical_rag_ingest import build_document_breadcrumb + + path = "content/en/docs/components/pipelines/_index.md" + breadcrumb = build_document_breadcrumb(path, title="Pipelines") + assert breadcrumb == "Kubeflow Documentation > Components > Pipelines" + + def test_build_document_breadcrumb_fallback_title(self): + from canonical_rag_ingest import build_document_breadcrumb + + breadcrumb = build_document_breadcrumb("custom/path.md", title="Custom Guide") + assert breadcrumb == "Kubeflow Documentation > Custom Guide" + + def test_format_contextual_text_combines_breadcrumbs_and_content(self): + from canonical_rag_ingest import format_contextual_text + + content = "spec.replicas specifies the number of instances." + doc_crumb = "Kubeflow Documentation > Katib > Early Stopping" + heading = "Configuring the Median Stopping Rule" + + contextual = format_contextual_text( + content, + document_breadcrumb=doc_crumb, + section_heading=heading, + ) + + expected = ( + "Document: Kubeflow Documentation > Katib > Early Stopping\n" + "Section: Configuring the Median Stopping Rule\n" + "\n" + "spec.replicas specifies the number of instances." + ) + assert contextual == expected + + def test_format_contextual_text_omits_redundant_heading(self): + from canonical_rag_ingest import format_contextual_text + + content = "Introductory text." + doc_crumb = "Kubeflow Documentation > Overview" + + contextual = format_contextual_text( + content, + document_breadcrumb=doc_crumb, + section_heading=doc_crumb, + ) + assert "Section:" not in contextual + assert ( + "Document: Kubeflow Documentation > Overview\n\nIntroductory text." == contextual + ) + + def test_format_contextual_text_respects_max_chars(self): + from canonical_rag_ingest import MAX_CONTENT_TEXT_CHARS, format_contextual_text + + long_content = "a" * (MAX_CONTENT_TEXT_CHARS + 500) + contextual = format_contextual_text( + long_content, + document_breadcrumb="Kubeflow Documentation > Long Doc", + section_heading="Heading", + ) + assert len(contextual) <= MAX_CONTENT_TEXT_CHARS + assert contextual.startswith("Document:") + assert "\n" in contextual + + def test_chunk_block_reserves_budget_for_breadcrumb(self): + from canonical_rag_ingest import ( + MAX_CHUNK_BODY_CHARS, + CanonicalBlock, + CanonicalSection, + _chunk_block, + ) + + long_code = "print('hello')\n" * 200 + block = CanonicalBlock(block_type="code_fence", content=long_code) + section = CanonicalSection( + heading="Code Header", + heading_level=2, + section_path="Docs > Code Header", + ) + chunks = _chunk_block(block, section, target_tokens=350, overlap_tokens=50) + + assert len(chunks) == 1 + assert len(chunks[0][1]) <= MAX_CHUNK_BODY_CHARS + + def test_extract_clean_content_recovers_original_content(self): + mcp_dir = Path(__file__).parent.parent / "docs-agent-mcp" / "mcp-server" + if str(mcp_dir) not in sys.path: + sys.path.insert(0, str(mcp_dir)) + from canonical_rag_ingest import format_contextual_text + from citations import extract_clean_content + + original = "- Set median_stop_rule: true in the experiment spec." + contextual = format_contextual_text( + original, + document_breadcrumb="Kubeflow Documentation > Katib", + section_heading="Median Stop", + ) + clean = extract_clean_content(contextual) + assert clean == original + + def test_extract_clean_content_passes_through_legacy_content(self): + mcp_dir = Path(__file__).parent.parent / "docs-agent-mcp" / "mcp-server" + if str(mcp_dir) not in sys.path: + sys.path.insert(0, str(mcp_dir)) + from citations import extract_clean_content + + legacy = "Some legacy content without prefix." + assert extract_clean_content(legacy) == legacy + assert extract_clean_content("") == "" + + def test_build_milvus_records_applies_contextual_enrichment(self): + mcp_dir = Path(__file__).parent.parent / "docs-agent-mcp" / "mcp-server" + if str(mcp_dir) not in sys.path: + sys.path.insert(0, str(mcp_dir)) + from canonical_rag_ingest import build_milvus_records + from citations import extract_clean_content + + file_data = { + "path": "content/en/docs/components/katib/early-stopping.md", + "file_name": "early-stopping.md", + "content": ( + "---\n" + "title: Early Stopping\n" + "---\n\n" + "## Configuring Rules\n\n" + "Set median_stop_rule: true to stop trials early.\n" + ), + } + records = build_milvus_records( + file_data, + repo_name="website", + base_url="https://www.kubeflow.org/docs", + ) + assert len(records) > 0 + first_record = records[0] + assert "content_text" in first_record + assert "clean_content" not in first_record + assert first_record["content_text"].startswith( + "Document: Kubeflow Documentation > Components > Katib > Early Stopping" + ) + assert "Section: Configuring Rules" in first_record["content_text"] + assert "" in first_record["content_text"] + assert extract_clean_content(first_record["content_text"]) == "Set median_stop_rule: true to stop trials early." + + def test_extract_clean_content_preserves_document_and_content_text_without_sentinel(self): + mcp_dir = Path(__file__).parent.parent / "docs-agent-mcp" / "mcp-server" + if str(mcp_dir) not in sys.path: + sys.path.insert(0, str(mcp_dir)) + from citations import extract_clean_content + + prose = "Document: My CRD Schema\n\nContent:\nSet replicas: 3." + assert extract_clean_content(prose) == prose + + def test_format_contextual_text_caps_header_and_preserves_max_body(self): + from canonical_rag_ingest import ( + CONTEXT_DELIMITER, + MAX_BREADCRUMB_HEADER_CHARS, + MAX_CHUNK_BODY_CHARS, + MAX_CONTENT_TEXT_CHARS, + format_contextual_text, + ) + + long_breadcrumb = "Kubeflow Documentation > " + ("Very Long Component Name > " * 12) + long_heading = "Very Detailed Section Title " * 10 + body = "b" * MAX_CHUNK_BODY_CHARS + + contextual = format_contextual_text( + body, + document_breadcrumb=long_breadcrumb, + section_heading=long_heading, + ) + + assert len(contextual) <= MAX_CONTENT_TEXT_CHARS + assert CONTEXT_DELIMITER in contextual + header, extracted_body = contextual.split(CONTEXT_DELIMITER, 1) + assert len(header) + len(CONTEXT_DELIMITER) <= MAX_BREADCRUMB_HEADER_CHARS + assert extracted_body == body + + def test_strip_context_delimiter_removes_sentinel_only(self): + from canonical_rag_ingest import format_contextual_text, strip_context_delimiter + + contextual = format_contextual_text( + "spec.replicas sets instances.", + document_breadcrumb="Kubeflow Documentation > Katib", + section_heading="Replicas", + ) + stripped = strip_context_delimiter(contextual) + assert "" not in stripped + assert "Document: Kubeflow Documentation > Katib" in stripped + assert "Section: Replicas" in stripped + assert "spec.replicas sets instances." in stripped + assert strip_context_delimiter("Plain text without sentinel") == "Plain text without sentinel" + + def test_embed_chunk_records_strips_sentinel_before_embed_texts(self, monkeypatch): + from unittest.mock import MagicMock + + monkeypatch.setitem(sys.modules, "pymilvus", MagicMock()) + sys.modules.pop("milvus_store", None) + import milvus_store + + captured = [] + + def fake_embed_texts(texts, url, batch_size=8): + captured.extend(texts) + return [[0.1] * 768 for _ in texts] + + monkeypatch.setattr(milvus_store, "embed_texts", fake_embed_texts) + + records = [ + { + "content_text": ( + "Document: Kubeflow Documentation > Katib\n" + "Section: Early Stopping\n" + "\n" + "Set median_stop_rule: true." + ) + } + ] + result = milvus_store.embed_chunk_records( + records, + embeddings_service_url="http://embeddings/embed", + ) + + assert len(captured) == 1 + assert "" not in captured[0] + assert "Document: Kubeflow Documentation > Katib" in captured[0] + assert "Set median_stop_rule: true." in captured[0] + assert "" in result[0]["content_text"]