ELLMEngineering Large
Language Models
Download PDF

Chapter 48

RAG, Vector Search, and Evaluation Pipelines

On this page

Retrieval-augmented generation is a data and evaluation system wrapped around a model. Retrieval quality, access control, freshness, and citation behavior matter as much as the generator.

The offline path creates a versioned index with source identities. The online path retrieves, filters, reranks, packs evidence, and generates an answer with citations. Retrieval authorization and evidence quality must survive every stage.
Open full diagram ↗

The offline path creates a versioned index with source identities. The online path retrieves, filters, reranks, packs evidence, and generates an answer with citations. Retrieval authorization and evidence quality must survive every stage.

Ingestion

Connectors fetch documents under source-specific permissions. Normalize without destroying structure. Chunk using semantic and layout boundaries while retaining document, section, time, and ACL metadata. Generate embeddings under a versioned model and write both canonical content and index entries.

Updates need identity and deletion. A replaced document should tombstone or supersede old chunks. Permission changes must propagate to caches and indexes. Store content hashes to avoid re-embedding unchanged chunks.

Retrieval

Hybrid retrieval combines lexical and dense signals. Lexical search handles rare names and exact identifiers; dense search handles semantic paraphrase. A reranker spends more compute on a small candidate set.

Filters should be enforced before content leaves the retrieval trust boundary. Post-filtering an approximate index can reduce recall; use filter-aware partitions, bitsets, or over-retrieval with a measured bound.

Query rewriting and decomposition can improve recall but also drift intent. Preserve original query, log transformations, and evaluate each stage.

Calculate hybrid ranking and late interaction

Dense retrieval commonly maps a query and a passage independently into fixed-length vectors, then ranks a dot product or cosine similarity. Independence allows passage vectors to be precomputed; compressing a passage to one vector can lose rare token-level matches. A cross-encoder instead processes query and passage together and learns a relevance score. That richer interaction costs a forward pass per candidate, so it usually reranks a shortlist rather than every document.

Hybrid fusion need not compare incomparable raw scores. Reciprocal rank fusion assigns each document a contribution from its position in each ranking:

2026-10-12T12:02:56.220599 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Ranks are one-based; a document absent from a ranking contributes zero, and k is a chosen smoothing constant.

If lexical search returns [A, B] and dense search returns [B, C], with k=60, B receives 1/62 + 1/61 ≈ 0.0325, A about 0.0164, and C about 0.0161. B wins through agreement even though it is not first lexically. This does not establish relevance: two correlated bad rankings can agree. Choose candidate depths and the constant on development data, retaining an independent evaluation split. The original RRF paper studies this rank-based combination.

ColBERT offers a different middle ground: encode passages into token vectors offline, then use query-token interactions at retrieval time. A simplified normalized MaxSim score is:

2026-10-12T12:02:56.228729 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Each query token finds its best document-token match; the matches are summed.

For query vectors [1,0] and [0,1], a passage containing both directions scores two; one containing only [1,0] scores one. This preserves two distinct matching needs that a single passage vector might blur. It uses more index state than one vector per passage and requires appropriate indexing/pruning for scale. The independent reference examples/retrieval_methods.py tests RRF and this simplified score; it does not implement trained encoders or a production index.

RAPTOR recursively clusters and summarizes text to create a retrieval hierarchy. GraphRAG builds graph-derived communities and summaries for corpus-level questions. Their shared motivation is that “What themes recur across this corpus?” may not be answered by retrieving five locally similar paragraphs. They differ in structure and retrieval strategy; a graph is not a required component of every RAG service.

Need Simple starting point Added technique and its cost
Exact product or error identifier Lexical retrieval Hybrid search for paraphrases; extra index and fusion
Several precise semantic matches Dense candidates plus reranker Late interaction; more vectors and scoring work
A global corpus summary Authorized aggregate evidence Hierarchical/graph summaries; build cost and derived-data freshness
A small, bounded document set Put the eligible documents in context Longer prefill and context; not guaranteed evidence use
Unknown subquestions Bounded query decomposition More model/search calls, drift, and stopping decisions

