Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 10 min read

Embedding Truncation in RAG: Test What the Encoder Actually Sees

Your vector database contains the full paragraph. The embedding request succeeded. Yet a search for the refund exception at the end of that paragraph returns every policy except the one you need. Check what the embeddin

Your vector database contains the full paragraph. The embedding request succeeded. Yet a search for the refund exception at the end of that paragraph returns every policy except the one you need.

Check what the embedding model actually received. If its tokenizer clipped the tail, the database can show you text that the vector has never represented. A normal vector dimension, a successful batch, and even a correct citation from a broad query can all coexist with this bug.

You can pin it down with two chunks that share a long prefix and disagree at the end. This guide builds a Python test that catches the loss at the token boundary, adds a guard before indexing, and shows how to tell truncation apart from weak retrieval.

Find the stage that lost the evidence

Say you index a billing policy with a long introduction and the line β€œRefunds for duplicate invoices require supervisor approval.” A search for the policy name finds it. A search for who approves a duplicate invoice refund misses it. That describes a symptom. To diagnose it, follow the approval rule through your pipeline.

Stage Check What a failure tells you
Extraction Does the source text contain the approval rule? Fix the parser, OCR, or normalization.
Chunking Does a child chunk contain the complete rule? Change the split boundary or carry adjacent text.
Encoding Does the rule fit in the formatted token sequence? Split again or change the embedding input budget.
Retrieval Is the expected child in dense top-k? Inspect query encoding, filters, similarity, or index settings.
Answer assembly Does the final prompt contain the rule? Inspect reranking, deduplication, and context packing.

Count and inspect the exact text your adapter formats for the encoder. This can include a title, heading path, document prefix, and special tokens. A chunk that fits when tested in isolation can cross the limit when a worker adds a long title. The token count of a raw document also tells you little about which individual child failed.

A vector row can prove that encoding ran. To establish input coverage, inspect the sequence that encoding used.

For mixed PDFs, a missing sentence at extraction calls for an OCR regression fixture. If retrieval returned the right child and the sentence disappeared during answer assembly, check the RAG context budget. Keeping these checks separate makes the failed assertion point to a concrete repair.

Use the effective embedding limit

The input limit comes from the deployed model and serving path. A framework wrapper can impose its own cap. Query and document endpoints can apply different instructions. A model card can describe supported input while a service enforces a smaller cap. Start with the documentation, then confirm how your adapter behaves at the boundary.

Backend What to verify in your adapter
Sentence Transformers Check the effective input limit and any configured task prompts. The linked issue shows how valid embeddings can hide clipped inputs.
Ollama embed API Set truncate: false if you want oversize input to surface as an error. The endpoint documents truncation as the default.
OpenAI embeddings API Check the chosen model's per-input limit and the separate request-wide limits. Split individual inputs and batch by the limits that apply.

The Sentence Transformers truncation report, Ollama endpoint reference, and OpenAI embeddings endpoint reference describe different contracts. Keep backend-specific details in the adapter so a model switch can change the behavior in one place.

Write a tail-swap regression test

The simplest useful fixture has two versions of a fake policy. They start with identical text and end with different facts. Before applying a length cap, their token sequences must differ. With a right-truncating encoder, the long versions should become identical after clipping. A short version should still preserve the difference.

This example uses the published all-MiniLM-L6-v2 tokenizer and its model card's default 256-token limit. It runs locally with no vector database or model weights. Install tokenizers, then run the code from a directory where you can save the tokenizer file.

python -m pip install tokenizers
curl -fL https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/tokenizer.json -o tokenizer.json
from tokenizers import Tokenizer

LIMIT = 256
tokenizer = Tokenizer.from_file("tokenizer.json")
tokenizer.no_padding()
tokenizer.no_truncation()

def token_ids(text):
    return tokenizer.encode(text, add_special_tokens=True).ids

