From c061e0217cc2542203b8691b27db7e0e1edf793c Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Tue, 17 Nov 2026 21:48:31 +0530 Subject: [PATCH] feat(ingest): markdown parsers + heading/fixed chunkers with token bounds (T06) --- src/caliper/ingest/chunkers.py | 279 ++++++++++++++++++++++++++++++++ src/caliper/ingest/parse.py | 153 ++++++++++++++++++ tests/unit/test_chunkers.py | 287 +++++++++++++++++++++++++++++++++ tests/unit/test_parse.py | 195 ++++++++++++++++++++++ 4 files changed, 914 insertions(+) create mode 100644 src/caliper/ingest/chunkers.py create mode 100644 src/caliper/ingest/parse.py create mode 100644 tests/unit/test_chunkers.py create mode 100644 tests/unit/test_parse.py diff --git a/src/caliper/ingest/chunkers.py b/src/caliper/ingest/chunkers.py new file mode 100644 index 0000000..496d4d8 --- /dev/null +++ b/src/caliper/ingest/chunkers.py @@ -0,0 +1,279 @@ +"""Chunkers: the V1 heading chunker and the V2/V3 fixed-window chunker (§7.4, FR-02). + +`make_chunker(cfg)` is ingest's §7.4 factory: it reads `cfg.chunking.unit` / +`size_tokens` / `overlap_tokens` (§9.7 presets) and returns the matching +`Chunker`. Chunkers consume `parse.ParsedPage` and emit `Chunk`s carrying +exactly the `db.ChunkRow` fields minus `chunk_hash` (hashing is T07's job). + +Binding decisions (recorded here for §7.4 and the T07 freeze): + +- **Token estimator:** `tokens = ceil(len(text) / 4)` (`count_tokens`, the + 4-chars-per-token rule of thumb). Zero dependencies, fully deterministic; + every bound below is expressed and enforced in these tokens. +- **Hard cap:** every chunk is ≤ `MAX_CHUNK_TOKENS = 1900` tokens (embedding + input limit is 2,048, §7.4). A chunk that would exceed the cap is **split + further, never truncated**: an oversized single section becomes sequential + whitespace-aligned windows of ≤ `size_tokens` tokens (no overlap — the + heading unit defines none). The `fixed` unit is structurally bounded: its + body budget is `size_tokens` minus the prefix, so every chunk is ≤ + `size_tokens` ≤ 1900 by construction. +- **`heading` (V1):** content is grouped at H2 boundaries (H3+ subsections + stay attached to their H2; the intro under the title is its own group). + Adjacent groups merge greedily while the merged body stays within + `size_tokens` (`max_tokens`). A single group larger than `size_tokens` is + emitted **alone and whole** up to the 1,900 cap (the §14.2 "single section + exceeds it" exception); only beyond the cap is it split as above. + `overlap_tokens` is ignored by this unit (§7.4 defines no overlap for it; + presets set 0) — a warning is logged if a config sets it > 0. A merged + chunk's heading path is the path of its first section (where it starts). +- **`fixed` (V2/V3):** the page body is windowed at `size_tokens` tokens per + chunk **counting the `Page: \\nHeading: \\n\\n` prefix** (the + window body budget is `size_tokens` minus the prefix's tokens), advancing + by window length minus `overlap_tokens` between windows. A chunk's heading + path is the path as of the window's first character. Windows cut at the + last line/whitespace break inside the budget (hard cuts only as a last + resort), so windows are ~`size_tokens` tokens but never more. +""" + +from __future__ import annotations + +import logging +from bisect import bisect_right +from dataclasses import dataclass +from typing import Protocol, runtime_checkable + +from caliper.config import CaliperConfig +from caliper.ingest.parse import ParsedPage + +_LOGGER = logging.getLogger(__name__) + +#: Chars per estimated token (binding decision: tokens = ceil(len / 4)). +CHARS_PER_TOKEN = 4 + +#: §7.4 hard cap: every chunk stays within this many estimated tokens +#: (the embedding input limit is 2,048). +MAX_CHUNK_TOKENS = 1900 + + +def count_tokens(text: str) -> int: + """Estimated token count: `ceil(len(text) / CHARS_PER_TOKEN)` (§7.4 note).""" + return (len(text) + CHARS_PER_TOKEN - 1) // CHARS_PER_TOKEN + + +def _chunk_prefix(page_url: str, heading_path: str) -> str: + """The fixed unit's per-chunk prefix (§7.4: `Page:` + `Heading:` lines).""" + return f"Page: {page_url}\nHeading: {heading_path}\n\n" + + +def _find_cut(text: str, start: int, max_chars: int) -> int: + """Exclusive end of a window `text[start : cut]` at most `max_chars` long. + + Cuts at the last whitespace inside the budget (paragraph break, line + break, or space, whichever lands latest); a hard cut inside a token is + the last resort. + """ + limit = start + max_chars + if limit >= len(text): + return len(text) + best = -1 + for separator in ("\n\n", "\n", " "): + cut = text.rfind(separator, start, limit) + if cut > best: + best = cut + if best > start: + return best + return limit + + +def _split_to_token_windows(text: str, max_tokens: int) -> list[str]: + """Split `text` into sequential windows of ≤ `max_tokens` tokens each. + + Used only by the cap splitter for oversized single sections; whitespace + between windows is dropped (never content). + """ + windows: list[str] = [] + start = 0 + while start < len(text): + cut = _find_cut(text, start, max_tokens * CHARS_PER_TOKEN) + window = text[start:cut].rstrip() + if window: + windows.append(window) + start = cut + while start < len(text) and text[start] in " \n": + start += 1 + return windows + + +@dataclass(frozen=True, slots=True) +class Chunk: + """One index chunk: the §8.3 row payload minus `chunk_hash` (T07's job). + + Field order mirrors `db.ChunkRow` so T07 builds rows positionally: + `db.ChunkRow(page_url, heading_path, body, body_tokens, chunk_hash, ordinal)`. + """ + + page_url: str + heading_path: str + body: str + body_tokens: int + ordinal: int + + +@runtime_checkable +class Chunker(Protocol): + """§7.4 chunker interface: one parsed page → bounded chunks.""" + + def chunk_page(self, page: ParsedPage) -> list[Chunk]: ... + + +def _h2_groups(page: ParsedPage) -> list[tuple[str, str]]: + """`(heading_path, group body)` pairs: a new group per level ≤ 2 segment. + + H3+ subsections attach to the current H2 group; the intro segment under + the title (level 1) is its own group and may merge with the next one. + """ + groups: list[tuple[str, list[str]]] = [] + for segment in page.segments: + if not segment.body: + continue + if segment.level <= 2 or not groups: + groups.append((segment.heading_path, [segment.body])) + else: + groups[-1][1].append(segment.body) + return [(path, "\n\n".join(parts)) for path, parts in groups] + + +class HeadingChunker: + """V1 unit: H2-boundary groups, undersized neighbors merged up to max.""" + + def __init__(self, max_tokens: int) -> None: + self._max_tokens = max_tokens + + def chunk_page(self, page: ParsedPage) -> list[Chunk]: + """Group at H2 boundaries, merge undersized neighbors, cap oversized ones.""" + chunks: list[Chunk] = [] + merged: list[str] = [] + merged_path: str | None = None + + def flush() -> None: + nonlocal merged, merged_path + if merged and merged_path is not None: + body = "\n\n".join(merged) + chunks.append( + Chunk( + page_url=page.page_url, + heading_path=merged_path, + body=body, + body_tokens=count_tokens(body), + ordinal=len(chunks), + ) + ) + merged = [] + merged_path = None + + for path, body in _h2_groups(page): + tokens = count_tokens(body) + if tokens > MAX_CHUNK_TOKENS: + # Hard cap: split further, never truncate (§7.4). The window + # size stays the unit's own bound (min with the cap). + flush() + budget = min(self._max_tokens, MAX_CHUNK_TOKENS) + for window in _split_to_token_windows(body, budget): + chunks.append( + Chunk( + page_url=page.page_url, + heading_path=path, + body=window, + body_tokens=count_tokens(window), + ordinal=len(chunks), + ) + ) + continue + candidate = [*merged, body] + if merged and count_tokens("\n\n".join(candidate)) > self._max_tokens: + flush() + if merged_path is None: + merged_path = path + merged.append(body) + flush() + return chunks + + +def _page_layout(page: ParsedPage) -> tuple[list[int], list[str], str]: + """The page's concatenated body plus each segment's (offset, heading path).""" + bodies = [segment.body for segment in page.segments if segment.body] + full = "\n\n".join(bodies) + offsets: list[int] = [] + paths: list[str] = [] + position = 0 + for segment in page.segments: + if not segment.body: + continue + offsets.append(position) + paths.append(segment.heading_path) + position += len(segment.body) + 2 # the "\n\n" separator added above + return offsets, paths, full + + +class FixedChunker: + """V2/V3 unit: sliding windows with overlap, prefix counted in bounds.""" + + def __init__(self, size_tokens: int, overlap_tokens: int) -> None: + self._size_tokens = size_tokens + self._overlap_tokens = overlap_tokens + + def chunk_page(self, page: ParsedPage) -> list[Chunk]: + """Window the whole page body; heading path as of each window's start.""" + offsets, paths, full = _page_layout(page) + if not full: + return [] + chunks: list[Chunk] = [] + overlap_chars = self._overlap_tokens * CHARS_PER_TOKEN + start = 0 + while start < len(full): + index = bisect_right(offsets, start) - 1 # offsets[0] == 0 ≤ start + path = paths[index] + prefix = _chunk_prefix(page.page_url, path) + budget_tokens = max(1, self._size_tokens - count_tokens(prefix)) + cut = _find_cut(full, start, budget_tokens * CHARS_PER_TOKEN) + body = prefix + full[start:cut] + chunks.append( + Chunk( + page_url=page.page_url, + heading_path=path, + body=body, + body_tokens=count_tokens(body), + ordinal=len(chunks), + ) + ) + if cut >= len(full): + break + if cut - start > overlap_chars: + start = cut - overlap_chars + else: + # Degenerate config (overlap ≈ size): still guarantee progress. + start = start + max(1, (cut - start) // 2) + return chunks + + +def make_chunker(cfg: CaliperConfig) -> Chunker: + """§7.4 factory: pick the chunker from `cfg.chunking` (§9.7 presets). + + `heading` (v1) → `HeadingChunker`; `fixed` (v2/v3) → `FixedChunker`. + Raises `ValueError` on an unknown unit (unreachable via the config model, + whose `unit` field is a Literal). + """ + chunking = cfg.chunking + if chunking.unit == "heading": + if chunking.overlap_tokens > 0: + _LOGGER.warning( + "chunking.unit 'heading' ignores overlap_tokens (%d): " + "the §7.4 heading unit defines no overlap", + chunking.overlap_tokens, + ) + return HeadingChunker(max_tokens=chunking.size_tokens) + if chunking.unit == "fixed": + return FixedChunker( + size_tokens=chunking.size_tokens, overlap_tokens=chunking.overlap_tokens + ) + raise ValueError(f"unknown chunking.unit {chunking.unit!r}") diff --git a/src/caliper/ingest/parse.py b/src/caliper/ingest/parse.py new file mode 100644 index 0000000..796ba94 --- /dev/null +++ b/src/caliper/ingest/parse.py @@ -0,0 +1,153 @@ +"""Markdown page parser: page title, heading paths, body segments (§7.4). + +Pure text-in/text-out: callers (T07) hand in a corpus-relative page path (as +produced by `source.discover_pages`) and the page's text content; this module +performs no file I/O over the cache. The page URL comes from T05's frozen +`source.page_to_url` (A1 mapping); an out-of-contract path surfaces as +`SourceError` from that call. + +Binding decisions (recorded here for §7.4 and the T07 freeze): + +- **Title:** the first ATX H1 (a line starting `# ` in column 0). Setext + underlines are not treated as headings (the corpus uses ATX exclusively). +- **Heading path:** the stack of headings open at a segment's position, + joined with `" > "`: `" >

