From 68b23c2d10cff7a00f768b6a6033763d0e7fc93e Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Mon, 16 Nov 2026 22:57:32 +0530 Subject: [PATCH 1/2] feat(ingest): corpus source with pinned-ref tarball cache, url mapping, and exclusions (T05) --- src/caliper/ingest/__init__.py | 1 + src/caliper/ingest/source.py | 407 +++++++++++++++++++++++++++++++++ tests/unit/test_source.py | 385 +++++++++++++++++++++++++++++++ 3 files changed, 793 insertions(+) create mode 100644 src/caliper/ingest/__init__.py create mode 100644 src/caliper/ingest/source.py create mode 100644 tests/unit/test_source.py diff --git a/src/caliper/ingest/__init__.py b/src/caliper/ingest/__init__.py new file mode 100644 index 0000000..6fba73e --- /dev/null +++ b/src/caliper/ingest/__init__.py @@ -0,0 +1 @@ +"""`ingest` component package (§7.4) — T05 marker only; implementation lands with T07.""" diff --git a/src/caliper/ingest/source.py b/src/caliper/ingest/source.py new file mode 100644 index 0000000..9e7716c --- /dev/null +++ b/src/caliper/ingest/source.py @@ -0,0 +1,407 @@ +"""Corpus source: pinned-ref tarball fetch + cache, A1 URL mapping, page discovery (§7.4). + +Downloads the `MicrosoftDocs/azure-docs` tarball exactly once at a pinned ref: +the branch head SHA is resolved via the GitHub API at first fetch and recorded +in the cache as `main@<7-char sha>` (§9.4 `source_ref`). The tarball is cached +under the cache dir keyed by SHA; every later call re-serves the cache with no +network call unless `refresh=True` re-resolves and refetches. This component +performs no database writes (`requests`/`runs` are never touched) and never +modifies or redistributes corpus files — the cache holds local copies for +private indexing only (NFR-06). + +URL mapping per A1: `articles/azure-functions/.md` maps to +`https://learn.microsoft.com/en-us/azure/azure-functions/`, analogously +for `articles/service-bus-messaging/.md`. While A1 holds, +learn.microsoft.com is never scraped; the only fallback — the Learn TOC-API +crawler — stays behind the single unimplemented seam `_fetch_via_toc_api` +(§7.4). + +The HTTP layer is one injectable seam (§15): `fetcher: Callable[[str], bytes]`, +defaulting to the httpx implementation. Tests inject a fake serving local +fixture bytes — no network, no `patch()` on internals. +""" + +from __future__ import annotations + +import json +import logging +import os +import re +from collections.abc import Callable +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from pathlib import Path + +import httpx + +from caliper.config import CaliperConfig + +_LOGGER = logging.getLogger(__name__) + +# --- Constants (§7.4, §11.2) --------------------------------------------------- + +#: §11.2: paths live in the environment, never in the fingerprinted config +#: model. `CaliperConfig` has no cache-dir field (recorded in docs/TASKS.md +#: Notes), so the cache dir is read from this env var with the §11.2 default. +CACHE_DIR_ENV_VAR = "CALIPER_CACHE_DIR" +DEFAULT_CACHE_DIR = "data/cache" + +#: The corpus repository and the branch whose head pins the frozen corpus. +AZURE_DOCS_REPO = "MicrosoftDocs/azure-docs" +AZURE_DOCS_BRANCH = "main" + +#: §7.4/OQ3: the two article trees read from the corpus (every other +#: `articles/*` tree is out of scope). +ARTICLE_TREES: tuple[str, ...] = ( + "articles/azure-functions", + "articles/service-bus-messaging", +) + +#: A1: Learn's public base URL for the `articles/` content. +LEARN_BASE_URL = "https://learn.microsoft.com/en-us/azure" + +#: Generous but bounded: the tarball is tens of MB (§16, no unbounded waits). +HTTP_TIMEOUT_S = 300.0 + +#: Headers acceptable to both the GitHub API (Accept) and codeload (ignored). +_HTTP_HEADERS = { + "user-agent": "caliper/0.1.0 (local documentation corpus fetcher)", + "accept": "application/vnd.github+json, application/octet-stream", +} + +_CACHE_SUBDIR = "azure-docs" + +_SHA_RE = re.compile(r"[0-9a-f]{40}") + + +# --- Typed component exception (§11.3) ------------------------------------------ + + +class SourceError(Exception): + """A corpus-source failure (§11.3): ref resolution, tarball fetch, cache + metadata, or an out-of-contract corpus path. Mapped to the §9 error + envelope at the CLI/web edges (T07/T12); no bare exceptions escape.""" + + +# --- Cache metadata (read by T07 for the §9.4 summary) --------------------------- + + +@dataclass(frozen=True) +class CacheMeta: + """The cached pin: which commit is frozen and when it was fetched. + + `source_ref` is the §9.4 ingestion-summary value; T07 reads it via + `read_cache_meta` — no network, no re-resolution of the ref. + """ + + branch: str + sha: str + source_ref: str + fetched_at: str + + +# --- HTTP seam (§15) -------------------------------------------------------------- + + +#: The single HTTP touchpoint of this component: fetch `url`, return the raw +#: response body. The default implementation is `_http_fetch`; tests inject a +#: fake through the public `fetcher` parameter — no network, no patch(). +Fetcher = Callable[[str], bytes] + + +def _http_fetch(url: str) -> bytes: + """The default Fetcher: one httpx GET, strict status handling, body out.""" + response = httpx.get(url, timeout=HTTP_TIMEOUT_S, headers=_HTTP_HEADERS, follow_redirects=True) + response.raise_for_status() + return response.content + + +def _fetch_bytes(fetcher: Fetcher, url: str, describe: str) -> bytes: + """Run one fetcher call, wrapping every failure as SourceError (§11.3). + + The wrap is the component boundary: callers (T07/CLI) only ever see the + typed error. Raw failures stay at DEBUG, never user-facing. + """ + try: + return fetcher(url) + except SourceError: + raise + except Exception as exc: # noqa: BLE001 - single typed wrap, never swallowed + _LOGGER.debug("%s failed", describe, exc_info=True) + raise SourceError(f"{describe} failed for {url}: {type(exc).__name__}: {exc}") from exc + + +# --- Wire URLs (public: T07 logs them alongside the summary) ---------------------- + + +def commits_api_url(branch: str = AZURE_DOCS_BRANCH) -> str: + """GitHub API URL for the branch head commit (the §7.4 pin resolution).""" + return f"https://api.github.com/repos/{AZURE_DOCS_REPO}/commits/{branch}" + + +def tarball_url(sha: str) -> str: + """Codeload tarball URL for an exact commit SHA (the §7.4 pin download).""" + return f"https://codeload.github.com/{AZURE_DOCS_REPO}/tar.gz/{sha}" + + +def format_source_ref(sha: str) -> str: + """§9.4 `source_ref` format: `main@<7-char sha>` (e.g. `main@9f3ab12`).""" + if _SHA_RE.fullmatch(sha) is None: + raise SourceError(f"expected a 40-hex commit SHA, got {sha!r}") + return f"{AZURE_DOCS_BRANCH}@{sha[:7]}" + + +# --- Cache layout ------------------------------------------------------------------ + + +def _cache_dir(cfg: CaliperConfig) -> Path: + """The cache dir: CALIPER_CACHE_DIR (§11.2), default `data/cache`. + + `cfg` is part of the frozen §7.4 signature; the fingerprint model + deliberately holds no paths (§11.2), and `CaliperConfig` has no cache-dir + field (choice recorded in docs/TASKS.md Notes). If a field is ever added, + prefer it over the env var here. + """ + return Path(os.environ.get(CACHE_DIR_ENV_VAR, DEFAULT_CACHE_DIR)) + + +def _component_dir(cache_root: Path) -> Path: + """The per-source cache directory: `/azure-docs/`.""" + return cache_root / _CACHE_SUBDIR + + +def _pointer_path(cache_root: Path) -> Path: + """The per-branch pin pointer: `/azure-docs/main.json`.""" + return _component_dir(cache_root) / f"{AZURE_DOCS_BRANCH}.json" + + +def _tarball_path(cache_root: Path, sha: str) -> Path: + """The SHA-keyed tarball path (distinct pinned refs coexist).""" + return _component_dir(cache_root) / f"{sha}.tar.gz" + + +def _now_iso() -> str: + """ISO-8601 UTC timestamp (§8 column convention).""" + return datetime.now(UTC).isoformat() + + +def _read_pointer(pointer: Path) -> CacheMeta: + """Parse + validate the pin pointer; SourceError on any problem. + + A corrupt pin raises rather than masquerading as a cache miss: the pin is + what keeps the corpus frozen, and silently refetching over it would move + the pin without `refresh`. (Writes are atomic, so corruption means manual + tampering — fix or delete the cache dir.) + """ + try: + raw: object = json.loads(pointer.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SourceError(f"cache pin file {pointer} is unreadable: {exc}") from exc + if not isinstance(raw, dict): + raise SourceError(f"cache pin file {pointer} must be a JSON object") + branch = raw.get("branch") + sha = raw.get("sha") + source_ref = raw.get("source_ref") + fetched_at = raw.get("fetched_at") + if not isinstance(branch, str) or branch != AZURE_DOCS_BRANCH: + raise SourceError( + f"cache pin file {pointer} is for branch {branch!r}, not {AZURE_DOCS_BRANCH!r}" + ) + if not isinstance(sha, str) or _SHA_RE.fullmatch(sha) is None: + raise SourceError(f"cache pin file {pointer} has no valid 40-hex 'sha'") + if not isinstance(source_ref, str) or source_ref != format_source_ref(sha): + raise SourceError(f"cache pin file {pointer} has an inconsistent 'source_ref'") + if not isinstance(fetched_at, str) or not fetched_at: + raise SourceError(f"cache pin file {pointer} has no 'fetched_at' timestamp") + return CacheMeta(branch=branch, sha=sha, source_ref=source_ref, fetched_at=fetched_at) + + +def _write_pointer(pointer: Path, meta: CacheMeta) -> None: + """Write the pin pointer atomically (tmp + os.replace, crash-safe).""" + pointer.parent.mkdir(parents=True, exist_ok=True) + tmp = pointer.with_name(f"{pointer.name}.tmp") + tmp.write_text(json.dumps(asdict(meta), indent=2) + "\n", encoding="utf-8") + os.replace(tmp, pointer) + + +def _cache_hit(cache_root: Path) -> Path | None: + """The cached tarball path when pin + tarball are both present, else None. + + A valid pin whose tarball vanished is a repairable miss (refetch); a + corrupt pin is a loud SourceError (see _read_pointer). + """ + pointer = _pointer_path(cache_root) + if not pointer.is_file(): + return None + meta = _read_pointer(pointer) + tarball = _tarball_path(cache_root, meta.sha) + if not tarball.is_file(): + _LOGGER.warning("cache pin exists but tarball %s is missing; refetching", tarball) + return None + return tarball + + +# --- Ref resolution + download (both via the Fetcher seam) ------------------------- + + +def _resolve_sha(fetcher: Fetcher) -> str: + """Resolve the branch head SHA once via the GitHub API (§7.4 pin).""" + url = commits_api_url() + raw = _fetch_bytes(fetcher, url, f"resolving {AZURE_DOCS_REPO} {AZURE_DOCS_BRANCH} head") + try: + payload: object = json.loads(raw) + except json.JSONDecodeError as exc: + raise SourceError(f"{url} returned invalid JSON") from exc + if not isinstance(payload, dict): + raise SourceError(f"{url} response must be a JSON object") + sha = payload.get("sha") + if not isinstance(sha, str) or _SHA_RE.fullmatch(sha) is None: + raise SourceError(f"{url} response has no 40-hex 'sha' commit") + return sha + + +def _download_tarball(fetcher: Fetcher, sha: str) -> bytes: + """Download the codeload tarball for the pinned SHA.""" + describe = f"fetching {AZURE_DOCS_REPO} tarball at {sha[:7]}" + return _fetch_bytes(fetcher, tarball_url(sha), describe) + + +# --- Public interface (frozen for T06/T07) ------------------------------------------ + + +def fetch_corpus( + cfg: CaliperConfig, + *, + refresh: bool = False, + fetcher: Fetcher | None = None, +) -> Path: + """Fetch the frozen corpus tarball once and cache it; return its path (§7.4). + + First call resolves the branch head SHA (GitHub API), downloads the + codeload tarball for that exact SHA, and caches it keyed by SHA plus a + pin pointer recording `source_ref` (§9.4) and the fetch timestamp. Any + later call with a complete cache returns the cached path with **no + network call at all** — the pin stays whatever was resolved at first + fetch. `refresh=True` re-resolves the ref and refetches unconditionally; + SHA-keyed storage keeps distinct refs coexisting. A tarball already on + disk for the resolved SHA is reused without redownloading (the bytes are + fetched exactly once per SHA). + + Both network steps go through the injected `fetcher` seam (§15). `cfg` + shapes the frozen §7.4 interface for T07's `run_ingest(cfg)`; the cache + directory comes from CALIPER_CACHE_DIR (§11.2 — see `_cache_dir`). + + Raises SourceError on any fetch, resolution, or cache-metadata failure. + """ + fetch: Fetcher = fetcher if fetcher is not None else _http_fetch + cache_root = _cache_dir(cfg) + if not refresh: + cached = _cache_hit(cache_root) + if cached is not None: + _LOGGER.info("corpus cache hit: %s", cached) + return cached + + sha = _resolve_sha(fetch) + tarball = _tarball_path(cache_root, sha) + if refresh or not tarball.is_file(): + blob = _download_tarball(fetch, sha) + tarball.parent.mkdir(parents=True, exist_ok=True) + tarball.write_bytes(blob) + meta = CacheMeta( + branch=AZURE_DOCS_BRANCH, + sha=sha, + source_ref=format_source_ref(sha), + fetched_at=_now_iso(), + ) + _write_pointer(_pointer_path(cache_root), meta) + _LOGGER.info("corpus cached: %s (source_ref %s)", tarball, meta.source_ref) + return tarball + + +def read_cache_meta(cfg: CaliperConfig) -> CacheMeta: + """The cached pin (§9.4 `source_ref`) without any network call. + + T07 touchpoint: supplies `source_ref` for the ingestion summary from the + cache instead of re-resolving the ref. Raises SourceError when nothing is + cached yet or the pin file is corrupt. + """ + pointer = _pointer_path(_cache_dir(cfg)) + if not pointer.is_file(): + raise SourceError( + f"no corpus cached yet (missing pin file {pointer}); run fetch_corpus first" + ) + return _read_pointer(pointer) + + +def page_to_url(rel_path: str) -> str: + """Map a corpus-relative page path to its public Learn URL (A1). + + `articles/azure-functions/.md` maps to + `https://learn.microsoft.com/en-us/azure/azure-functions/` and + analogously for `articles/service-bus-messaging/.md`; nested slugs + keep their subpath (Learn mirrors the docs tree). Backslashes are + normalized so Windows-built paths map identically. Raises SourceError for + paths outside the two §7.4/OQ3 trees, wrong extensions, or an empty slug; + `_`/`includes` filtering is `discover_pages`' job, not this mapping's. + """ + normalized = rel_path.replace("\\", "/") + for tree in ARTICLE_TREES: + prefix = f"{tree}/" + if normalized.startswith(prefix) and normalized.endswith(".md"): + slug = normalized.removeprefix(prefix).removesuffix(".md") + if slug: + return f"{LEARN_BASE_URL}/{tree.removeprefix('articles/')}/{slug}" + raise SourceError( + f"corpus path {rel_path!r} is outside the article trees " + f"({', '.join(ARTICLE_TREES)}) or not a .md page" + ) + + +def discover_pages(extracted_root: str | Path) -> list[str]: + """Corpus-relative `.md` paths of the two article trees (§7.4, OQ3). + + `extracted_root` is the root of the *extracted* tarball — the directory + containing `articles/` (T07 strips the tarball's top-level + `azure-docs-/` directory before calling this). Returns sorted + forward-slash paths relative to `extracted_root` — feed them straight to + `page_to_url`. Both exclusion rules apply: any path segment named + `includes`, and any filename starting with `_`. + + Raises SourceError when the root or either tree is missing — that is the + A1-failure signal that would trigger the TOC-API fallback seam. + """ + root = Path(extracted_root) + if not root.is_dir(): + raise SourceError(f"extracted corpus root is not a directory: {root}") + pages: list[str] = [] + for tree in ARTICLE_TREES: + tree_root = root / tree + if not tree_root.is_dir(): + raise SourceError( + f"corpus article tree {tree!r} is missing under {root} " + "(assumption A1 broken; TOC-API fallback would apply)" + ) + for path in tree_root.rglob("*.md"): + rel = path.relative_to(root) + if "includes" in rel.parts or rel.name.startswith("_"): + continue + pages.append(rel.as_posix()) + return sorted(pages) + + +def _fetch_via_toc_api(toc_url: str) -> bytes: + """A1 fallback seam: the Learn TOC-API crawler (§7.4), unimplemented. + + Used ONLY if assumption A1 breaks — the upstream repository no longer + keeps Azure Functions articles at `articles/azure-functions/*.md` and + Service Bus articles at `articles/service-bus-messaging/*.md`, or the + repository disappears. In that case, `discover_pages` raises the A1 + error and fetching must switch to the documented Learn TOC API plus a + polite per-page fetcher (§7.4: "fallback TOC-API crawler only if A1 + fails, behind source.py's single seam"). While A1 holds, + learn.microsoft.com is never scraped (NFR-06, §7.4). + """ + raise NotImplementedError( + "TOC-API fallback is unimplemented: assumption A1 holds, so the GitHub " + "tarball is the only active corpus source" + ) diff --git a/tests/unit/test_source.py b/tests/unit/test_source.py new file mode 100644 index 0000000..e31138d --- /dev/null +++ b/tests/unit/test_source.py @@ -0,0 +1,385 @@ +"""Unit tests: ingest/source.py — pinned-ref tarball fetch/cache, A1 URL mapping, +and corpus page discovery with exclusions (§7.4, §15). + +The single Fetcher seam is injected through fetch_corpus's public `fetcher` +parameter: a test-local fake serving a locally built fixture .tar.gz — no +network, no patch() on internals (§15 mocking policy; same injection style as +the provider tests' FakeGeminiModels). Cache/env tests run under tmp_path via +monkeypatch, like the provider env tests. +""" + +import io +import json +import tarfile +from pathlib import Path + +import pytest + +from caliper.config import CaliperConfig +from caliper.ingest.source import ( + CACHE_DIR_ENV_VAR, + CacheMeta, + SourceError, + _fetch_via_toc_api, + discover_pages, + fetch_corpus, + format_source_ref, + page_to_url, + read_cache_meta, +) + +# --- fixture constants ------------------------------------------------------------- + +# 40-hex scripted SHAs (never a real commit; only the format is contract). +FIXED_SHA_A = "9f3ab12e4d5c6b7a8f9e0d1c2b3a495867766554" +FIXED_SHA_B = "0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e" + +# The wire URLs are pinned as literals so the test is honest about the format. +COMMITS_URL = "https://api.github.com/repos/MicrosoftDocs/azure-docs/commits/main" +CODELOAD_URL = "https://codeload.github.com/MicrosoftDocs/azure-docs/tar.gz/{sha}" +ROOT_NAME_A = f"azure-docs-{FIXED_SHA_A[:7]}" + +LEARN = "https://learn.microsoft.com/en-us/azure" + + +def _fixture_tarball(root_name: str, pages: dict[str, str]) -> bytes: + """A real .tar.gz with in-memory members, shaped like the upstream tarball + (one top-level `azure-docs-/` directory — T07 strips it on extract).""" + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as tar: + for rel_path, content in pages.items(): + data = content.encode("utf-8") + info = tarfile.TarInfo(name=f"{root_name}/{rel_path}") + info.size = len(data) + info.mtime = 0 + tar.addfile(info, io.BytesIO(data)) + return buffer.getvalue() + + +def _write_tree(root: Path, pages: dict[str, str]) -> None: + """Materialize an extracted-corpus directory tree for discovery tests.""" + for rel_path, content in pages.items(): + path = root / rel_path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +class FakeFetcher: + """Fake of source.py's single Fetcher seam (§15). + + Serves the commits-API JSON for the scripted SHAs (popped in order; the + last one repeats) and the fixture tarball bytes for the matching codeload + URL. Every fetched URL is recorded in `calls` so tests can assert call + counts (cache hit ⇒ 0, refresh ⇒ refetch). No network, no patch(). + """ + + def __init__(self, tarball: bytes, *shas: str) -> None: + self._tarball = tarball + self._pending = list(shas) or [FIXED_SHA_A] + self._last_sha: str | None = None + self.calls: list[str] = [] + + def __call__(self, url: str) -> bytes: + self.calls.append(url) + if url == COMMITS_URL: + if self._pending: + self._last_sha = self._pending.pop(0) + assert self._last_sha is not None, "FakeFetcher: no sha scripted" + return json.dumps({"sha": self._last_sha}).encode("utf-8") + if self._last_sha is not None and url == CODELOAD_URL.format(sha=self._last_sha): + return self._tarball + raise AssertionError(f"FakeFetcher: unexpected url {url}") + + +@pytest.fixture(autouse=True) +def _isolate_cache_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """No ambient CALIPER_CACHE_DIR, and cwd pinned to tmp_path so the + relative `data/cache` default can never write into the repo.""" + monkeypatch.delenv(CACHE_DIR_ENV_VAR, raising=False) + monkeypatch.chdir(tmp_path) + + +# --- fetch_corpus: fetch once, cache, pin ------------------------------------------- + + +def test_fetch_corpus_downloads_and_pins_ref( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + tarball = _fixture_tarball( + ROOT_NAME_A, + {"articles/azure-functions/functions-timer.md": "# Timer triggers\n"}, + ) + fake = FakeFetcher(tarball, FIXED_SHA_A) + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + + path = fetch_corpus(CaliperConfig(), fetcher=fake) + + assert fake.calls == [COMMITS_URL, CODELOAD_URL.format(sha=FIXED_SHA_A)] + assert path.is_file() + assert path.read_bytes() == tarball + assert path == tmp_path / "cache" / "azure-docs" / f"{FIXED_SHA_A}.tar.gz" + pointer = json.loads( + (tmp_path / "cache" / "azure-docs" / "main.json").read_text(encoding="utf-8") + ) + assert pointer["branch"] == "main" + assert pointer["sha"] == FIXED_SHA_A + assert pointer["source_ref"] == f"main@{FIXED_SHA_A[:7]}" + assert pointer["fetched_at"] + + +def test_fetch_corpus_cache_hit_makes_no_network_calls( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake = FakeFetcher(_fixture_tarball(ROOT_NAME_A, {}), FIXED_SHA_A) + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + + first = fetch_corpus(CaliperConfig(), fetcher=fake) + assert len(fake.calls) == 2 # ref resolution + download + + second = fetch_corpus(CaliperConfig(), fetcher=fake) + + assert second == first + assert fake.calls == [COMMITS_URL, CODELOAD_URL.format(sha=FIXED_SHA_A)] # 0 new calls + + +def test_fetch_corpus_refresh_reresolves_refetches_and_repins( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake = FakeFetcher(_fixture_tarball(ROOT_NAME_A, {}), FIXED_SHA_A, FIXED_SHA_B) + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + fetch_corpus(CaliperConfig(), fetcher=fake) + + refreshed = fetch_corpus(CaliperConfig(), refresh=True, fetcher=fake) + + assert len(fake.calls) == 4 # resolve+download again + assert fake.calls[-1] == CODELOAD_URL.format(sha=FIXED_SHA_B) + cache_dir = tmp_path / "cache" / "azure-docs" + assert (cache_dir / f"{FIXED_SHA_A}.tar.gz").is_file() # sha-keyed refs coexist + assert (cache_dir / f"{FIXED_SHA_B}.tar.gz").is_file() + assert refreshed == cache_dir / f"{FIXED_SHA_B}.tar.gz" + pointer = json.loads((cache_dir / "main.json").read_text(encoding="utf-8")) + assert pointer["sha"] == FIXED_SHA_B + assert pointer["source_ref"] == f"main@{FIXED_SHA_B[:7]}" + + # the refreshed pin is now served from cache with zero network calls + assert fetch_corpus(CaliperConfig(), fetcher=fake) == refreshed + assert len(fake.calls) == 4 + + +def test_fetch_corpus_reuses_cached_sha_tarball_without_redownload( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake = FakeFetcher(_fixture_tarball(ROOT_NAME_A, {}), FIXED_SHA_A) + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + first = fetch_corpus(CaliperConfig(), fetcher=fake) + (tmp_path / "cache" / "azure-docs" / "main.json").unlink() # pin lost, tarball kept + + second = fetch_corpus(CaliperConfig(), fetcher=fake) + + assert second == first + # only the ref resolution ran again; the sha-keyed tarball was not redownloaded + assert fake.calls == [COMMITS_URL, CODELOAD_URL.format(sha=FIXED_SHA_A), COMMITS_URL] + + +def test_fetch_corpus_defaults_to_data_cache_relative_to_cwd() -> None: + fake = FakeFetcher(_fixture_tarball(ROOT_NAME_A, {}), FIXED_SHA_A) + + path = fetch_corpus(CaliperConfig(), fetcher=fake) + + assert path == Path("data/cache/azure-docs") / f"{FIXED_SHA_A}.tar.gz" + assert path.is_file() # resolved under tmp_path (cwd pinned by the fixture) + + +def test_fetch_corpus_wraps_fetcher_failures_as_source_error() -> None: + def offline(url: str) -> bytes: + raise RuntimeError("connection refused") + + with pytest.raises(SourceError, match="RuntimeError: connection refused"): + fetch_corpus(CaliperConfig(), fetcher=offline) + + +@pytest.mark.parametrize( + ("body", "match"), + [ + (b"rate limited", "invalid JSON"), + (json.dumps({"sha": "9f3ab12"}).encode("utf-8"), "40-hex"), + (json.dumps({"commit": {"sha": FIXED_SHA_A}}).encode("utf-8"), "40-hex"), + ], +) +def test_fetch_corpus_rejects_bad_ref_payload(body: bytes, match: str) -> None: + def bad_api(url: str) -> bytes: + assert url == COMMITS_URL + return body + + with pytest.raises(SourceError, match=match): + fetch_corpus(CaliperConfig(), fetcher=bad_api) + + +def test_fetch_corpus_raises_on_corrupt_pin_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake = FakeFetcher(_fixture_tarball(ROOT_NAME_A, {}), FIXED_SHA_A) + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + fetch_corpus(CaliperConfig(), fetcher=fake) + pin = tmp_path / "cache" / "azure-docs" / "main.json" + pin.write_text("{not json", encoding="utf-8") + + with pytest.raises(SourceError, match="unreadable"): + fetch_corpus(CaliperConfig(), fetcher=fake) + assert len(fake.calls) == 2 # corrupt pin is loud, never silently refetched + + +# --- read_cache_meta (T07 touchpoint) ------------------------------------------------ + + +def test_read_cache_meta_returns_pinned_ref_without_network( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + fake = FakeFetcher(_fixture_tarball(ROOT_NAME_A, {}), FIXED_SHA_A) + monkeypatch.setenv(CACHE_DIR_ENV_VAR, str(tmp_path / "cache")) + fetch_corpus(CaliperConfig(), fetcher=fake) + + meta = read_cache_meta(CaliperConfig()) + + assert isinstance(meta, CacheMeta) + assert meta.source_ref == f"main@{FIXED_SHA_A[:7]}" + assert meta.sha == FIXED_SHA_A + assert meta.branch == "main" + assert meta.fetched_at + assert len(fake.calls) == 2 # no additional network for the metadata read + + +def test_read_cache_meta_raises_when_nothing_is_cached() -> None: + with pytest.raises(SourceError, match="no corpus cached"): + read_cache_meta(CaliperConfig()) + + +def test_format_source_ref_uses_seven_char_sha() -> None: + assert format_source_ref(FIXED_SHA_A) == f"main@{FIXED_SHA_A[:7]}" + with pytest.raises(SourceError, match="40-hex"): + format_source_ref("nothex") + + +# --- page_to_url (A1 mapping, 5 known pages) ------------------------------------------ + +# Mapping tests per the task spec: real article slugs (the first two appear in +# ARCHITECTURE §8 examples) pinning the path→URL rule — NOT existence tests. +KNOWN_PAGES = [ + ( + "articles/azure-functions/functions-timer.md", + f"{LEARN}/azure-functions/functions-timer", + ), + ( + "articles/azure-functions/functions-bindings-timer.md", + f"{LEARN}/azure-functions/functions-bindings-timer", + ), + ( + "articles/azure-functions/functions-create-first-function-vscode.md", + f"{LEARN}/azure-functions/functions-create-first-function-vscode", + ), + ( + "articles/service-bus-messaging/service-bus-messaging-overview.md", + f"{LEARN}/service-bus-messaging/service-bus-messaging-overview", + ), + ( + "articles/service-bus-messaging/service-bus-queues-topics-subscriptions.md", + f"{LEARN}/service-bus-messaging/service-bus-queues-topics-subscriptions", + ), +] + + +@pytest.mark.parametrize(("rel_path", "expected_url"), KNOWN_PAGES) +def test_page_to_url_maps_known_pages(rel_path: str, expected_url: str) -> None: + assert page_to_url(rel_path) == expected_url + + +@pytest.mark.parametrize( + "rel_path", + [ + "articles/app-service/functions-timer.md", # outside the two trees + "articles/azure-functions/functions-timer.txt", # wrong extension + "articles/azure-functions/functions-timer.markdown", # wrong extension + "articles/azure-functions/functions-timer", # no extension + "articles/azure-functions/.md", # empty slug + "articles/azure-functions", # the tree root itself + "README.md", + "", + ], +) +def test_page_to_url_rejects_out_of_tree_or_non_md_paths(rel_path: str) -> None: + with pytest.raises(SourceError, match="outside the article trees"): + page_to_url(rel_path) + + +def test_page_to_url_normalizes_windows_separators() -> None: + expected = KNOWN_PAGES[0][1] + assert page_to_url("articles\\azure-functions\\functions-timer.md") == expected + + +# --- discover_pages (both trees + exclusions) ----------------------------------------- + + +def test_discover_pages_lists_both_trees_sorted(tmp_path: Path) -> None: + _write_tree( + tmp_path, + { + "articles/service-bus-messaging/service-bus-messaging-overview.md": "kept", + "articles/azure-functions/functions-timer.md": "kept", + "articles/azure-functions/prebuilt/functions-container-image.md": "kept (nested)", + "articles/app-service/not-in-corpus.md": "other tree, out of scope", + "articles/azure-functions/notes.txt": "not markdown", + }, + ) + + pages = discover_pages(tmp_path) + + assert pages == [ + "articles/azure-functions/functions-timer.md", + "articles/azure-functions/prebuilt/functions-container-image.md", + "articles/service-bus-messaging/service-bus-messaging-overview.md", + ] + + +def test_discover_pages_applies_exclusion_rules(tmp_path: Path) -> None: + _write_tree( + tmp_path, + { + "articles/azure-functions/functions-timer.md": "kept", + "articles/azure-functions/_footer.md": "excluded: underscore name", + "articles/azure-functions/includes/required-permissions.md": "excluded: segment", + "articles/azure-functions/includes-guide.md": "kept: not an includes segment", + "articles/service-bus-messaging/service-bus-queues-topics-subscriptions.md": "kept", + "articles/service-bus-messaging/_toc.md": "excluded: underscore name", + "articles/service-bus-messaging/service-bus-topics/includes/endpoint.md": "nested", + }, + ) + + pages = discover_pages(tmp_path) + + assert pages == [ + "articles/azure-functions/functions-timer.md", + "articles/azure-functions/includes-guide.md", + "articles/service-bus-messaging/service-bus-queues-topics-subscriptions.md", + ] + + +def test_discover_pages_raises_on_missing_root(tmp_path: Path) -> None: + with pytest.raises(SourceError, match="not a directory"): + discover_pages(tmp_path / "missing") + + +def test_discover_pages_raises_when_a_tree_is_missing(tmp_path: Path) -> None: + _write_tree( + tmp_path, {"articles/service-bus-messaging/service-bus-messaging-overview.md": "kept"} + ) + + with pytest.raises(SourceError, match="assumption A1"): + discover_pages(tmp_path) + + +# --- TOC-API fallback seam ------------------------------------------------------------- + + +def test_toc_api_fallback_seam_is_deliberately_unimplemented() -> None: + with pytest.raises(NotImplementedError, match="A1"): + _fetch_via_toc_api("https://learn.microsoft.com/api/catalog/") From c97de874fd799c749c5fee7ed0f7a241edbbcf38 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Mon, 16 Nov 2026 22:58:21 +0530 Subject: [PATCH 2/2] chore(tasks): mark t05 in progress --- docs/TASKS.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index ef3182c..5338552 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -19,7 +19,9 @@ Statuses: ✅ done · 🔄 doing · ⬜ remaining · ✂️ cut (stretch only, p ## Doing -_(none — next up: **T05** (needs T04) and **T09** (needs T03+T04); parallelizable per §14.3)_ +| ID | Branch | Status | +|---|---|---| +| T05 | arch/caliper/t05 | implemented, verification below | ## Remaining @@ -35,7 +37,6 @@ _(none — next up: **T05** (needs T04) and **T09** (needs T03+T04); paralleliza | ID | Task | Files | Deps | Acceptance criteria (summary) | |---|---|---|---|---| -| T05 | Corpus source | `src/caliper/ingest/source.py` | T04 | Tarball fetched once, cached, ref pinned; file→URL mapping unit-tested against 5 known pages; exclusions applied | | T06 | Parsers + chunkers | `src/caliper/ingest/parse.py`, `src/caliper/ingest/chunkers.py` | T05 | Heading paths correct on fixture corpus; both chunkers hit token bounds; 1,900-token cap enforced | | T07 | Ingest orchestration | `src/caliper/ingest/__init__.py`, `src/caliper/cli.py` (ingest) | T03, T06 | Double-ingest on mini-corpus yields identical counts; orphan chunks removed; summary JSON matches §9.4 | | T08 | Embedding batcher + resume | edits within `src/caliper/ingest/` only | T07 | Batch ≤100/request; 429 backoff via providers; interrupt + resume completes without re-embedding finished batches | @@ -108,3 +109,10 @@ _(none — next up: **T05** (needs T04) and **T09** (needs T03+T04); paralleliza - **T04 — OQ1 still open:** free-tier RPD for `gemini-3.5-flash-lite` must be verified live (AI Studio) at the smoke run and logged in §18. - **T04 — live smoke result (2026-11-16):** Gemini leg PASSED live — chat OK on `gemini-3.5-flash-lite` (26/18 tokens), embed OK 768-dim norm 1.000000, cost estimated from `prices.json`, 429 backoff demo logged. Ollama leg deferred: Ollama not installed; re-run `uv run python scripts/smoke.py` after `ollama pull qwen2.5:7b-instruct` + `nomic-embed-text`. User decision recorded 2026-11-16. - **T04 — bug found by the live smoke:** google-genai's `Models` holds only a weak reference to its `Client`; dropping the Client fails every request ("client has been closed"). Fixed in `89e5423`: `GeminiSession` owns the `genai.Client`, factories and smoke pass it to the backends (`keepalive` slot). This would have broken the production ask path at T11/T12 — worth remembering when reading T04's diff. +- **T05 — `ingest/__init__.py` marker ownership:** T05 created `src/caliper/ingest/__init__.py` as an empty package marker (one docstring line, no code) so `caliper.ingest.source` is importable. §14.2 assigns this file to T07 — it remains T07-owned from here on; T05 made no other change to it. +- **T05 — cache dir source:** `CaliperConfig` (T02, `extra="forbid"`, fingerprint-relevant fields only per §11.2) has no cache-dir field, so `fetch_corpus`/`read_cache_meta` read `CALIPER_CACHE_DIR` directly, default `data/cache` (§11.2); constants `CACHE_DIR_ENV_VAR`/`DEFAULT_CACHE_DIR` live in `source.py`. No `config.py` edit was made (forbidden for T05); if a field is ever added, `_cache_dir` should prefer it over the env var. +- **T05 — public API frozen for T06/T07:** `fetch_corpus(cfg, *, refresh=False, fetcher=None) -> Path`; `read_cache_meta(cfg) -> CacheMeta` (frozen dataclass `branch`/`sha`/`source_ref`/`fetched_at` — T07 reads it for the §9.4 summary instead of re-resolving the ref); `format_source_ref(sha) -> str` (`main@<7-char sha>`); `page_to_url(rel_path) -> str`; `discover_pages(extracted_root) -> list[str]` (sorted, forward-slash, corpus-relative, exclusions applied); `SourceError`; constants `AZURE_DOCS_REPO`, `AZURE_DOCS_BRANCH`, `ARTICLE_TREES`, `LEARN_BASE_URL`, `HTTP_TIMEOUT_S`; type alias `Fetcher = Callable[[str], bytes]`. `fetch_corpus` performs no DB writes (§7.4) and extracts nothing — extraction/chunking starts at T06/T07. +- **T05 — fetcher seam design:** one seam serves both network steps (GitHub ref resolution via `commits_api_url()` and the tarball download via `tarball_url(sha)`): `Callable[[str], bytes]` returning raw bodies, injected through `fetch_corpus`'s public `fetcher` parameter, defaulting to an httpx GET. The test fake (`FakeFetcher` in `tests/unit/test_source.py`) is a test-local constructor-injected double in the same style as the provider tests' `FakeGeminiModels`; `tests/fakes.py` (T04-owned) is untouched, and tests pin the wire URLs as literals. No `patch()`/monkeypatch of internals anywhere (§15); monkeypatch is used only for env/cwd isolation, mirroring `test_providers_base.py`. +- **T05 — cache layout + pin semantics:** `/azure-docs/<40-hex-sha>.tar.gz` plus a per-branch pin pointer `/azure-docs/main.json` (`branch`, `sha`, `source_ref`, `fetched_at`), written atomically (tmp + `os.replace`). Cache hit = pointer + tarball both present ⇒ zero network calls and the pin stays the first-fetch ref (fulfilling "pinned ref recorded at first ingest"); corrupt pointer raises `SourceError` (loud, never silently refetched); pointer with missing tarball is a repairable miss; a sha-keyed tarball already on disk is reused without redownload. Distinct refs coexist (keyed by sha); `refresh=True` re-resolves + refetches and re-points. +- **T05 — mapping/exclusion decisions:** `page_to_url` normalizes `\` → `/` and accepts nested slugs under the two trees (Learn mirrors the docs path); it rejects only out-of-tree paths, non-`.md` extensions, and empty slugs — `_`/`includes` filtering is `discover_pages`' job (segment-based, so a filename like `includes-guide.md` is kept). `discover_pages` raises `SourceError` when the root or either article tree is missing — that is the A1-failure signal for the `_fetch_via_toc_api` fallback seam, which stays deliberately unimplemented (`NotImplementedError`). The 5 URL-mapping test pages (`functions-timer`, `functions-bindings-timer`, `functions-create-first-function-vscode`, `service-bus-messaging-overview`, `service-bus-queues-topics-subscriptions`) are mapping tests per the T05 spec, not existence tests; the first two are the slugs already used in ARCHITECTURE §8 examples. +- **T05 — extraction contract handed to T07:** the upstream tarball has one top-level `azure-docs-/` directory (mirrored by the test fixtures); T07 must strip it and pass the inner root — the directory containing `articles/` — to `discover_pages`.