def checked_input(text):
    size = len(token_ids(text))
    if size > LIMIT:
        raise ValueError(f"Embedding input has {size} tokens; limit is {LIMIT}")
    return text

header = "Billing policy. "
padding = "Customers can download invoices from their account. " * 80
finance = "Duplicate refunds require finance approval."
support = "Duplicate refunds require support approval."
long_pair = [header + padding + ending for ending in (finance, support)]
short_pair = [header + ending for ending in (finance, support)]

assert token_ids(long_pair[0]) != token_ids(long_pair[1])
assert all(len(token_ids(text)) > LIMIT for text in long_pair)
assert all(len(token_ids(checked_input(text))) <= LIMIT for text in short_pair)
try:
    checked_input(long_pair[0])
except ValueError:
    pass
else:
    raise AssertionError("Expected an oversized input to be rejected")

clipping_tokenizer = Tokenizer.from_file("tokenizer.json")
clipping_tokenizer.no_padding()
clipping_tokenizer.enable_truncation(max_length=LIMIT, direction="right")

def clipped_pair(pair):
    return [row.ids for row in clipping_tokenizer.encode_batch(pair)]

a, b = clipped_pair(long_pair)
assert len(a) == len(b) == LIMIT
assert a == b, "The fixture no longer hides the difference at the tail"

a, b = clipped_pair(short_pair)
assert a != b, "The short control should preserve both endings"

The paired inputs make the result easy to interpret. Both contain a different approval rule. After right truncation, the long pair yields the same IDs, including the model's special tokens. An encoder using those IDs and the same other inputs has no signal from which to distinguish those endings. This test compares integer sequences and avoids choosing a cosine threshold for floating-point vectors.

Your CI test should call the actual adapter's preparation code where possible. Pin the tokenizer and model revisions so the test inputs stay reproducible. Build a second boundary fixture with lengths exactly at the limit and one token over it. Compute those lengths after formatting and assert them in the test. If the template changes, the fixture then tells you when it no longer exercises the intended boundary.

Recheck the text after splitting

A token-aware splitter can propose slices. Give it a rough budget for the title and document instructions, then render each candidate and count the final token sequence. Token boundaries can change when two strings are joined. The final check should occur after assembling the string, including the separator.

If a candidate is too big, split it at the nearest paragraph or sentence boundary that still fits. For a table, try a smaller group of rows and repeat the column heading. For an API reference, keep the parameter name with its constraints so the returned child can answer a question by itself. As a fallback for a single long span, use token-aware windows and keep source offsets for citations. Process the new candidates through the same validator.

Make your handling of overlong metadata explicit. For instance, a deeply nested heading path might exhaust the budget before any body text arrives. Preserve the source ID and stable heading location, then shorten the display path under a documented rule. When a formatting or input error prevents meaningful indexing, record that failure for the document and let other valid documents proceed.

Add a retrieval test that only the tail can pass

The token test confirms input coverage. A retrieval test tells you whether the recovered evidence is discoverable. Run the second test against a tiny index built through the same ingestion adapter that production uses.

  1. Index a procedure with a long shared introduction and a unique instruction near its end. Add several procedures with similar introductions and different instructions.
  2. Ask a question that only the target instruction can answer, such as β€œWhere should duplicate-invoice reversals with an expired approval be sent?” Include at least one paraphrase.
  3. Run a query specific to the beginning as a control. A useful control finds a fact expressed in the leading section without naming the document.
  4. Run dense retrieval alone and check for a child ID tied to the source span that contains the instruction. Then rerun with the normal search stack to check what the user sees.
  5. Inspect the returned child evidence before asking a language model to generate an answer. Record the expected child or source span, rank, and whether its evidence made it into the final prompt.

Keep the first index small enough for exact similarity search when your vector store supports it. This removes approximate-search settings from the first diagnosis. With exact search working, test the real index settings in staging. If dense retrieval misses while hybrid search succeeds, inspect the lexical branch. A matching phrase can carry the hybrid result even when the dense vector lost the tail.

