Capstone - Document Question-Answering Retrieval Service

Article · 6:00

Relevance evaluation as the primary evidence, tenant isolation proved by a deliberate bug, and a cost model that prices the relevance decisions.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

The system. A document question-answering retrieval service for several tenants. Each tenant's documents are ingested, chunked, embedded and indexed; queries return ranked passages with sources; a language model generates a grounded, cited answer; and the service declines when it cannot find relevant context. Tenants cannot see each other's data.

Three invariants must hold:

  1. Measured relevance meets a declared threshold on a hand-built ground-truth set - recall@5, MRR and nDCG@10 all reported, for conceptual and exact-match questions separately.
  2. No query can return another tenant's data, proved by a test that attempts it through every code path that reaches the index.
  3. The index can be rebuilt from the document store, with a measured time, and the answer to "what is our RPO" is the document store's freshness.

Invariant 1 is this capstone's distinguishing requirement and the one that separates this course from the rest of the programme. Everywhere else, a correct query returns the right answer or an error. Here, a wrong answer is returned with a confident score and no error, so the only evidence that the system works is a measurement against known-correct results. A capstone without a ground-truth set and a relevance measurement has not demonstrated that it works at all - however good the architecture diagram is.

What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.

Relevance measured against a hand-built ground truth, with the configuration sweep behind it. Not a single number - the table showing what you tried, split by question type, with the parameter that mattered most identified. The evaluation harness is a deliverable.

Tenant isolation proved rather than asserted. The single code path, the test that attempts a cross-tenant read through every entry point, and the deliberate-bug demonstration showing what the design prevents.

A cost model that prices the relevance decisions. Read units at your chosen top_k, the reranker, the embedding, and specifically the cost of any recall mitigation you adopted - because the central lesson of this course is that relevance and cost are the same conversation.

Deliverables: architecture diagram including the embedding and reranking path; the chunking and metadata design with the measurements behind it; the versioned ground-truth set; the evaluation harness; source code including the single namespace code path, retry handling and the ingestion pipeline; reproducible corpus; benchmark report with all relevance metrics split by question type and latency split by component; security review including the data flow and the isolation test results; recovery runbook with the measured rebuild time; cost model with the relevance trade-offs priced; and a short design defence.

PY Example 1 179 lines
# ================= Invariants, as runnable checks ==================

# 1. *** MEASURED RELEVANCE MEETS A DECLARED THRESHOLD. ***
#    Split by question type, because the winner differs (Module 3).
def assert_relevance(cfg, gt_conceptual, gt_exact, thresholds):
    c = evaluate(cfg, gt_conceptual)
    e = evaluate(cfg, gt_exact)
    for name, got, want in [
        ("conceptual recall@5", c["recall@5"], thresholds["c_recall5"]),
        ("conceptual mrr",      c["mrr"],      thresholds["c_mrr"]),
        ("exact recall@5",      e["recall@5"], thresholds["e_recall5"]),
        ("exact mrr",           e["mrr"],      thresholds["e_mrr"]),
    ]:
        assert got >= want, f"{name}: {got:.3f} < {want:.3f}"
    return c, e
#
# *** THIS IS THE INVARIANT THAT SEPARATES THIS COURSE FROM THE REST
# *** OF THE PROGRAMME. *** Everywhere else a correct query returns
# the right answer or an error. HERE A WRONG ANSWER IS RETURNED WITH
# A CONFIDENT SCORE AND NO ERROR.
#
# So a capstone WITHOUT a ground-truth set and a relevance
# measurement HAS NOT DEMONSTRATED THAT IT WORKS AT ALL - however
# good the architecture diagram is. Run this in CI.

# 2. *** NO QUERY CAN RETURN ANOTHER TENANT'S DATA. *** Proved
#    through EVERY code path that reaches the index.
def test_tenant_isolation():
    acme   = Principal(tenant_id="acme")
    globex = Principal(tenant_id="globex")

    # Seed a document only globex has, with a distinctive term.
    ingest_document(globex, {"id": "secret-1", "title": "Globex pricing",
                             "body": "Internal rate card: zorblatt-9981",
                             "section": "pricing", "public": False,
                             "tags": [], "published_epoch": 1764500460,
                             "contains_pii": False})
    wait_for_freshness()        # Module 3: upserts are eventually
                                # consistent, so the test must wait

    # EVERY entry point that reaches the index:
    for fn in (search, answer_question, suggest_related, export_matches):
        hits = fn(acme, "zorblatt-9981")
        ids = {h["id"] for h in (hits["matches"] if "matches" in hits
                                 else hits)}
        assert not any(i.startswith("secret-1") for i in ids), fn.__name__

    # And the principal with no tenant must be refused, not defaulted:
    try:
        search(Principal(tenant_id=None), "anything")
        assert False, "a principal with no tenant was served"
    except PermissionError:
        pass

# Plus the structural check: EXACTLY ONE call site computes a
# namespace.
#   grep -rn 'namespace=' src/ | grep -v 'namespace=ns' | wc -l
#   -> must be the single call inside search(), and nothing else.

# 3. *** THE INDEX CAN BE REBUILT FROM THE DOCUMENT STORE. ***
#    With a MEASURED time. Run it in the laboratory; state it in the
#    runbook:
#      "RTO: 47 minutes, measured, to rebuild 11,208 vectors across
#       4 tenants. RPO: the document store's freshness, 5 minutes."
#    "Pinecone is managed" is not an answer to either question.