Derived summaries inherit access and deletion obligations. A public summary cannot silently contain facts from a restricted child document. Rebuilding leaves without invalidating an ancestor summary preserves stale information. Keep source-to-summary lineage, permissions appropriate to the combined content, and evidence links. For a claim requiring an exact number or exception, expand the summary back to authorized primary passages before answering.

Long context and retrieval are complementary resource choices. Loading an entire 20-page manual may be simpler than maintaining an index for it. Loading every document in a changing enterprise corpus is different. Compare answer quality, first-token latency, cost, freshness, and disclosure scope using the same eligible evidence—not a context-heavy system with hidden extra documents against an artificially restricted retriever.

Context assembly

Select chunks under a token budget, remove redundancy, preserve useful order, and include source identifiers. Position effects can make evidence in the middle less influential. Context compression saves tokens but can remove qualifications or provenance.

Prompt injection in retrieved content is an adversarial input. Separate instructions from evidence, apply source trust policy, constrain tool use, and evaluate injection attacks. The model should cite evidence and abstain when evidence is insufficient.

Evaluation

Decompose end-to-end quality:

  • retrieval recall at k for required evidence;
  • reranker quality;
  • context precision and redundancy;
  • answer correctness;
  • faithfulness to provided evidence;
  • citation correctness and completeness;
  • abstention quality;
  • latency and cost by stage;
  • freshness and ACL correctness.

An answer can be correct despite failed retrieval due to model memory, or incorrect despite good retrieval due to generation. Stage metrics localize the failure.

Visual evidence and multimodal retrieval

Text extraction can lose the evidence in a chart, a table's column structure, or a screenshot. ColPali, revised February 2025, provides a foundation for page-image embeddings with late interaction. A different current example, Qwen3-VL-Embedding and Qwen3-VL-Reranker, January 2026, combines multimodal embeddings with a pairwise reranker across text, images, document images, and video. These are different retrieval architectures, not interchangeable implementations of MaxSim.

The Qwen3-VL-Embedding-8B publisher card, inspected September 24, describes selectable embedding dimensions through Matryoshka training. Dimensional truncation is a model-supported contract, not a general property of arbitrary embeddings. Pin preprocessing, modality limits, pooling, normalization, query instructions, output dimensions, and checkpoint revision together. Test smaller dimensions or output quantization against full-precision retrieval before adopting their storage savings.

For the documentation assistant, keep page or media identity, document revision, access scope, and a region or time reference with each hit. A retrieved page image is useful only if the answering model can inspect the relevant evidence; converting it back to lossy OCR can discard the original advantage. Cite the page and region, and retain accessible text where possible. For video, record frame sampling and time intervals so the system does not claim evidence for an event between sampled frames.

Compare OCR-plus-text retrieval, multimodal dense retrieval, and page-level late interaction on the same authorized corpus. Include chart lookup, visually ambiguous tables, exact identifiers, multilingual pages, and ordinary prose. Count image preprocessing, vectors per page, reranking, and generator image tokens in the budget. Select by measured workload quality and cost, not a published benchmark's overall rank.

Separate approximation loss from representation loss

An exact vector-search oracle only measures the nearest neighbors under one chosen representation and metric. It is not ground truth for semantic relevance. First compare ANN with exact search using the same vectors and eligible corpus; then compare those retrieved documents with labeled evidence. This separates index approximation errors from an embedding model's inability to represent the task.

Filters change the operating point. If a tenant can access 0.1% of one million vectors, only 1,000 are eligible. An exact scan of that subset may be competitive with traversing a globally shared graph. Vespa's nearest-neighbor guide documents exact and approximate modes and their interaction with filtering. This is an implementation example; measure the crossover for your index, selectivity, concurrency, and memory layout. Overfetching globally and then filtering does not guarantee eligible top-k recall.