>

"` per §7.4. Deeper + headings (H4+) continue the same pattern — the path simply grows one + `" > "` per open level (azure-docs pages rarely go past H3, but the + rule stays uniform instead of truncating). +- **No H1:** raises `ParseError` with `reason="no H1"` — T07 reports the + §9.4 skip reason `parse-error: no H1` from that attribute. +- **Repeated H1** (not expected in the corpus): treated as a level-2 divider, + so the path becomes `" > <text>"` and structure stays consistent. +- **Cleaning:** YAML front matter (a leading `---` block) is stripped; heading + lines become structure, not body; fenced code blocks (` ``` `/` ~~~ `) are + never scanned for headings (a `#` comment inside a sample is body text). + Everything else is kept **verbatim**: bodies remain GitHub markdown, the + canonical quote source (§17 — quote verification normalizes emphasis, so + stripping emphasis here would break verbatim quotes). +- **Content before the first H1** is dropped with a DEBUG log (the corpus + places the H1 right after front matter). +- **Empty body:** an H1 with no following content parses fine with zero + segments (T07 counts the page OK and writes zero chunks for it). +""" + +from __future__ import annotations + +import logging +import re +from dataclasses import dataclass + +from caliper.ingest.source import page_to_url + +_LOGGER = logging.getLogger(__name__) + +_HEADING_RE = re.compile(r"^(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$") +_FENCE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})") + + +class ParseError(Exception): + """A page failed structural parsing (§11.3 typed component error). + + `reason` is a short stable slug (currently only `"no H1"`); T07 reports + the §9.4 skip reason as `f"parse-error: {exc.reason}"`. + """ + + def __init__(self, rel_path: str, reason: str) -> None: + self.reason = reason + super().__init__(f"{rel_path}: {reason}") + + +@dataclass(frozen=True, slots=True) +class BodySegment: + """The text under one heading position (§7.4 body segment).""" + + heading_path: str + level: int + body: str + + +@dataclass(frozen=True, slots=True) +class ParsedPage: + """A parsed markdown page: title, URL, and body segments in order.""" + + rel_path: str + page_url: str + title: str + segments: list[BodySegment] + + +def _strip_front_matter(text: str) -> str: + """Drop a leading YAML front-matter block; return the text unchanged otherwise.""" + lines = text.splitlines() + if not lines or lines[0].strip() != "---": + return text + for index in range(1, len(lines)): + if lines[index].strip() == "---": + return "\n".join(lines[index + 1 :]) + return text # unterminated front matter: keep the original text + + +def parse_page(rel_path: str, text: str) -> ParsedPage: + """Parse one markdown page into title, URL, and heading-aligned segments. + + `rel_path` is a corpus-relative page path (forward slashes) as produced + by `source.discover_pages`; `text` is the page's full content. Raises + `ParseError` (reason "no H1") when the page has no first-level heading, + and `SourceError` (from `page_to_url`) for out-of-contract paths. + """ + page_url = page_to_url(rel_path) + body_text = _strip_front_matter(text) + + title: str | None = None + stack: list[tuple[int, str]] = [] # open headings: (level, text) + segments: list[BodySegment] = [] + buf: list[str] = [] + current_path: str | None = None + current_level: int = 0 + fence: str | None = None # fence marker character while inside a block + + def flush() -> None: + if current_path is None: + buf.clear() + return + body = "\n".join(buf).strip() + buf.clear() + if body: + segments.append(BodySegment(heading_path=current_path, level=current_level, body=body)) + + for line in body_text.splitlines(): + if fence is not None: + buf.append(line) + if line.lstrip().startswith(fence * 3): + fence = None + continue + fence_match = _FENCE_RE.match(line) + if fence_match is not None: + fence = fence_match.group(1)[0] + buf.append(line) + continue + heading = _HEADING_RE.match(line) + if heading is None: + buf.append(line) + continue + flush() + level = len(heading.group(1)) + heading_text = heading.group(2).strip() + if level == 1: + if title is None: + title = heading_text + stack = [(1, heading_text)] + else: + stack = [(1, title), (2, heading_text)] + else: + while stack and stack[-1][0] >= level: + stack.pop() + stack.append((level, heading_text)) + current_path = " > ".join(open_text for _, open_text in stack) + current_level = level + flush() + + if title is None: + _LOGGER.debug("page %s has no H1 heading; reporting parse error", rel_path) + raise ParseError(rel_path, "no H1") + return ParsedPage(rel_path=rel_path, page_url=page_url, title=title, segments=segments) diff --git a/tests/unit/test_chunkers.py b/tests/unit/test_chunkers.py new file mode 100644 index 0000000..d4fef9e --- /dev/null +++ b/tests/unit/test_chunkers.py @@ -0,0 +1,287 @@ +"""Unit tests: ingest/chunkers.py — heading/fixed token bounds, overlap, 1,900 cap. + +Segment bodies are crafted with exact character counts so token bounds +(ceil(len/4)) are asserted precisely (§7.4, FR-02, §14.2 T06). Everything is +inline fixtures: no network, no patch(). +""" + +from pathlib import Path + +import pytest + +from caliper.config import CaliperConfig, ChunkingConfig, load_config +from caliper.ingest.chunkers import ( + MAX_CHUNK_TOKENS, + Chunker, + FixedChunker, + HeadingChunker, + count_tokens, + make_chunker, +) +from caliper.ingest.parse import BodySegment, ParsedPage + +URL = "https://learn.microsoft.com/en-us/azure/azure-functions/functions-timer" + +V1_PRESET = """\ +[chunking] +unit = "heading" +size_tokens = 800 +overlap_tokens = 0 +""" + +V2_PRESET = """\ +[chunking] +unit = "fixed" +size_tokens = 350 +overlap_tokens = 50 +""" + + +def _page(*segments: tuple[str, int, str]) -> ParsedPage: + return ParsedPage( + rel_path="articles/azure-functions/functions-timer.md", + page_url=URL, + title="Timer triggers", + segments=[BodySegment(path, level, body) for path, level, body in segments], + ) + + +def _long_body(lines: int, filler: str = "x") -> str: + return "\n".join(f"{filler}-line-{i:04d} {filler * 30}" for i in range(lines)) + + +# --- token estimator --------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("", 0), + ("a", 1), + ("abcd", 1), + ("abcde", 2), + ("a" * 400, 100), + ], +) +def test_count_tokens_is_ceiling_of_len_over_four(text: str, expected: int) -> None: + assert count_tokens(text) == expected + + +# --- heading chunker (V1) ------------------------------------------------------------ + + +def test_heading_chunker_merges_undersized_neighbors_up_to_max() -> None: + chunker = HeadingChunker(max_tokens=55) + page = _page(("T > A", 2, "a" * 100), ("T > B", 2, "b" * 100), ("T > C", 2, "c" * 100)) + + chunks = chunker.chunk_page(page) + + # A + B merged (202 chars → 51 tokens ≤ 55); C would push past max. + assert [chunk.ordinal for chunk in chunks] == [0, 1] + assert chunks[0].heading_path == "T > A" # path of the chunk's first section + assert chunks[0].body == "a" * 100 + "\n\n" + "b" * 100 + assert chunks[0].body_tokens == count_tokens(chunks[0].body) == 51 + assert chunks[1].heading_path == "T > C" + assert chunks[1].body == "c" * 100 + assert chunks[1].body_tokens == 25 + + +def test_heading_chunker_never_merges_beyond_max_tokens() -> None: + chunker = HeadingChunker(max_tokens=30) + page = _page(("T > A", 2, "a" * 100), ("T > B", 2, "b" * 100), ("T > C", 2, "c" * 100)) + + chunks = chunker.chunk_page(page) + + assert len(chunks) == 3 + assert [chunk.heading_path for chunk in chunks] == ["T > A", "T > B", "T > C"] + assert all(chunk.body_tokens == 25 for chunk in chunks) + + +def test_heading_chunker_groups_h3_sections_into_their_h2() -> None: + chunker = HeadingChunker(max_tokens=800) + page = _page( + ("T", 1, "intro"), + ("T > A", 2, "alpha"), + ("T > A > Sub", 3, "sub"), + ("T > B", 2, "beta"), + ) + + chunks = chunker.chunk_page(page) + + # Everything is undersized at 800: one merged chunk anchored at the intro. + assert len(chunks) == 1 + assert chunks[0].heading_path == "T" + assert all(needle in chunks[0].body for needle in ("intro", "alpha", "sub", "beta")) + + +def test_heading_chunker_splits_at_h2_boundaries_when_groups_are_large() -> None: + chunker = HeadingChunker(max_tokens=800) + page = _page(("T", 1, "intro"), ("T > A", 2, "a" * 2800), ("T > B", 2, "b" * 2800)) + + chunks = chunker.chunk_page(page) + + assert [chunk.heading_path for chunk in chunks] == ["T", "T > B"] + assert chunks[0].body_tokens == count_tokens("intro\n\n" + "a" * 2800) == 702 + assert chunks[1].body_tokens == 700 + + +def test_heading_chunker_keeps_a_single_oversized_section_whole_under_the_cap() -> None: + # 3,600 chars → 900 tokens: above size_tokens (30) but below the 1,900 cap. + chunker = HeadingChunker(max_tokens=30) + page = _page(("T > Big", 2, "d" * 3600)) + + chunks = chunker.chunk_page(page) + + assert len(chunks) == 1 + assert chunks[0].heading_path == "T > Big" + assert chunks[0].body == "d" * 3600 + assert chunks[0].body_tokens == 900 + assert chunks[0].body_tokens <= MAX_CHUNK_TOKENS + + +def test_heading_chunker_splits_sections_past_the_cap_never_truncates() -> None: + chunker = HeadingChunker(max_tokens=30) # windows of ≤ 30 tokens = 120 chars + page = _page(("T > Huge", 2, "e" * 20000)) + + chunks = chunker.chunk_page(page) + + assert len(chunks) > 1 + assert all(chunk.body_tokens <= 30 for chunk in chunks) + assert all(chunk.body_tokens <= MAX_CHUNK_TOKENS for chunk in chunks) + assert "".join(chunk.body for chunk in chunks) == "e" * 20000 # nothing truncated + + +def test_heading_chunker_cap_enforced_with_max_config_size() -> None: + chunker = HeadingChunker(max_tokens=MAX_CHUNK_TOKENS) + page = _page(("T > Huge", 2, "e" * 20000)) # 5,000 tokens > 1,900 + + chunks = chunker.chunk_page(page) + + assert len(chunks) > 1 + assert all(chunk.body_tokens <= MAX_CHUNK_TOKENS for chunk in chunks) + assert "".join(chunk.body for chunk in chunks) == "e" * 20000 + + +def test_heading_chunker_returns_no_chunks_for_empty_pages() -> None: + chunker = HeadingChunker(max_tokens=800) + + assert chunker.chunk_page(_page()) == [] + assert chunker.chunk_page(_page(("T", 1, ""), ("T > A", 2, ""))) == [] + + +# --- fixed chunker (V2/V3) ------------------------------------------------------------- + + +def _fixed() -> FixedChunker: + chunker = make_chunker( + CaliperConfig(chunking=ChunkingConfig(unit="fixed", size_tokens=350, overlap_tokens=50)) + ) + assert isinstance(chunker, FixedChunker) + return chunker + + +def test_fixed_chunker_windows_are_bounded_with_prefix_counted() -> None: + page = _page(("T > A", 2, _long_body(280))) # ~12k chars ≈ 3k tokens + + chunks = _fixed().chunk_page(page) + + assert len(chunks) >= 5 + expected_prefix = f"Page: {URL}\nHeading: T > A\n\n" + for chunk in chunks: + assert chunk.body_tokens == count_tokens(chunk.body) + assert chunk.body.startswith(expected_prefix) + assert chunk.body_tokens <= 350 # prefix counted in the token count + assert chunk.body_tokens <= MAX_CHUNK_TOKENS + # windows are ~size_tokens, not fragments: every non-final chunk is ≥ 250 tokens + assert all(chunk.body_tokens >= 250 for chunk in chunks[:-1]) + + +def test_fixed_chunker_overlap_shares_the_window_tail() -> None: + page = _page(("T > A", 2, _long_body(280))) + chunks = _fixed().chunk_page(page) + + assert len(chunks) >= 2 + for first, second in zip(chunks, chunks[1:], strict=False): + # overlap of 50 tokens = 200 chars: the next window starts 200 chars back + assert first.body[-60:] in second.body + + +def test_fixed_chunker_heading_path_follows_the_window_position() -> None: + page = _page(("T", 1, "a" * 400), ("T > Section Two", 2, _long_body(280))) + + chunks = _fixed().chunk_page(page) + + assert chunks[0].heading_path == "T" + assert chunks[1].heading_path == "T > Section Two" + assert all(chunk.heading_path == "T > Section Two" for chunk in chunks[1:]) + + +def test_fixed_chunker_returns_no_chunks_for_empty_pages() -> None: + assert _fixed().chunk_page(_page()) == [] + assert _fixed().chunk_page(_page(("T", 1, ""), ("T > A", 2, ""))) == [] + + +def test_fixed_chunker_respects_the_cap_at_max_config_size() -> None: + chunker = make_chunker( + CaliperConfig( + chunking=ChunkingConfig(unit="fixed", size_tokens=MAX_CHUNK_TOKENS, overlap_tokens=50) + ) + ) + page = _page(("T > A", 2, _long_body(700))) + + chunks = chunker.chunk_page(page) + + assert len(chunks) >= 2 + assert all(chunk.body_tokens <= MAX_CHUNK_TOKENS for chunk in chunks) + + +# --- make_chunker factory (§9.7 presets) ------------------------------------------------- + + +def _preset_config(tmp_path: Path, preset_toml: str) -> CaliperConfig: + """A resolved config from an inline preset file (self-contained fixture).""" + preset = tmp_path / "preset.toml" + preset.write_text(preset_toml, encoding="utf-8") + user = tmp_path / "user.toml" + user.write_text("", encoding="utf-8") + return load_config(user, preset) + + +def test_make_chunker_builds_the_heading_chunker_for_v1_preset_values( + tmp_path: Path, +) -> None: + cfg = _preset_config(tmp_path, V1_PRESET) + + chunker = make_chunker(cfg) + + assert isinstance(chunker, Chunker) + assert isinstance(chunker, HeadingChunker) + # 800-token max: two 700-token H2 sections must not merge. + page = _page(("T > A", 2, "a" * 2800), ("T > B", 2, "b" * 2800)) + chunks = chunker.chunk_page(page) + assert len(chunks) == 2 + assert all(chunk.body_tokens <= 800 for chunk in chunks) + + +def test_make_chunker_builds_the_fixed_chunker_for_v2_preset_values( + tmp_path: Path, +) -> None: + cfg = _preset_config(tmp_path, V2_PRESET) + + chunker = make_chunker(cfg) + + assert isinstance(chunker, Chunker) + assert isinstance(chunker, FixedChunker) + # 350-token windows with the prefix counted: long page → many bounded chunks. + page = _page(("T > A", 2, _long_body(280))) + chunks = chunker.chunk_page(page) + assert len(chunks) >= 5 + assert all( + chunk.body_tokens <= 350 and chunk.body.startswith(f"Page: {URL}") for chunk in chunks + ) + + +def test_make_chunker_defaults_to_the_heading_chunker() -> None: + chunker = make_chunker(CaliperConfig()) + + assert isinstance(chunker, HeadingChunker) diff --git a/tests/unit/test_parse.py b/tests/unit/test_parse.py new file mode 100644 index 0000000..af17ea3 --- /dev/null +++ b/tests/unit/test_parse.py @@ -0,0 +1,195 @@ +"""Unit tests: ingest/parse.py — title, heading paths, body segments (§7.4). + +Inline markdown fixtures only (§15): no file I/O over the cache, no network, +no patch() on internals. Out-of-contract paths surface T05's SourceError. +""" + +import pytest + +from caliper.ingest.parse import BodySegment, ParsedPage, ParseError, parse_page +from caliper.ingest.source import SourceError + +REL_AZ = "articles/azure-functions/functions-timer.md" +URL_AZ = "https://learn.microsoft.com/en-us/azure/azure-functions/functions-timer" + +SIMPLE_PAGE = """\ +--- +title: Timer triggers +ms.topic: reference +--- + +# Timer triggers + +Intro paragraph about timer triggers. + +## Cron expressions + +Cron text under the first H2. + +## Retry behavior + +Retry text under the second H2. +""" + +NESTED_PAGE = """\ +# Page + +intro + +## One + +one body + +### Nested + +nested body + +## Two + +two body +""" + +DEEP_PAGE = """\ +# Deep + +deep intro + +## A + +a body + +### B + +b body + +#### C + +deep body +""" + + +def test_parse_page_extracts_title_url_and_h2_paths() -> None: + page = parse_page(REL_AZ, SIMPLE_PAGE) + + assert isinstance(page, ParsedPage) + assert page.rel_path == REL_AZ + assert page.page_url == URL_AZ + assert page.title == "Timer triggers" + assert [segment.heading_path for segment in page.segments] == [ + "Timer triggers", + "Timer triggers > Cron expressions", + "Timer triggers > Retry behavior", + ] + assert [segment.body for segment in page.segments] == [ + "Intro paragraph about timer triggers.", + "Cron text under the first H2.", + "Retry text under the second H2.", + ] + assert [segment.level for segment in page.segments] == [1, 2, 2] + assert all("ms.topic" not in segment.body for segment in page.segments) + + +def test_parse_page_h3_nests_under_h2_and_resets_on_next_h2() -> None: + page = parse_page(REL_AZ, NESTED_PAGE) + + assert page.title == "Page" + assert [(segment.heading_path, segment.level) for segment in page.segments] == [ + ("Page", 1), + ("Page > One", 2), + ("Page > One > Nested", 3), + ("Page > Two", 2), + ] + assert [segment.body for segment in page.segments] == [ + "intro", + "one body", + "nested body", + "two body", + ] + + +def test_parse_page_h4_continues_the_same_path_pattern() -> None: + page = parse_page(REL_AZ, DEEP_PAGE) + + assert [segment.heading_path for segment in page.segments] == [ + "Deep", + "Deep > A", + "Deep > A > B", + "Deep > A > B > C", + ] + assert page.segments[-1].level == 4 + assert page.segments[-1].body == "deep body" + + +@pytest.mark.parametrize( + "text", + [ + "## Only an H2\n\nbody text\n", + "", + "\n\n", + "---\ntitle: x\nms.topic: y\n---\n", + "Title\n=====\n\nsetext underlines are not headings\n", + ], +) +def test_parse_page_without_atx_h1_raises_parse_error(text: str) -> None: + with pytest.raises(ParseError) as excinfo: + parse_page(REL_AZ, text) + + assert excinfo.value.reason == "no H1" + assert "no H1" in str(excinfo.value) + assert REL_AZ in str(excinfo.value) + + +def test_parse_page_title_only_page_has_no_segments() -> None: + page = parse_page(REL_AZ, "# Timer triggers\n") + + assert page.title == "Timer triggers" + assert page.segments == [] + + +def test_parse_page_heading_inside_code_fence_is_body_text() -> None: + page = parse_page(REL_AZ, "# T\n\n```python\n# not a heading\nx = 1\n```\n\nafter\n") + + assert len(page.segments) == 1 + assert "# not a heading" in page.segments[0].body + assert page.segments[0].heading_path == "T" + + +def test_parse_page_repeated_h1_becomes_a_divider() -> None: + page = parse_page(REL_AZ, "# Title\n\nintro\n\n# Second\n\nbody\n") + + assert page.title == "Title" + assert [segment.heading_path for segment in page.segments] == [ + "Title", + "Title > Second", + ] + + +def test_parse_page_drops_content_before_the_first_h1() -> None: + page = parse_page(REL_AZ, "orphan lead\n# Title\n\nbody\n") + + assert page.title == "Title" + assert [segment.body for segment in page.segments] == ["body"] + + +def test_parse_page_maps_service_bus_urls() -> None: + page = parse_page( + "articles/service-bus-messaging/service-bus-messaging-overview.md", + "# Service Bus messaging overview\n\nbody\n", + ) + + assert page.page_url == ( + "https://learn.microsoft.com/en-us/azure/" + "service-bus-messaging/service-bus-messaging-overview" + ) + + +def test_parse_page_rejects_out_of_tree_paths() -> None: + with pytest.raises(SourceError): + parse_page("README.md", "# Title\n\nbody\n") + + +def test_body_segment_is_frozen() -> None: + segment = BodySegment(heading_path="T", level=1, body="text") + + with pytest.raises(AttributeError): + segment.body = "other" # type: ignore[misc]