Avoid scoring only the parent document ID. A match for the opening paragraph can retrieve the right parent, whose displayed text contains the answer. That result is useful for the user interface. The child-level test still needs to show that the tail can drive discovery. For the same reason, include a few test questions whose wording shares little with the answer, so a match to an unusual keyword alone cannot explain every pass.

Repair the index without hiding failures

Fix new writes first. Run your formatter and token guard immediately before the embedding boundary. Treat a length error as a signal to split or repair a chunk. A retry with the same payload will still exceed the budget. Retry transient network errors separately, with limits that fit your ingestion worker.

Track affected documents

Emit counters for inputs checked, oversized inputs, inputs split again, and documents whose children failed to index. Add a token length histogram tagged by model and formatter version. When a spike appears after changing the splitter, compare the distribution before and after that release. An aggregate count can show the scope even when every batch response came back successful.

Use IDs and offsets to make individual failures traceable. Keep log fields small and bounded. If you need to inspect the exact text, do it from an authorized copy of the source with the matching formatter version. For a backfill, use the configuration that created the suspect vectors when you can. Applying today's chunker to yesterday's source may mask the oversized inputs that caused the problem.

Replace the affected vectors

Changing a splitter only affects future writes. For existing rows built from clipped input, recover the source text, render and split it with the fixed adapter, and embed the replacement children. Record the source revision and configuration used for each build. If an edit arrives during the job, publish the replacements only if they still match the active source revision.

Stage the new generation so search can switch from the old child set to the complete replacement set. This also prevents queries from returning two versions of the same paragraph while a document is being rebuilt. If you change models, verify that queries use the model and instructions paired with the active index. Keep the earlier generation available for a controlled rollback under the same document freshness rules.

Compare tail-evidence hit rate at a fixed top-k before and after the repair. Divide the number of tail questions that retrieve a child containing the expected evidence by the number of tail questions tested. Track leading-section questions separately. Include support policies with long headings, API references with tables, and documents in languages your tokenizer may segment more finely. Also record vector count and query latency. Splitting can recover missing evidence while increasing the number of children your system must search.

FAQ

How can I tell if my embedding model truncated a chunk silently?

Tokenize the exact formatted input with truncation disabled and compare its length with the effective limit of the deployed adapter. If you can inspect the actual model input, compare it with the untruncated sequence. For a hosted endpoint, use its reported truncation status or strict error mode when available, then exercise the boundary with a known fixture.

What is a safe chunk size for RAG embeddings?

Use the embedding backend's effective limit and test the final formatted input with its own tokenizer. Leave room for metadata, instructions, and special tokens. A splitter's character or word budget can help produce readable sections, but the embedding adapter should enforce the final token budget for each child.

Can overlap recover a sentence that the encoder clipped?

Overlap can help when another overlapping window includes the complete sentence and fits the limit. Confirm this with a tail-evidence query aimed at that child. If every returned window exceeds the cap after headings and prefixes are added, adjust the formatted window sizes first.

Does reducing embedding dimensions fix input truncation?

Input truncation caps the text the model reads. Output dimensions specify the width of the vector the model returns. Increasing or reducing the vector width has no effect on whether the input sequence reached the end of the paragraph. Check the input limit for the deployed model and serving path.

Should I re-embed everything after finding truncated chunks?

Start with the affected document revisions if you can reconstruct what the original adapter sent. Otherwise rebuild the index partition associated with the suspect configuration and test it before switching traffic. Replacing the stored text alone leaves the clipped vector in place.

Why can keyword search find an answer that vector search misses?

Keyword search can index the full stored text while the dense encoder sees only a prefix. Compare dense-only and keyword-only results on questions aimed at the missing tail. Check token coverage first, then inspect query formatting, filters, and nearest-neighbor settings if the full evidence reached the encoder.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.