Use paired query-level comparisons for a migration. Freeze evidence labels, corpus revisions, roles, budgets, and the evaluation rubric. Report wins, losses, and uncertainty, with resampling at the user or document group when queries share evidence. Synthetic questions and model judges can expand diagnostics, but their shared generation biases do not create an independent acceptance set. Keep judge versions and rubric changes in the experiment manifest, and inspect disagreement cases separately from the average score.

Worked check: ANN matches 98% of the exact vector top ten, but neither retrieves the required chart. Increasing graph search effort addresses approximation loss; it cannot recover information omitted by the representation. Add the visual-evidence slice before selecting a remedy.

Serving architecture

Use an API layer, query planner, lexical and vector retrieval, metadata/ACL service, reranker, context builder, generation service, and evaluation/telemetry pipeline. Cache public or tenant-scoped retrieval carefully. Version embeddings and indexes; support dual-read during migration.

For multi-region, decide whether indexes are replicated, partitioned by data residency, or queried remotely. Freshness and deletion propagation may control the topology more than query latency.

Worked service: a versioned documentation assistant

The following workload is hypothetical; its budgets are design assumptions, not measured performance. A company wants employees to ask questions about product documentation and operating policies. There are 50,000 documents, roughly 200,000 searchable chunks, and separate public, employee, and administrator audiences. Typical traffic is 20 queries per second with bursts to 60. A document update should become searchable within five minutes. A permission revocation must stop new disclosures as soon as the authoritative access service commits it, even if the search index is behind.

The product target is a p99 time to first token at most 1.5 seconds and a p99 token gap at most 100 ms, matching the serving objectives used in Part III. Correctness means answering from the current authorized evidence, with useful citations. A fluent answer from an obsolete policy is a failure. If current sources conflict and no explicit authority rule resolves them, the assistant should report the conflict or abstain rather than select whichever chunk ranks first.

The first baseline is deliberately modest: a canonical document store, a revision/permission service, a lexical index, an optional dense index, a reranker, a bounded context builder, and the 7B generation service from Part III. Retrieval-Augmented Generation establishes the combination of model parameters and retrieved memory; Dense Passage Retrieval supplies a primary dual-encoder reference. Neither paper removes the need for the service's access and freshness contracts.

Make revision and authority explicit

A chunk should carry document_id, revision_id, chunk_id, source location, content hash, embedding version, permission scope, and effective time. Do not encode “latest” only as the largest timestamp: future-dated policies, backfills, and different authority domains can all invalidate that shortcut. Resolve current status from the source's revision semantics.

Keep canonical text and its provenance independent of the search index. Build a new revision's chunks, check completeness, then atomically switch the active revision manifest. A failed embedding job must not make half an update appear current. An index row is a candidate pointer, not the authoritative document. At context assembly, resolve that pointer against the manifest and fetch the authorized revision.

An ACL filter at search time reduces the candidate set, but permission must also be checked before content leaves the trusted retrieval service. If a user loses access between search and context assembly, discard the candidate. Permission-service failure should fail closed for protected data. Do not send restricted snippets to an external reranker, generator, trace collector, or user-visible explanation and rely on a final-output filter to undo the disclosure.

The immediate-revocation requirement also needs a contract for in-flight generation and cached answers. Order authorization to release protected content against revocation at a trusted output boundary, and cancel affected streams or discard unreleased buffers when authority is lost. A one-time retrieval check cannot establish this guarantee. Content already released before revocation cannot be recalled from a client or an in-flight network buffer.

Serialize output commits with revocation

For this design, a disclosure occurs when a bounded output unit enters the trusted outbound queue, not when a network packet eventually reaches the client. The authority coordinator owns a permission epoch for each evidence scope. Revocation increments that epoch and disables the scope. An output commit supplies the epochs for every source used by the unit; the coordinator validates them and appends the unit to its outbox in the same serialized transaction. A separate allowed? RPC followed by an unrelated socket write cannot implement this contract.

