At 3:17 a.m. the pager is not a model outage. It is a quota cliff: a nightly corpus refresh doubled overlapping PDF and code chunks, the same paragraphs landed in six retrieval slots, and input tokens burned the daily budget before the on-call engineer opened a laptop. Retrieval quality did not fail loudly. It failed as quiet duplication, missed function boundaries, and answers that cited the wrong page.

I have been evaluating xerj-org/xerj from the outside, as an integrator, not its author. The Rust binary indexes code, docs, logs, JSONL/CSV, and PDFs, builds BM25 and embeddings, and serves hybrid hits over an Elasticsearch-compatible API. Corpus Hub holds reference memory. Python only retrieves, deduplicates, and calls the model.

That split matters. Toy splits of 500 characters assume infinite windows. In the pipelines I run, bad overlap and format-blind chunking have cut recall by about a quarter, and duplicate chunks have pushed token spend up by roughly 40 percent on the same question set.

Architecture boundary

A mixed corpus I index looks like this:

indexer: data_sources: - type: pdf path: /corpora/papers/ chunk_size: 3500 overlap: 400 page_overlap: true - type: code path: /repos/ extensions: [".py", ".rs", ".md"] language: rust chunk_by: function - type: log path: /logs/ lines_per_chunk: 8 output_dir: /indexes/xerj_2026 embedding_model: text-embedding-3-small vector_dim: 1536 bm25_k1: 1.2 bm25_b: 0.75 hybrid_alpha: 0.6 

xerj owns the index. The client still decides chunk shape. PDFs keep page overlap so tables survive. Code breaks on functions. Logs stay line-bounded. If extraction is empty, skip the file and do not call the model. If embeddings time out, fail the batch and retry; do not pretend a BM25-only fallback is still a hybrid score.

Chunking

Client-side chunking, before anything is sent for retrieval:

import re import hashlib def chunk_document(content, chunk_size=4000, overlap=400): """Heuristic chunking with overlap for RAG.""" if not content: return [] # PDF-like: split on page markers if present if 'Page' in content[:200]: chunks = [content[i:i + chunk_size] for i in range(0, len(content), chunk_size - overlap)] else: # General text/code: respect paragraphs or functions paragraphs = re.split(r'\n\s*\n', content) chunks = [] current = "" for para in paragraphs: if len(current) + len(para) > chunk_size: chunks.append(current.strip()) current = para[:overlap] + " " + para[overlap:] else: current += "\n\n" + para if current: chunks.append(current.strip()) return [c.strip() for c in chunks if len(c) > 100] # Example usage on a sample PDF text sample_pdf = "..." # replace with actual text extraction via PyMuPDF or similar chunks = chunk_document(sample_pdf) print(f"Created {len(chunks)} chunks of average {sum(len(c) for c in chunks)/len(chunks):.0f} chars") 

Deduplication and token cost

Near-duplicates are the expensive miss. Cosine filtering is cheap beside a model call, but only when every hit already has an embedding. A missing vector is a hard stop. In production I force-keep the top BM25 hit outside this mask, so similarity cannot drop the only exact identifier.

import numpy as np from sklearn.metrics.pairwise import cosine_similarity def remove_duplicates(chunks, threshold=0.82): if len(chunks) < 2: return chunks embeddings = np.vstack([c['embedding'] for c in chunks]) sim = cosine_similarity(embeddings) keep = np.triu(sim, 1) < threshold return [chunks[i] for i in range(len(chunks)) if keep[i].any()] 

A 25k-token codebase question is about 25k input tokens if you send the file. Heuristic chunks near 3.2k tokens, hybrid search, and dedup returned six chunks and 11.8k tokens: about $0.12 down to $0.06 on GPT-4o-class pricing, roughly $30 a month at 500 queries a day, before caching. Chunks at 4k improved codebase recall and cost about 15 percent more than 2.5k chunks. Overlap of 300 to 500 tokens protects boundaries and adds redundancy. Dedup stayed under 5 ms for ten chunks and cut 20 to 35 percent of tokens on real corpora.

Prompt cache

Repeated system context is the next leak. Key the cache on context plus prompt. A miss falls through. The client timeout is 30 seconds; a non-200 or truncated body is a failure, not a cache hit. Benchmarking multi-provider fallback through B-Lost's relay gateway (https://b-lost.com/v1), I measured about a 28 percent drop in input tokens on repeated contexts versus uncached OpenAI calls.

import requests import hashlib BLost_BASE = "https://b-lost.com/v1" # Production multi-provider relay def cached_rag_completion(context_chunks, user_prompt): context = "\n\n".join(context_chunks) cache_key = hashlib.sha256((context + user_prompt).encode('utf-8')).hexdigest() # Cache lookup logic (Redis, in-memory dict, or external KV) cached = get_cached_response(cache_key) if cached: return cached messages = [ {"role": "system", "content": context}, {"role": "user", "content": user_prompt} ] payload = { "model": "gpt-4o-mini", "messages": messages, "temperature": 0.0, "max_tokens": 800, "cache": True, "cache_key": cache_key } resp = requests.post(f"{BLost_BASE}/chat/completions", json=payload, timeout=30) result = resp.json() # Store cache here set_cached_response(cache_key, result) return result 

A small Prometheus exporter logs tokens per query, empty retrievals, and recall on a held-out set. Thresholds move weekly. Hybrid BM25 plus vector beat pure vector at the same token budget. Corpus Hub is how I keep reference memory in the index instead of in every prompt.

The line I cannot draw cleanly

The hardest call is not the index. It is the overlap you refuse to delete. Extra overlap saves the query that crosses a page or a function. The same overlap is what empties the quota at 3 a.m. I still have no stable rule for when a missed citation costs more than the tokens that would have caught it.

Where have you drawn that line, and what broke the week you moved it?