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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 65 additions & 34 deletions docs-agent-mcp/pipelines/code-pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,14 @@ def download_github_code(
Args:
repos: Comma-separated repos (e.g., "kubeflow/manifests,kubeflow/pipelines").
directory_paths: Comma-separated directory paths to crawl per repo
(e.g., "apps/pipeline,common/istio").
(e.g., "applications/pipeline,common/istio").
file_extensions: Comma-separated extensions to include
(e.g., "yaml,yml,py,json").
github_token: GitHub personal access token.
code_data: Output dataset path.
"""
import requests
import json
import base64
import time
import os

Expand All @@ -52,66 +51,89 @@ def resolve_github_token(token):
headers = {"Authorization": f"token {github_token}"} if github_token else {}
extensions = [ext.strip().lstrip(".") for ext in file_extensions.split(",")]

def api_request(url, params=None):
"""GitHub API request with rate limit handling and retries."""
def request_with_retries(url, params=None):
"""GET with GitHub rate-limit handling; raises once the retries are spent.

A directory the operator asked for must not quietly resolve to nothing,
so an unrecoverable response ends the component instead of returning None.
"""
max_retries = 3
last_error = "no response"
for attempt in range(max_retries):
try:
resp = requests.get(url, params=params, headers=headers)

if resp.status_code == 403:
remaining = resp.headers.get("X-RateLimit-Remaining", "0")
if remaining == "0":
if resp.status_code == 200:
return resp

# GitHub reports both primary and secondary rate limits as 403
# or 429; a secondary limit carries Retry-After rather than a
# zeroed X-RateLimit-Remaining.
if resp.status_code in (403, 429):
retry_after = resp.headers.get("Retry-After", "")
if retry_after or resp.headers.get("X-RateLimit-Remaining") == "0":
reset_time = int(resp.headers.get("X-RateLimit-Reset", 0))
wait_time = max(reset_time - int(time.time()), 60)
if retry_after.isdigit():
wait_time = int(retry_after)
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(min(wait_time, 300))
last_error = f"rate limited (HTTP {resp.status_code})"
continue

if resp.status_code == 200:
return resp.json()
else:
print(f"API error: HTTP {resp.status_code} for {url}")
return None
last_error = f"HTTP {resp.status_code}"
# A 4xx will not change on retry; a 5xx might.
if resp.status_code < 500:
break

except Exception as e:
print(f"Request failed (attempt {attempt+1}): {e}")
last_error = str(e)

if attempt < max_retries - 1:
time.sleep(2 ** attempt)

return None
raise RuntimeError(f"GitHub request failed for {url}: {last_error}")

def get_files_recursive(owner, name, path):
"""Recursively fetch files from a GitHub directory."""
files = []
url = f"https://api.github.com/repos/{owner}/{name}/contents/{path}"
items = api_request(url)
items = request_with_retries(url).json()

if not items or not isinstance(items, list):
return files
if not isinstance(items, list):
raise RuntimeError(f"Expected a directory listing at {owner}/{name}/{path}")

for item in items:
if item["type"] == "file":
ext = item["name"].rsplit(".", 1)[-1].lower() if "." in item["name"] else ""
# Also include extensionless files like Dockerfile, Makefile
include_no_ext = item["name"] in ("Dockerfile", "Makefile", "Kustomization")
if ext in extensions or include_no_ext:
# Read the blob from the listing's raw URL. The Contents API
# only base64-encodes files under 1 MiB; above that it answers
# 200 with encoding "none" and an empty content field, which
# was stored as an empty file and dropped further down.
download_url = item.get("download_url")
if not download_url:
print(f"Skipping {item['path']}: no raw URL (submodule)")
continue
blob = request_with_retries(download_url)
try:
file_resp = api_request(item["url"])
if file_resp and "content" in file_resp:
content = base64.b64decode(file_resp["content"]).decode("utf-8")
files.append({
"path": item["path"],
"content": content,
"file_name": item["name"],
"repo": f"{owner}/{name}",
# Preserve GitHub's canonical page URL. Repositories do
# not all use `main` (kubeflow/katib uses `master`), and
# reconstructing this URL downstream creates dead or
# non-canonical citations even when retrieval is correct.
"citation_url": file_resp.get("html_url") or item.get("html_url", ""),
})
except Exception as e:
print(f"Error decoding {item['path']}: {e}")
content = blob.content.decode("utf-8")
except UnicodeDecodeError:
print(f"WARNING: skipping {item['path']}: not valid UTF-8")
continue
files.append({
"path": item["path"],
"content": content,
"file_name": item["name"],
"repo": f"{owner}/{name}",
# Preserve GitHub's canonical page URL. Repositories do
# not all use `main` (kubeflow/katib uses `master`), and
# reconstructing this URL downstream creates dead or
# non-canonical citations even when retrieval is correct.
"citation_url": item.get("html_url", ""),
})
elif item["type"] == "dir":
files.extend(get_files_recursive(owner, name, item["path"]))

Expand All @@ -134,6 +156,8 @@ def get_files_recursive(owner, name, path):
files = get_files_recursive(owner, name, dir_path)
all_files.extend(files)
print(f" Found {len(files)} files in {dir_path}/")
if not files:
print(f" WARNING: no {file_extensions} files under {dir_path}/")

print(f"Total code files fetched: {len(all_files)}")

Expand Down Expand Up @@ -389,6 +413,11 @@ def chunk_code_file(content, file_path, c_size, c_overlap):
)
response.raise_for_status()
vectors = response.json()
if not isinstance(vectors, list) or len(vectors) != len(texts):
raise RuntimeError(
f"Embeddings service returned {len(vectors) if isinstance(vectors, list) else type(vectors)} "
f"vectors for batch of {len(texts)}"
)
for idx, vector in enumerate(vectors):
batch[idx]["embedding"] = vector

Expand Down Expand Up @@ -553,7 +582,9 @@ def store_code_milvus(
)
def code_rag_pipeline(
repos: str = "kubeflow/manifests",
directory_paths: str = "apps/pipeline/upstream,apps/katib,common/istio,apps/jupyter",
directory_paths: str = (
"applications/pipeline,applications/katib,applications/notebooks-v1,common/istio"
),
file_extensions: str = "yaml,yml,py,json",
github_token: str = "",
chunk_size: int = 1000,
Expand Down
2 changes: 1 addition & 1 deletion tests/eval/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Known gaps against **default** pipeline arguments:
|---|---|---|
| Katib hyperparameter tuning | `website` `content/en/docs/components/katib` → configure-experiment | Yes, if the docs full/incremental pipeline has been run on `content/en/docs` |
| KServe deploymentMode / Knative vs Serverless | `kserve/kserve#5885` | **No.** Issues default is `kubeflow/kubeflow,kubeflow/pipelines,kubeflow/manifests` |
| Katib Experiment YAML | `kubeflow/katib` `examples/v1beta1/hp-tuning/random.yaml` | **No.** Code default is `kubeflow/manifests` `apps/katib` (install YAML/CRDs) |
| Katib Experiment YAML | `kubeflow/katib` `examples/v1beta1/hp-tuning/random.yaml` | **No.** Code default is `kubeflow/manifests` `applications/katib` (install YAML/CRDs) |

## 2. Ingest the missing sources

Expand Down
2 changes: 1 addition & 1 deletion tests/eval/queries.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"ingest": {
"pipeline": "docs-agent-mcp/pipelines/code-pipeline.py",
"compiled": "code_rag_pipeline.yaml",
"why": "Default code pipeline is kubeflow/manifests apps/katib (install manifests/CRDs), not kubeflow/katib examples/. random.yaml will not be in the index until that repo/path is ingested.",
"why": "Default code pipeline is kubeflow/manifests applications/katib (install manifests/CRDs), not kubeflow/katib examples/. random.yaml will not be in the index until that repo/path is ingested.",
"arguments": {
"repos": "kubeflow/katib",
"directory_paths": "examples/v1beta1/hp-tuning",
Expand Down
149 changes: 146 additions & 3 deletions tests/test_code_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ def load_code_pipeline_module():


class FakeResponse:
def __init__(self, payload):
def __init__(self, payload=None, text="", status_code=200, headers=None):
self.payload = payload
self.status_code = 200
self.headers = {}
self.text = text
self.content = text.encode("utf-8")
self.status_code = status_code
self.headers = headers or {}

def json(self):
return self.payload
Expand All @@ -45,6 +47,7 @@ def test_code_pipeline_preserves_github_canonical_citation_url(monkeypatch, tmp_
source_url = "https://github.com/kubeflow/katib/blob/master/examples/v1beta1/hp-tuning/random.yaml"
contents_url = "https://api.github.com/repos/kubeflow/katib/contents/examples/v1beta1/hp-tuning"
file_api_url = "https://api.github.com/repos/kubeflow/katib/contents/random.yaml"
raw_url = "https://raw.githubusercontent.com/kubeflow/katib/master/examples/v1beta1/hp-tuning/random.yaml"
yaml_text = "apiVersion: kubeflow.org/v1beta1\nkind: Experiment\nmetadata:\n name: random\n"

def fake_get(url, params=None, headers=None):
Expand All @@ -56,6 +59,7 @@ def fake_get(url, params=None, headers=None):
"name": "random.yaml",
"path": "examples/v1beta1/hp-tuning/random.yaml",
"url": file_api_url,
"download_url": raw_url,
"html_url": source_url,
}
]
Expand All @@ -67,6 +71,8 @@ def fake_get(url, params=None, headers=None):
"html_url": source_url,
}
)
if url == raw_url:
return FakeResponse(text=yaml_text)
raise AssertionError(f"Unexpected GitHub URL: {url}")

monkeypatch.setattr("requests.get", fake_get)
Expand Down Expand Up @@ -267,3 +273,140 @@ def test_oversized_yaml_subchunks_preserve_metadata(self):
assert chunk["resource_name"] == "large-config"
assert chunk["resource_namespace"] == "kubeflow"
assert chunk["file_type"] == "yaml"


def test_code_pipeline_downloads_files_over_the_contents_api_size_cap(monkeypatch, tmp_path):
"""Above 1 MiB the Contents API returns no content, so the raw URL must be used."""
module = load_code_pipeline_module()
contents_url = "https://api.github.com/repos/kubeflow/manifests/contents/applications/kserve"
file_api_url = "https://api.github.com/repos/kubeflow/manifests/contents/kserve.yaml"
raw_url = "https://raw.githubusercontent.com/kubeflow/manifests/master/applications/kserve/kserve.yaml"
html_url = "https://github.com/kubeflow/manifests/blob/master/applications/kserve/kserve.yaml"
yaml_text = "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: kserve\n" + ("# padding\n" * 2000)

def fake_get(url, params=None, headers=None):
if url == contents_url:
return FakeResponse(
[
{
"type": "file",
"name": "kserve.yaml",
"path": "applications/kserve/kserve.yaml",
"size": 7051337,
"url": file_api_url,
"download_url": raw_url,
"html_url": html_url,
}
]
)
if url == file_api_url:
# What GitHub actually answers for a blob over the cap.
return FakeResponse({"encoding": "none", "content": "", "html_url": html_url})
if url == raw_url:
return FakeResponse(text=yaml_text)
raise AssertionError(f"Unexpected GitHub URL: {url}")

monkeypatch.setattr("requests.get", fake_get)
downloaded_path = tmp_path / "downloaded.jsonl"
module.download_github_code.python_func(
repos="kubeflow/manifests",
directory_paths="applications/kserve",
file_extensions="yaml,yml",
github_token="test-token",
code_data=SimpleNamespace(path=str(downloaded_path)),
)

downloaded = json.loads(downloaded_path.read_text())
assert downloaded["content"] == yaml_text
assert downloaded["citation_url"] == html_url


def test_code_pipeline_fails_when_a_configured_directory_is_missing(monkeypatch, tmp_path):
"""A directory that 404s must end the run, not report zero files and succeed."""
module = load_code_pipeline_module()

monkeypatch.setattr("requests.get", lambda url, params=None, headers=None: FakeResponse(status_code=404))
monkeypatch.setattr("time.sleep", lambda seconds: None)

with pytest.raises(RuntimeError, match="HTTP 404"):
module.download_github_code.python_func(
repos="kubeflow/manifests",
directory_paths="apps/katib",
file_extensions="yaml,yml",
github_token="test-token",
code_data=SimpleNamespace(path=str(tmp_path / "downloaded.jsonl")),
)


def test_code_pipeline_rejects_a_short_embeddings_response(monkeypatch, tmp_path):
"""A truncated batch would otherwise leave records with no embedding at all."""
module = load_code_pipeline_module()
source_path = tmp_path / "downloaded.jsonl"
source_path.write_text(
"\n".join(
json.dumps(
{
"path": f"applications/katib/manifest-{index}.yaml",
"content": f"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: cm-{index}\n",
"file_name": f"manifest-{index}.yaml",
"repo": "kubeflow/manifests",
"citation_url": f"https://github.com/kubeflow/manifests/blob/master/m-{index}.yaml",
}
)
for index in range(3)
)
+ "\n"
)

monkeypatch.setattr("requests.post", lambda *args, **kwargs: FakeResponse([[0.1, 0.2]]))

with pytest.raises(RuntimeError, match="vectors for batch of 3"):
module.chunk_and_embed_code.python_func(
code_data=SimpleNamespace(path=str(source_path)),
chunk_size=1000,
chunk_overlap=100,
embeddings_service_url="http://embeddings.test/embed",
embedding_batch_size=8,
embedded_data=SimpleNamespace(path=str(tmp_path / "embedded.jsonl")),
)


def test_code_pipeline_waits_out_a_secondary_rate_limit(monkeypatch, tmp_path):
"""A secondary rate limit answers 429 with Retry-After and must be waited out."""
module = load_code_pipeline_module()
contents_url = "https://api.github.com/repos/kubeflow/manifests/contents/common/istio"
raw_url = "https://raw.githubusercontent.com/kubeflow/manifests/master/common/istio/base.yaml"
listing = [
{
"type": "file",
"name": "base.yaml",
"path": "common/istio/base.yaml",
"download_url": raw_url,
"html_url": "https://github.com/kubeflow/manifests/blob/master/common/istio/base.yaml",
}
]
attempts = []
waited = []

def fake_get(url, params=None, headers=None):
attempts.append(url)
if url == contents_url and attempts.count(contents_url) == 1:
return FakeResponse(status_code=429, headers={"Retry-After": "7"})
if url == contents_url:
return FakeResponse(listing)
return FakeResponse(text="apiVersion: v1\nkind: Namespace\nmetadata:\n name: istio-system\n")

monkeypatch.setattr("requests.get", fake_get)
monkeypatch.setattr("time.sleep", lambda seconds: waited.append(seconds))

downloaded_path = tmp_path / "downloaded.jsonl"
module.download_github_code.python_func(
repos="kubeflow/manifests",
directory_paths="common/istio",
file_extensions="yaml,yml",
github_token="test-token",
code_data=SimpleNamespace(path=str(downloaded_path)),
)

assert waited == [7]
assert json.loads(downloaded_path.read_text())["file_name"] == "base.yaml"