examples/output_authority.py implements the local ordering with one lock. A distributed implementation needs the equivalent conditional epoch check and outbox append in one linearizable authority partition. If a unit depends on multiple independently managed partitions, either consolidate their authority at a common commit service or specify a transaction protocol; checking them sequentially permits a race. A permission grant advances the epoch too, so regranting access does not revive an old request. This example is a protocol reference, not a deployed identity service.

Revocation position Required behavior
Before retrieval or generation Do not transfer protected evidence into generation
During generation, before the first output commit Cancel generation and discard its unreleased buffer
Between an earlier authority read and enqueue The atomic commit observes the new epoch and rejects the unit
After one committed chunk That chunk may still arrive; reject subsequent commits and cancel remaining work
Authority unavailable or outbound queue full Commit nothing; apply the deadline/backpressure policy

The generation service supplies model state and proposed text; it does not decide whether a stale permission epoch is acceptable. The outbox consumer may retry delivery using a committed unit identifier, but it may not turn uncommitted text into a retry. A commit that is lost from the response must be reconciled by identifier, just as an ambiguous external tool effect must be reconciled by its receipt. Bounding output-unit size limits how much already committed content can remain in transit after revocation.

The streaming architecture uses this gate for successive output units. Its 100 ms transport/first-flush planning allocation below must include the output commit, with admission rejecting workloads whose measured authority tails cannot meet it. A final authority check in a buffered implementation is useful but has a different timing boundary: user-visible first output includes complete generation and validation. The local extractive assistant and model-selection lab are buffered references; neither claims to implement the streaming SLO or a cross-service atomic commit. This separation preserves a useful runnable baseline without attributing the proposed production protocol to it.

Deletion has at least four surfaces: canonical access, index candidates, retrieval caches, and answer caches. The authoritative denial can take effect before background index cleanup completes. Cache keys need tenant/principal scope, query normalization, index and embedding versions, and the relevant permission/revision epoch. A fast cached answer that bypasses revocation is not a successful cache hit.

Estimate before adding an ANN service

At 768 float32 dimensions, 200,000 vectors require 200000 * 768 * 4 = 614400000 bytes, about 614 MB in decimal units before graph edges, identifiers, text, metadata, replication, and allocator overhead. That estimate does not prove that exact scanning meets latency; it only shows that a large distributed vector database is not forced by the raw vectors alone.

Start with an exact-search oracle on the evaluation set. Compare candidate recall and stage latency for lexical, dense, and hybrid retrieval under real permission filters. A global recall score can look good while a small tenant with narrow filters receives no usable candidates. Report both overall and tenant/query-class results. Increasing candidate count is useful only while added reranking and context work remains affordable.

Suppose the query is “How long do we keep logs?” An obsolete policy repeats “log retention” several times, while the current policy says “remove these records after thirty days.” A lexical baseline can favor the obsolete document; a dense retriever can still retrieve both and leave the error to the ranker. The repair is not necessarily a better embedding model. It is first to enforce current revision, then evaluate semantic recall among eligible documents.

Allocate an end-to-end budget

The table allocates the illustrative 1,500 ms first-token budget. It is a planning budget, not an assertion that stage p99 values add to the end-to-end p99; measure request traces to account for correlation, queueing, and overlap.

Stage Planning allocation First response to an overrun
Admission and authorization 100 ms Bound the queue; investigate access-service tails
Candidate retrieval 200 ms Inspect filters, query class, and index choice
Reranking 150 ms Reduce or batch candidates only after recall checks
Revision checks and context assembly 50 ms Coalesce metadata fetches; reject stale pointers
Model admission and prefill 800 ms Tune prompt budget and serving admission
Transport and first flush 100 ms Trace buffering and network tails
Reserve 100 ms Absorb measured variation, not permanent overload

The token budget also connects directly to the KV ledger. A 4,000-token prompt in the running model needs 500 MiB of logical KV before generated tokens and padding. Longer context can therefore lower generator batch capacity even if retrieval itself becomes more accurate. Track useful evidence per context token, not only the number of passages retrieved.