# ================= Declare the baseline BEFORE measuring ===========
#
#   Model:      all-mpnet-base-v2, 768-d, LOCAL (no text leaves our
#               boundary for embedding - a privacy decision, stated)
#   Metric:     cosine (as the model's documentation specifies)
#   Chunking:   structural + contextual prefix
#               (measured best of four: 0.91 vs 0.63 for the worst)
#   Retrieval:  dense top_k=50 -> cross-encoder rerank -> top 5
#               + sparse (BM25) fused by RRF for exact-match queries
#   Isolation:  NAMESPACE per tenant, derived from the authenticated
#               identity in ONE code path
#   Threshold:  rerank_score >= 0.35 or the service DECLINES
#   Context:    3,000 tokens, deduplicated by document, cited
#
#   DECLARED THRESHOLDS - invariant 1:
#                        conceptual   exact-match
#     recall@5              >= 0.88      >= 0.85
#     recall@10             >= 0.94      >= 0.92
#     MRR                   >= 0.80      >= 0.78
#     nDCG@10               >= 0.82      >= 0.80
#
#   LATENCY, split by component (Module 4):
#     embed                 p95 <  25 ms
#     vector query          p95 <  20 ms
#     rerank (50 cands)     p95 < 160 ms
#     end to end            p95 < 220 ms
#
#   FRESHNESS: upsert-to-visible, measured, at idle and under load
#     idle         ___ s        under ingestion load  ___ s
#     -> and the product behaviour during that window, stated
#
#   REBUILD RTO  ___ min, measured.   RPO = document store freshness.

# ================= The full sweep behind the choice ===============
#   The table is a deliverable, not the best row from it:
#
#   chunking            alpha  rerank  c_recall@5  e_recall@5  p95
#   fixed512            -      no        0.71        0.38      14ms
#   recursive400        -      no        0.78        0.41      15ms
#   structural          -      no        0.84        0.43      14ms
#   structural+ctx      -      no        0.91        0.44      14ms
#   structural+ctx      0.7    no        0.89        0.81      19ms
#   structural+ctx      RRF    no        0.90        0.92      26ms
#   structural+ctx      RRF    YES       0.96        0.95     188ms  <-
#
#   *** AND THE MORE USEFUL FINDING: CHUNKING MOVED CONCEPTUAL
#   *** RECALL BY 0.20; THE RERANKER MOVED IT BY 0.06; THE METRIC
#   *** AND top_k MOVED IT BY ALMOST NOTHING. *** Name the parameter
#   that mattered, because that is what a reader can act on.

# ================= The cost model, with relevance priced ==========
#   read units/query at top_k=5     ____
#   read units/query at top_k=50    ____   <- our choice, for rerank
#   write units, full ingestion     ____
#   storage GB                      ____
#   embedding compute (local)       ____ GPU-hours or CPU-seconds
#   reranker compute                ____ per query
#
#   *** AND THE RELEVANCE DECISIONS, PRICED: ***
#     "The reranker takes conceptual recall@5 from 0.90 to 0.96 and
#      adds 160 ms and N read units per query, which is $X/month at
#      50,000 queries/day. We ship it because the product is a
#      question-answering service and a missed passage is a wrong
#      answer."
#
#     "We use a namespace per tenant rather than a metadata filter.
#      Under a 1% filter, recall@5 would fall to 0.71 and recovering
#      it would need top_k=100 at N times the read units. The
#      namespace achieves 0.91 at the top_k=50 cost."
#
# *** THOSE TWO PARAGRAPHS ARE THE POINT OF THE WHOLE COURSE: a
# *** relevance decision, a measured alternative, and a price. ***

# ================= Failure modes ==================================
#   *** WRONG ANSWER, NO ERROR      the characteristic vector
#                                   failure. Only a scheduled
#                                   recall measurement detects it.
#                                   Run the harness against
#                                   production on a schedule. ***
#   metric / model mismatch         subtly worse ordering, no error.
#   chunks too large                the vector averages several
#                                   topics and matches nothing.
#   chunks lacking context          "this is not permitted" matching
#                                   every permission question.
#   exact-match query, dense only   SKU-4471-B retrieves
#                                   SKU-4471-C. Hybrid or sparse.
#   selective metadata filter       RECALL DROPS. Namespace instead,
#                                   or raise top_k and PAY FOR IT.
#   no relevance threshold          the model confabulates around
#                                   irrelevant context, confidently.
#   upsert freshness                a just-ingested document is not
#                                   findable. Measured; product
#                                   behaviour stated.
#   namespace from a request param  *** CROSS-TENANT LEAK, no error
#                                   anywhere. *** Invariant 2.
#   leaked API key                  EVERY INDEX IN THE PROJECT.
#   embedding API in the path       every document and every query
#                                   leaves your boundary. A legal
#                                   decision; we chose local.
#   PII in metadata                 stored in plain text. Reviewed
#                                   like the document.
#   model change                    A FULL RE-EMBED. Blue-green,
#                                   evaluated before cutover, and
#                                   the new model may be WORSE.
#   chunking + model changed        ground-truth ids no longer
#   together                        exist. One thing at a time.
#   unretried partial batch         silently missing vectors, and
#                                   the only symptom is slightly
#                                   worse recall.
#
# Verify after every re-index with invariant 1, not with a vector
# count. A full index with the wrong vectors looks exactly like a
# correct one.

Open this example in the editor and change it. Nothing you type is saved.

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course Why the ground truth comes first, what dominates quality, the local model argument, and what to skip. 4 min read

Discussion

No questions on this topic yet. Sign in to ask the first one.