MODULE 02.1 · PUBLISHED · ~1-2h

Chunking, Hybrid Search & Reranking

Overlap-aware document chunking, lexical + vector hybrid search via Reciprocal Rank Fusion, second-stage reranking, and Recall@k / MRR@k benchmarking verified with pytest and GitHub Actions.

Pure vector search often misses exact error codes, product SKUs, or rare identifiers, while pure keyword search misses paraphrases and conceptual matches. Even when hybrid retrieval finds the right passages, the single best answer can still sit at rank 6 instead of rank 1.

In this module, you will build a deterministic, dependency-light retrieval pipeline covering overlap-aware text chunking, simplified lexical scoring, cosine vector similarity, Reciprocal Rank Fusion (RRF) hybrid search, second-stage reranking, and Recall@k / MRR@k benchmarking verified with pytest and GitHub Actions.

What You Will Build

  • Overlap-aware chunker: Split documents into deterministic, bounded word chunks with configurable overlap and traceable chunk IDs as a foundational baseline.
  • Lexical, vector, and hybrid retrievers: Score chunks with a simplified length-normalized lexical baseline, cosine vector similarity, and rank-based Reciprocal Rank Fusion (RRF) with duplicate-free rank lists.
  • Second-stage reranker: Re-score top-N hybrid candidates using pairwise query-chunk relevance scoring to promote exact matches to rank 1.
  • Retrieval benchmark assignment + CI: Implement benchmark_retrieval_pipelines in the practice assignment to evaluate top-k results across retrieval stages and verify with pytest and GitHub Actions.

1. Chunking, Hybrid Search, and Second-Stage Reranking

  • Chunk boundaries and overlap: Documents rarely fit cleanly into a single retrieval unit. Splitting text into bounded windows with overlap keeps context intact across adjacent boundaries. Fixed word-window chunking is a clean starting baseline, whereas production retrieval for technical docs or enterprise knowledge often preserves paragraph boundaries, headings, code blocks, and document structure.
  • Lexical + vector hybrid search: Lexical retrieval matches exact words, flags, and error codes (such as ERR_504_TIMEOUT), whereas dense embeddings match semantic intent even when wording differs. This module uses a simplified lexical overlap score normalized by token-length square root (related in spirit to production BM25, which adds term saturation and document-length/IDF weighting). Combining lexical and vector lists via Reciprocal Rank Fusion (score = sum(1 / (rrf_k + rank))) avoids raw score normalization headaches because it operates purely on rank positions, provided each input list has unique chunk IDs.
  • Second-stage reranking and latency trade-offs: First-stage retrieval must scan thousands or millions of chunks quickly, so it relies on precomputed vectors and inverted indexes. A second-stage reranker (such as a cross-encoder or LLM scorer) evaluates query and candidate text together for the top-N candidates (for example, top 10 or 20), improving top-rank precision at the cost of extra inference latency per candidate scored.
  • Measuring Recall@k and MRR@k: Recall@k measures the fraction of all expected relevant chunks retrieved within the top k results. If 4 chunks are relevant and 3 appear in the top k, Recall@k is 0.75. MRR@k (Mean Reciprocal Rank) measures how high the first relevant chunk ranks within the top k (1.0 for rank 1, 0.5 for rank 2, 0.0 if absent from top k).