For an API-priced generator, let C_in and C_out be the contracted cost per million input and output tokens. A 4,000-input/200-output request costs 0.004 * C_in + 0.0002 * C_out for generation, before embeddings, reranking, retries, and infrastructure. These are symbolic prices, not a current vendor quote. For self-hosting, use reserved accelerator time and measured SLO-compliant throughput instead. Divide total service cost by successful authorized answers, counting failed attempts in the numerator.

Reproduce a failure before replacing components

Run python -m examples.rag from the repository root. The fixture has six synthetic documents and five queries. It includes a stale revision, a restricted administrator document, one ordinary answer, missing evidence, and conflicting current sources. The intentionally unsafe comparison searches every document and emits the top result. The guarded version filters permissions and current status, then applies a deterministic labeled-fact check.

Example status: Runnable excerpt; execute from the repository root after checkout.

from examples.rag import evaluate

baseline = evaluate(safe=False)
guarded = evaluate(safe=True)
assert baseline["correct"] == 2
assert baseline["acl_leaks"] == 1
assert guarded["correct"] == 5
assert guarded["acl_leaks"] == 0

The measured results of this fixture are:

Metric Unsafe baseline Guarded fixture
Correct decisions, including abstention 2 / 5 5 / 5
Queries exposing unauthorized retrieved content 1 / 5 0 / 5
Queries retrieving an obsolete revision 2 / 5 0 / 5
Answerable queries with all required evidence retrieved 2 / 2 2 / 2
Correct abstentions on unanswerable/conflicting queries 1 / 3 3 / 3

Both versions retrieve the needed evidence for the answerable queries. That retrieval metric alone misses the baseline's wrong revision choice, unauthorized content, and unjustified answers. The table is useful precisely because it exposes different failure boundaries instead of compressing everything into one quality score.

The fixture is not an LLM benchmark. Its topic and answer fields are hand-labeled ground truth, and equality of those labels is not a production contradiction detector. Five hand-built cases do not establish a population accuracy rate or resistance to prompt injection. They are deterministic regression tests for specific failures. A real generator needs separate evaluation of entailment, partial support, conflicting scope, and calibrated abstention.

Run a documentation assistant without answer labels

The next example removes the fixture's topic and answer fields. examples/documentation_assistant.py loads four Markdown documents, splits their sections into seven paragraph chunks, retrieves permitted evidence, and assembles an answer from a verbatim paragraph. The corpus contains current service instructions, backup instructions, an administrator-only procedure, and an archived policy. The current log-retention policy says 30 days; the archived version says 90.

Run python -m examples.documentation_assistant 'How long are service logs retained?'. It returns the current policy with citation service:0:0 and a SHA-256 document revision. An emergency-access question abstains for the default reader identity and returns the procedure with --role admin. This flag selects a trusted test identity; a deployed service must obtain identity from authentication rather than accepting a caller's role claim.

Example status: Runnable excerpt; execute from the repository root after checkout.

from examples.documentation_assistant import answer, index, load_store

store = load_store()
chunks = index(store)
result = answer("How long are service logs retained?",
                "reader", chunks, store)
assert result["status"] == "answered"
assert "30 days" in result["answer"]
assert result["citations"][0]["document"] == "service"

store.revoke("service", "reader")
result = answer("How long are service logs retained?",
                "reader", chunks, store)
assert result["status"] == "abstained"

Follow the data boundary. The index holds document IDs, revisions, headings, and paragraphs. The source store owns permissions and current status. Retrieval filters against that store before computing a BM25-style lexical score, then requires at least 60% query-term coverage. This threshold is an uncalibrated heuristic. The answer function rechecks authority before generation and again before returning text. A changed revision, revocation, or unavailable authority suppresses the answer.

