RAG on tax PDFs: the bugs were in the code around the model
The knowledge base behind the AI layer for a fintech platform is US tax law and IRS guidance, ingested from HTML, XML and PDF. When people talk about RAG quality they usually mean the model and the retriever. On this project the model was the least of the problems. The bugs that cost time were in deterministic code around it – validators, batch loops, size limits – which is good news, because that code can be fixed for good.
Three of them, and one decision that made the system safer by making it less helpful.
Tables: the validator was stricter than the truth
Tax PDFs are full of tables, and text extraction flattens them into noise. So a model converts each table to Markdown, and code – not another model – checks the result three ways:
- Numbers. The model added nothing: every number in its output exists in the table or on the page.
- Completeness. The model lost nothing: every number in the table is in its output.
- Totals. A row or column named Total equals the sum of what it totals, exactly, with no rounding tolerance. Subtotals aren’t summed, and the first column is treated as row labels.
The model was mostly fine. The validator rejected correct tables, for two reasons.
Completeness collected ‘the numbers of the table’ too generously. It included numbers from the caption, the notes, the footnotes and the page labels, which the model rightly left out of a Markdown table. The check was demanding that the model copy page furniture. Those elements are now excluded from what must be carried over.
Totals were triggered by a word, not a role. A column called ‘Total Assets’ in one form’s table was taken for a totals column and checked as a sum of its neighbours, which it isn’t. The pattern now requires ‘Total’ as a word on its own – ‘Tax Year Totals’, ‘Total for 2021’ – rather than any measure whose name starts with it.
Large tables hit a different wall: the 60-second timeout shared by every model call. Table extraction got its own task class with a 120-second timeout, set through an environment variable and used only by the loader, never by the agents’ runtime. A timeout belongs to a kind of work, not to the provider.
If I started again, I would build the completeness check from a sample of real rejections instead of from a rule. I wrote the rule first, and the real tables then taught me what it had got wrong.
Embeddings: where 9,829 comes from
text-embedding-3-large accepts at most 8,191 tokens and rejects longer input. Chunk sizes are usually set in characters, so you need a characters-per-token ratio, and the common rule of thumb of about four is true for prose and wrong for tax tables.
I measured it on the model on 19 October. A table of dates and dollar amounts came out at 1.65 characters per token; prose at about four. The limit uses a pessimistic 1.5, and keeps back a fifth for the section heading that is embedded with each chunk:
EMBED_MAX_TOKENS = 8191
CHARS_PER_TOKEN_WORST = 1.5 # measured 1.65 on tables of dates and amounts
HEADING_SHARE = 1 / 5 # the section heading is embedded with the chunk
MAX_CHUNK_CHARS = int(EMBED_MAX_TOKENS * CHARS_PER_TOKEN_WORST * (1 - HEADING_SHARE)) # 9829
Anything longer is split at write time on paragraph and then sentence boundaries.
The more damaging bug was in the batch pass. It stopped at the first chunk the model rejected, so one oversized chunk left everything after it in the document without a vector. One document was missing two of 191; in others, everything after the first bad chunk was. Nothing failed loudly – retrieval simply never found those passages. The pass now skips and records a rejected chunk, and a document’s status shows how many chunks have no vector. In a retrieval system, ‘how much of the corpus is actually searchable’ is a metric, and it should be on a dashboard, not discovered.
Grounding: a rule counts only if its source checks out
The agents answer from rules – deadlines, thresholds, forms – and each rule cites a section of a source document. A citation is easy to write and easy to get wrong, so a rule grounds an answer only if all of this holds: the source matches the rule’s jurisdiction, topic and year; that revision is in force on the date in question; the cited section exists among the document’s chunks; and the hash of the section text matches the hash recorded with the rule.
The hash is taken from text, not from the file, so re-parsing the same document doesn’t change it:
- the section’s chunks in order, joined by a space;
- Unicode NFC;
- every run of whitespace collapsed to one space, edges trimmed;
- case and punctuation kept, because in legal text they carry meaning;
- SHA-256 of the result.
The idea comes from the text quote selector in the W3C Web Annotation model: anchor a reference to the words, not to the bytes of a particular copy. If any condition fails, the rule fails to import, and it is checked again when read.
This made the system less helpful before it made it more trustworthy. Until the rules were loaded with exact sections, every explanation went to a human specialist instead of being answered. I would make that trade again. Later the same check caught a calendar template citing a section called ‘Form 8938’ that doesn’t exist among the sections of the parsed instructions. It could not be approved. It is still a draft in production, waiting for a version that cites a section that exists – which is the right place for it.
Hybrid search, and what I deliberately left out
Retrieval combines two lists in the same PostgreSQL. Full-text search over tsvector finds exact identifiers – form numbers, section numbers – that embeddings blur. Vector search with pgvector finds the question asked in other words. Reciprocal Rank Fusion joins them: each chunk scores 1 / (60 + rank) in every list it appears in, and each list contributes its top 50. Candidates are filtered by the revision in force on the date of the tax event, and chunks are taken in order until they fill the character budget.
Those numbers are starting values, and there is a separate retrieval eval – 20 queries, Recall@k and MRR – to move them. Just as deliberately, there is no similarity threshold on the vector list, no reranker, no BM25 extensions and no HNSW index. Each is a reasonable thing to add. None was added before the eval showed a need, because every one of them is another parameter that changes results in ways you can only see with an eval you already trust.
The pattern
All three bugs were deterministic and all three were found late, because nothing failed loudly: a validator rejected good tables, a batch loop quietly skipped the rest of a document, a check refused a citation that looked fine. In RAG the model gets the attention, but the boundary code decides what the model ever gets to see. Measure that code against real documents as carefully as you evaluate the model. It is the same lesson as in testing LLM integrations: the failures that hurt are at the boundaries you assumed were simple.