2. Step-by-Step Build Walkthrough

  1. Set up the fde-02-1 repository and virtual environment: Create the package layout, configure .env.example, .gitignore, and pyproject.toml, and install editable dev dependencies.

    macOS / Linux:

    mkdir -p fde-02-1/src/fde_02_1 fde-02-1/tests
    cd fde-02-1
    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    cp .env.example .env

    Windows (PowerShell):

    mkdir fde-02-1
    cd fde-02-1
    py -m venv .venv
    .\.venv\Scripts\Activate.ps1
    py -m pip install --upgrade pip
    py -m pip install -e ".[dev]"
    Copy-Item .env.example .env

    Windows (CMD):

    mkdir fde-02-1
    cd fde-02-1
    py -m venv .venv
    .venv\Scripts\activate.bat
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    copy .env.example .env
  2. Define strict chunk, ranking, query, and benchmark schemas: Use Pydantic v2 models with extra="forbid", strict=True, finite floating-point checks, and non-empty unique expected_chunk_ids validation on EvalQuery.
    import math
    from pydantic import BaseModel, ConfigDict, Field, field_validator
    
    def _require_finite(value: float, field_name: str) -> float:
        if not math.isfinite(value):
            raise ValueError(f"{field_name} must be finite")
        return value
    
    class DocumentChunk(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        chunk_id: str = Field(min_length=1)
        doc_id: str = Field(min_length=1)
        chunk_index: int = Field(ge=0)
        text: str = Field(min_length=1)
        embedding: list[float] = Field(default_factory=list)
    
        @field_validator("embedding")
        @classmethod
        def _validate_finite_embedding(cls, values: list[float]) -> list[float]:
            for val in values:
                _require_finite(val, "embedding element")
            return values
    
    class RankedChunk(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        chunk_id: str = Field(min_length=1)
        score: float
        text: str = Field(min_length=1)
    
        @field_validator("score")
        @classmethod
        def _validate_finite_score(cls, value: float) -> float:
            return _require_finite(value, "score")
    
    class EvalQuery(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        query_id: str = Field(min_length=1)
        query_text: str = Field(min_length=1)
        expected_chunk_ids: list[str] = Field(min_length=1)
    
        @field_validator("expected_chunk_ids")
        @classmethod
        def _validate_expected_ids(cls, values: list[str]) -> list[str]:
            if any(not value.strip() for value in values):
                raise ValueError("Expected chunk IDs must not be empty")
            if len(values) != len(set(values)):
                raise ValueError("Expected chunk IDs must be unique")
            return values
    
    class BenchmarkSummary(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        pipeline_name: str = Field(min_length=1)
        query_count: int = Field(ge=0)
        k: int = Field(ge=1)
        recall_at_k: float = Field(ge=0.0, le=1.0)
        mrr_at_k: float = Field(ge=0.0, le=1.0)
  3. Implement overlap-aware word chunking: Validate chunk_size >= 1 and 0 <= overlap < chunk_size so chunk windows advance deterministically without infinite loops.
    def chunk_text_words(
        doc_id: str,
        text: str,
        chunk_size: int = 80,
        overlap: int = 20,
    ) -> list[DocumentChunk]:
        if not doc_id.strip():
            raise ValueError("doc_id must not be empty")
        if chunk_size < 1:
            raise ValueError("chunk_size must be at least 1")
        if overlap < 0 or overlap >= chunk_size:
            raise ValueError("overlap must satisfy 0 <= overlap < chunk_size")
    
        words = text.split()
        if not words:
            return []
    
        step = chunk_size - overlap
        chunks: list[DocumentChunk] = []
        idx = 0
        for start in range(0, len(words), step):
            window = words[start : start + chunk_size]
            chunk_body = " ".join(window)
            chunks.append(
                DocumentChunk(
                    chunk_id=f"{doc_id}::chunk-{idx}",
                    doc_id=doc_id,
                    chunk_index=idx,
                    text=chunk_body,
                )
            )
            idx += 1
            if start + chunk_size >= len(words):
                break
        return chunks
  4. Implement simplified lexical scoring, vector search, RRF fusion, and second-stage reranking: Reject duplicate chunk IDs within any individual ranked list passed to reciprocal_rank_fusion before accumulating scores, and re-score top-N candidates with a pairwise scorer.
    import re
    from typing import Callable
    
    TokenEmbedder = Callable[[str], list[float]]
    PairwiseScorer = Callable[[str, str], float]
    
    def _tokenize(text: str) -> list[str]:
        return re.findall(r"[a-z0-9_]+", text.lower())
    
    def lexical_search(
        query: str,
        chunks: list[DocumentChunk],
        top_k: int = 5,
    ) -> list[RankedChunk]:
        if top_k < 1:
            raise ValueError("top_k must be at least 1")
        q_tokens = set(_tokenize(query))
        if not q_tokens or not chunks:
            return []
    
        scored: list[RankedChunk] = []
        for chunk in chunks:
            c_tokens = _tokenize(chunk.text)
            if not c_tokens:
                continue
            overlap_hits = sum(1 for tok in c_tokens if tok in q_tokens)
            if overlap_hits == 0:
                continue
            score = overlap_hits / math.sqrt(len(c_tokens))
            scored.append(
                RankedChunk(chunk_id=chunk.chunk_id, score=score, text=chunk.text)
            )
    
        scored.sort(key=lambda item: (-item.score, item.chunk_id))
        return scored[:top_k]
    
    def _cosine_similarity(vec_a: list[float], vec_b: list[float]) -> float:
        if len(vec_a) != len(vec_b) or not vec_a:
            raise ValueError("Vectors must be non-empty and have matching dimensions")
        dot = sum(a * b for a, b in zip(vec_a, vec_b))
        norm_a = math.sqrt(sum(a * a for a in vec_a))
        norm_b = math.sqrt(sum(b * b for b in vec_b))
        if norm_a == 0.0 or norm_b == 0.0:
            return 0.0
        return dot / (norm_a * norm_b)
    
    def vector_search(
        query_embedding: list[float],
        chunks: list[DocumentChunk],
        top_k: int = 5,
    ) -> list[RankedChunk]:
        if top_k < 1:
            raise ValueError("top_k must be at least 1")
        if not chunks:
            return []
    
        scored: list[RankedChunk] = []
        for chunk in chunks:
            if not chunk.embedding:
                raise ValueError(f"Chunk {chunk.chunk_id} is missing an embedding")
            sim = _cosine_similarity(query_embedding, chunk.embedding)
            scored.append(
                RankedChunk(chunk_id=chunk.chunk_id, score=sim, text=chunk.text)
            )
    
        scored.sort(key=lambda item: (-item.score, item.chunk_id))
        return scored[:top_k]
    
    def reciprocal_rank_fusion(
        ranked_lists: list[list[RankedChunk]],
        top_k: int = 5,
        rrf_k: int = 60,
    ) -> list[RankedChunk]:
        if top_k < 1:
            raise ValueError("top_k must be at least 1")
        if rrf_k < 1:
            raise ValueError("rrf_k must be at least 1")
    
        for ranked in ranked_lists:
            seen_ids: set[str] = set()
            for item in ranked:
                if item.chunk_id in seen_ids:
                    raise ValueError(f"Duplicate chunk_id in ranked list: {item.chunk_id}")
                seen_ids.add(item.chunk_id)
    
        fused_scores: dict[str, float] = {}
        chunk_texts: dict[str, str] = {}
    
        for ranked in ranked_lists:
            for rank_idx, item in enumerate(ranked, start=1):
                fused_scores[item.chunk_id] = fused_scores.get(item.chunk_id, 0.0) + (
                    1.0 / (rrf_k + rank_idx)
                )
                chunk_texts[item.chunk_id] = item.text
    
        merged = [
            RankedChunk(chunk_id=cid, score=score, text=chunk_texts[cid])
            for cid, score in fused_scores.items()
        ]
        merged.sort(key=lambda item: (-item.score, item.chunk_id))
        return merged[:top_k]
    
    def rerank_candidates(
        query: str,
        candidates: list[RankedChunk],
        scorer: PairwiseScorer,
        top_k: int = 5,
    ) -> list[RankedChunk]:
        if top_k < 1:
            raise ValueError("top_k must be at least 1")
        if not candidates:
            return []
    
        rescored: list[RankedChunk] = []
        for item in candidates:
            rel_score = scorer(query, item.text)
            if not math.isfinite(rel_score):
                raise ValueError("Reranker returned a non-finite score")
            rescored.append(
                RankedChunk(chunk_id=item.chunk_id, score=rel_score, text=item.text)
            )
    
        rescored.sort(key=lambda item: (-item.score, item.chunk_id))
        return rescored[:top_k]
  5. Run tests and commit to Git: Verify deterministic unit tests with pytest, add .github/workflows/pytest.yml, and commit to Git.
    python -m pytest -v
    git status
    git add .
    git commit -m "Complete FDE module 02.1"

3. Common Pitfalls and Operational Hygiene

  • Setting chunk overlap greater than or equal to chunk size, or ignoring document structure in complex corpora: Always enforce 0 <= overlap < chunk_size, and consider structure-aware chunking (paragraphs, headings, code blocks) when indexing technical documentation or enterprise knowledge bases.
  • Averaging raw lexical and cosine similarity scores directly, or allowing duplicate IDs in ranked lists: Use rank-based fusion (such as RRF) over score-calibrated combinations, and reject duplicate chunk_ids within each ranked list so candidates are not double-counted.
  • Sending too many candidates to a slow second-stage reranker: Rerank a bounded candidate pool (for example, top 10 to 20 from hybrid search) rather than the entire corpus to stay within P95 latency budgets.

4. Completion Criteria

  • chunk_text_words splits text with bounded window size and overlap validation as a baseline chunker.
  • lexical_search, vector_search, reciprocal_rank_fusion, and rerank_candidates implemented and tested with duplicate-free RRF lists, deterministic tie-breaking, and finite score validation.
  • benchmark_retrieval_pipelines implemented and tested across lexical, vector, hybrid, and reranked retrieval with fractional Recall@k and top-k MRR@k metrics.
  • All pytest tests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Practice assignment

Build this

In fde-02-1, implement benchmark_retrieval_pipelines(queries: list[EvalQuery], pipelines: dict[str, Callable[[str, int], list[RankedChunk]]], k: int) -> dict[str, BenchmarkSummary] in src/fde_02_1/benchmark.py that validates k >= 1 and non-empty pipelines (raising ValueError otherwise), runs each named pipeline (such as "lexical", "vector", "hybrid", and "reranked") across every query, and returns a mapping of pipeline name to BenchmarkSummary containing:

  • pipeline_name (str)
  • query_count (int)
  • k (int)
  • recall_at_k (float): mean across queries of len(retrieved_relevant_at_k) / len(expected_chunk_ids)
  • mrr_at_k (float): mean across queries of 1.0 / first_relevant_rank (1-based rank within top k, or 0.0 if no relevant chunk appears in the top k)

Add unit tests in tests/test_benchmark.py covering empty queries, multi-pipeline comparison showing recall/MRR progression across lexical, vector, hybrid, and reranked retrieval, and invalid k or empty pipeline validation, then run python -m pytest -v and push fde-02-1 (including .github/workflows/pytest.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. What problem does a second-stage reranker solve after initial vector or keyword retrieval, and what latency trade-off does it add?
  2. Why does chunk size and chunk overlap matter when indexing technical documentation or support tickets?
  3. When does lexical (keyword/BM25-style) retrieval outperform dense vector similarity, and vice versa?
  4. How does Reciprocal Rank Fusion (RRF) combine ranked lists from lexical and vector retrievers without needing raw score calibration?
  5. How do Recall@k and Mean Reciprocal Rank (MRR@k) measure different aspects of retrieval quality?
Reveal self-review answers (attempt the questions first)
  1. Second-stage reranking trade-off: Bi-encoder vector search and lexical indexes retrieve candidates fast using precomputed representations, but they encode queries and passages independently; a cross-encoder or LLM reranker scores query-passage pairs jointly for higher precision at the top, adding extra inference latency proportional to the candidate set size (top_n).
  2. Chunk size and overlap: Oversized chunks dilute embeddings and waste context tokens, while tiny chunks split key facts across boundaries; controlled overlap preserves context across adjacent chunk boundaries.
  3. Lexical vs. vector strengths: Lexical retrieval excels at exact identifiers, error codes, SKUs, and rare terms, while dense vector retrieval captures semantic paraphrases and conceptual similarity.
  4. Reciprocal Rank Fusion (RRF): RRF scores each candidate using 1 / (rrf_k + rank) across retriever lists, merging heterogeneous score scales using rank positions alone.
  5. Recall@k vs. MRR@k: Recall@k measures what fraction of all relevant chunks appear anywhere in the top k results, whereas MRR@k rewards placing the first relevant chunk as close to rank 1 as possible.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.