The default generator selects the highest-ranked paragraph. Citation validation accepts only an exact retrieved paragraph bound to its source revision; an invented citation or rewritten quotation fails. This is an extractive baseline, not LLM synthesis. There are no model calls, tool executions, or external side effects. The sequential checks illustrate the boundaries in one process, not a distributed authorization transaction.

Run python -m examples.assistant_evaluation --repeats 100 to measure it. Evaluation labels live in a separate module and are never passed into retrieval or generation. On September 27, 2026, the local macOS ARM64 run used Python 3.12.14 and produced:

Measurement Local result
Expected source/span or abstention matched 8 / 10 cases
Required evidence recalled on answerable cases 6 / 7
Answers with mechanically valid verbatim citations 7 / 7 emitted answers
Correct abstentions on unanswerable cases 2 / 3
Sequential resident-index latency, p50 / p95 0.0167 / 0.0216 ms
Process CPU time for 1,000 timed requests 0.0178 s
Model API calls and billed API cost 0 calls; $0

The timing run repeats ten synthetic cases 100 times after one warm-up. It excludes network, model inference, concurrent load, and production storage. Repetition adds timing observations, not quality samples. Total infrastructure cost is unmeasured; a zero API bill does not establish zero operating cost. The commands, corpus, timing boundary, and fault tests are documented in docs/part6-runnable-assistant-2026-09-27.md.

Inspect the failures before changing a component. “When will diagnostic records be purged?” misses the log-retention paragraph because the vocabulary differs. That is a retrieval failure. “What is the password reset retention?” retrieves a genuine password-reset paragraph about a link's expiry. Its quotation and citation pass, but it does not answer the retention question. That is an answerability failure. A support check cannot replace a relevance check.

The tests also inject revocation during generation, a stale index, permission-service failure, fabricated citations, changed quote text, generator exceptions, and a deadline overrun. Late results are discarded; the deadline does not interrupt a blocked callback. A production implementation needs cancellation and bounded execution separately. To extend the example, compare hybrid retrieval on held-out paraphrases, then add an answerability gate. Introducing an LLM requires new semantic-support, usage, cost, and adversarial evaluations; these CPU results do not predict them.

Build the evaluation set around decisions

For the hypothetical service, begin with an adjudicated set of 200 queries drawn from real user needs with appropriate permission to use them. As an initial allocation, reserve 100 for ordinary answerable questions, 30 for recent updates, 30 for permission boundaries, 20 for missing evidence, and 20 for conflicting sources. These counts are a sampling plan, not existing collected data. Keep document revisions and access roles with each case, split by source/topic where possible, and retain a held-out set for changes to the retriever, prompt, or verifier.

For each query, annotate required evidence, acceptable answers, unacceptable claims, and whether abstention is correct. Multi-hop questions may require several passages; retrieving one supporting sentence is not complete evidence coverage. Two reviewers should resolve ambiguous policy scope before the example becomes an automatic oracle. Do not use an LLM judge's preference as the sole definition of correctness.

Report retrieval recall at k on answerable cases, answer correctness on all cases, and citation support/completeness only where an answer was emitted. Report abstention precision and recall separately so a model cannot earn a high safety score by refusing everything. Record ACL violations and stale disclosures as counts with their denominators, not as a tiny component of an average score. Keep paraphrase robustness, rare identifiers, multilingual inputs, and long documents as visible slices when they matter to users.

An answer may be factually right from model memory but unsupported by the provided documents. It can pass answer correctness and fail citation grounding. Conversely, a quotation can faithfully repeat a document that is obsolete or outside the user's access scope. These are distinct errors with different fixes.

Operate revisions and failures as part of retrieval

Evaluate the exact-search oracle, the production retriever, and the generator separately, then join them in trace replay. Record the eligible corpus revision, candidate IDs and scores, authorization decision, selected context, model/prompt revision, citations, stage times, and cancellation outcome. Avoid storing protected document text in broad-access logs; log identifiers and controlled diagnostic samples instead.

On an embedding migration, write the new index beside the old one and shadow queries with both embedding versions. Compare filtered recall, stale-pointer rate, cost, and latency before switching the routing manifest. Never compare old query embeddings with new document embeddings merely because their vector dimensions match. Keep the old compatible pair available for rollback while the new index proves stable.

On retriever timeout, the safe fallback is an explicit retrieval-unavailable response or a policy-approved reduced service, not an answer presented as grounded without evidence. On reranker timeout, a lexical or hybrid ordering may be acceptable only if its quality was evaluated and the response remains inside policy. On conflicting evidence, show the permitted sources or abstain; do not silently choose based on recency when policy scope differs. On permission-service failure, protected retrieval is unavailable.

Prompt injection belongs in a separate adversarial suite. Include documents that imitate system messages, request tool execution, or try to disclose other tenants' data. The generator must not gain capabilities from retrieved text. Restrict the service to answering unless an explicitly authorized workflow grants tools, and enforce those permissions outside the model. Passing the deterministic fixture is not evidence that these attacks have been handled.

Design Exercises

  1. Design a secure RAG system for enterprise documents.
  2. How do you evaluate retrieval and generation separately?
  3. What happens when an embedding model changes?
  4. How do ACL filters interact with approximate search?
  5. Design defenses against prompt injection in retrieved content.

Worked design answers

  1. Secure enterprise retrieval: resolve user scope, filter candidates, recheck current revision and authority before context leaves the retrieval service, and invalidate scoped caches on permission changes. Keep canonical ownership outside the index.
  2. Separate evaluation: use evidence recall to diagnose retrieval, correctness to score the decision, and citation support/completeness to score grounding. The fixture shows why identical recall can coexist with different answer quality.
  3. Embedding migration: maintain versioned query/index pairs, shadow against a fixed evaluation corpus and roles, then switch an atomic manifest with rollback. Dimension compatibility is not semantic compatibility.
  4. ANN plus filters: benchmark recall after access filtering, particularly for small or selective tenants; compare with an exact oracle and choose partitions or candidate budgets from measured tails.
  5. Injection defense: treat retrieved text as data, enforce capabilities outside the model, and test unauthorized side effects separately from benign task success. Do not use blanket refusal as the sole success metric.

A real-model extension that loses to the baseline

examples/model_application.py replaces the scripted top-passage selection with the pretrained SmolLM2-135M-Instruct checkpoint at revision 12fd25f77366fa6b3b4b768ec3050bf629380bac. It runs locally in FP32 with PyTorch 2.8.0 and Transformers 4.57.1. Retrieval, authority checks, evidence identity, and the evaluation cases stay fixed. The model receives only the query and eligible passages; expected labels are not in its prompt.

The model must return exactly one JSON object selecting a candidate ID or abstaining. The host resolves a valid ID into the original verbatim paragraph. This architecture measures learned evidence selection under a strict interface; it does not claim free-form synthesis or independent entailment verification.

The recorded run matched 2 of 10 regression cases, versus 8 of 10 for the extractive baseline. Retrieval skipped generation on three cases; all seven actual model calls failed the strict selection interface. Some returned natural-language source text; others added fields, emitted the literal placeholder passage-id, or ran into the 48-token limit. The two successful outcomes were host-side abstentions, not successful generated answers. Raw responses, template hash, configuration, and per-case outcomes are retained in docs/experiments/model-application-cpu.json.

The decision is to retain the deterministic baseline. A more capable checkpoint, constrained decoding, or a redesigned selection task could be tested next, but silently accepting malformed output would change the interface and the experiment. The negative result demonstrates why model integration and model usefulness are separate claims. Ten hand-authored cases are regression coverage, not a held-out estimate of production quality; repeated timing does not increase that quality sample size.

The same separation applies to the agent chapter. Scripted policies test the host's control loop; a learned policy additionally needs task-outcome evidence under a fixed tool budget. Do not credit host-side rejection as evidence that the policy reliably chose safe or useful actions.

Separate formatting failure from evidence selection

The follow-up keeps the checkpoint, prompt, corpus and host checks fixed. A finite grammar permits only {"chunk":"eligible-id"} for retrieved candidates or {"chunk":null}. The model chooses evidence or abstention; expected labels never enter its prompt or grammar. Syntax constraints cannot make irrelevant evidence useful.

examples/model_followup.py fixes ten new diagnostic queries before this comparison runs, with a recorded case-manifest hash and no tuning loop. They use the same small corpus and author, so they are not an independently sampled benchmark or production-quality estimate.

Same-checkpoint comparison Prompt only Finite answer grammar
Correct task outcomes / all ten cases 3 / 10 8 / 10
Calls reaching the model 5 5
Generated interface failures 5 0
Correct evidence selections / model calls 0 / 5 5 / 5
Answerable cases missed before generation 2 2

Three correct abstentions come from the host's retrieval gate in both conditions. The two answerable misses ask about the backup region and purging diagnostic records; the lexical coverage threshold rejects their required evidence before either decoder runs. The finite grammar repairs the five malformed responses, but cannot repair those retrieval misses. The deterministic baseline also matches 8/10, so this experiment provides no reason to pay the model's additional execution cost for this fixture.

Each of the five generated cases has exactly one retrieved candidate, plus null in the grammar. The run therefore establishes constrained interface execution and acceptance of the supplied correct paragraph. It does not test discrimination among competing passages or model-driven abstention: an unconditional first-candidate selector matches all five generated successes. The negative adoption decision remains useful, but a harder selection diagnostic is needed before attributing the result to reliable semantic discrimination. A larger experiment should freeze document/user-separated cases and include ambiguous eligible candidates, conflicting sources and prompt injection. Free-form synthesis and a learned agent policy remain separate studies; this book's completed local experiment concerns constrained evidence selection and verbatim rendering.

Before loading, the runner checks weights, configuration, tokenizer and generation files against docs/model-snapshots/smollm2-135m.json, whose bytes were verified against pinned publisher Git/LFS hashes. Wrong revisions, altered files and extra files are rejected. Results bind the manifest digest to prompt/template hashes; a revision-shaped command-line label alone is insufficient.

Competing passages expose valid but wrong choices

examples/model_selection_diagnostic.py freezes six further diagnostic questions before execution and runs each in lexical and reversed candidate order. It keeps the same verified checkpoint, prompt, finite grammar and buffered authority checks. To isolate selection, it deliberately replaces the 60% coverage gate with a broader top-three lexical shortlist, retaining even zero-overlap tails. Each call therefore sees three authorized current paragraphs. Expected source labels enter only the scorer. This is a new selection-stage workload; its scores are not directly comparable to the earlier end-to-end ten-case results.

Four questions require a particular passage; two require null despite available passages. Reversal gives twelve views of six questions, not twelve independent tasks. The local CPU run recorded in docs/experiments/model-selection-diagnostic.json produced:

Diagnostic outcome Recorded result
Interface-valid model outputs 12 / 12
Correct source or null, across both orders 5 / 12
Always choose first candidate baseline 4 / 12
Correct model abstentions on null-required views 0 / 4
Questions whose selected source changes with order 4 / 6

The lexical-order backup schedule answer is correct. Reversing the same passages makes the model select the backup-location paragraph instead. A password-retention question selects an irrelevant backup paragraph in both orders; the grammar accepts its ID because the paragraph is eligible, not because it answers the question. The log-retention question succeeds in both orders. All selected text remains a verbatim authorized quote, so these are relevance and abstention failures rather than citation-format or access failures.

This diagnostic supplies the missing valid-but-wrong examples. It supports retaining the deterministic baseline while investigating retrieval and answerability separately. A one-view gain over the first-candidate policy does not justify adoption on six constructed questions, especially with failed null cases and order sensitivity. The program records candidate IDs/counts, expected and selected sources, raw model responses, prompt/template and case-manifest hashes, token counts and elapsed times. Neither it nor the earlier experiment establishes free-form synthesis quality or production reliability.