A document pipeline can fail in a way that looks a lot like success. The job finishes, the index status is green, the file count matches what you uploaded. Then someone asks a question and gets nothing back. No error, just an empty answer.
It's a common trap, and a recent community thread about PDFs with Swedish file names is a good example of it. The cause is nearly always the same: we watch the input side (files found, files processed) and not the output side (text that ended up searchable). A file that parses to zero characters still counts as "processed".
This post walks through a small pattern that's worth adding to every document RAG pipeline on Databricks. It has four steps:
- Ingest files with a stable id that doesn't depend on the file name.
- Parse them with ai_parse_document and keep the raw result.
- Build a per-document health table and alert on zero-text documents.
- Run a self-retrieval check against the vector index.
It's all SQL plus a few lines of Python, and it runs on serverless.
Step 1: Ingest with a content hash as the id
File names are for people, not keys. They have spaces, accents, and sometimes two different Unicode encodings of the same letter that look identical on screen. So the document id is a hash of the bytes, and the name is just a column.
CREATE TABLE IF NOT EXISTS main.rag.raw_docs (
doc_id STRING,
original_name STRING,
path STRING,
bytes BIGINT,
content BINARY,
ingested_at TIMESTAMP
);
MERGE INTO main.rag.raw_docs t
USING (
SELECT
sha2(content, 256) AS doc_id,
element_at(split(path, '/'), -1) AS original_name,
path,
length(content) AS bytes,
content,
current_timestamp() AS ingested_at
FROM read_files('/Volumes/main/rag/source_docs/',
format => 'binaryFile',
pathGlobFilter => '*.{pdf,docx}')
) s
ON t.doc_id = s.doc_id
WHEN NOT MATCHED THEN INSERT *;A nice side effect: if someone uploads the same PDF twice under different names, it only gets parsed once.
Step 2: Parse once and keep the result
ai_parse_document returns a VARIANT with document.pages, document.elements, error_status and metadata. Store the whole thing so you never have to pay to parse the same file twice while you tweak the chunking.
CREATE TABLE IF NOT EXISTS main.rag.parsed_docs (
doc_id STRING, original_name STRING, parsed VARIANT, parsed_at TIMESTAMP
);
INSERT INTO main.rag.parsed_docs
SELECT r.doc_id, r.original_name, ai_parse_document(r.content), current_timestamp()
FROM main.rag.raw_docs r
LEFT ANTI JOIN main.rag.parsed_docs p ON r.doc_id = p.doc_id;
Each element has a type (text, table, section_header, page_footer and so on) and a content string. Tables come back as HTML, which works fine for retrieval.
Step 3: Per-document health, and an alert on silence
This is the step that saves the most time. For every document, count the elements and characters that came out, and record whether the parser reported any page errors.
CREATE OR REPLACE VIEW main.rag.doc_health AS
SELECT
p.doc_id,
p.original_name,
count(e.value) AS elements,
coalesce(sum(length(e.value:content::string)), 0) AS extracted_chars,
to_json(any_value(p.parsed:error_status)) AS parse_errors
FROM main.rag.parsed_docs p,
LATERAL variant_explode_outer(p.parsed:document:elements) AS e
GROUP BY p.doc_id, p.original_name;
Then make a SQL alert on this query and have it fire when the count is above 0:
SELECT count(*) AS empty_docs
FROM main.rag.doc_health
WHERE extracted_chars < 200;
I'd use 200 instead of 0 because a scanned cover page or a file that's only a logo can produce a few characters of junk. Tune it to your documents. The point is to have a signal that tells "worked" apart from "quietly produced nothing".
Step 4: Chunk, index, and run a self-retrieval check
For chunks, keep it simple: one row per meaningful element, with the document title in front so the embedding knows where it came from. Headers, footers and page numbers get dropped.
CREATE OR REPLACE TABLE main.rag.doc_chunks
TBLPROPERTIES (delta.enableChangeDataFeed = true) AS
SELECT
concat(p.doc_id, '-', e.pos) AS chunk_id,
p.doc_id,
p.original_name,
concat(p.original_name, '\n\n', e.value:content::string) AS chunk_text
FROM main.rag.parsed_docs p,
LATERAL variant_explode(p.parsed:document:elements) AS e
WHERE e.value:type::string IN ('text', 'table', 'section_header', 'title')
AND length(e.value:content::string) > 20;Change data feed has to be on for a Delta Sync index. Then create the index:
from databricks.vector_search.client import VectorSearchClient
vsc = VectorSearchClient()
index = vsc.create_delta_sync_index(
endpoint_name="rag-endpoint",
source_table_name="main.rag.doc_chunks",
index_name="main.rag.doc_chunks_index",
pipeline_type="TRIGGERED",
primary_key="chunk_id",
embedding_source_column="chunk_text",
embedding_model_endpoint_name="databricks-gte-large-en",
)If your documents aren't in English, pick an embedding model that handles that language. It matters more than any chunking trick.
Last, the self-retrieval check. For each document, take a sentence from its own text, search for it, and see if that document comes back in the top results. If a document can't find itself, users won't find it either.
import random
index = vsc.get_index("rag-endpoint", "main.rag.doc_chunks_index")
chunks = spark.table("main.rag.doc_chunks").toPandas()
misses = []
for doc_id, group in chunks.groupby("doc_id"):
probe = random.choice(group["chunk_text"].tolist()).split("\n\n", 1)[-1][:300]
hits = index.similarity_search(
query_text=probe, columns=["doc_id"], num_results=5
)["result"]["data_array"]
if doc_id not in [h[0] for h in hits]:
misses.append(group["original_name"].iloc[0])
print(f"{len(misses)} of {chunks.doc_id.nunique()} docs failed self-retrieval")
print(misses)Run this right after each index sync. Writing the result to a table also gives you a history to compare against when someone changes the embedding model or the chunking.
What I'd take away from this
- "Files processed" tells you about input. Always measure output too: characters extracted, chunks created, documents you can actually retrieve.
- Key everything on a content hash, not a file name. Keep the name around for display only.
- Store the raw parse result, so changing the chunking doesn't mean parsing everything again.
- A cheap SQL alert on zero-text documents plus a self-retrieval check catches most silent failures before your users do.
None of this is complicated, and that's kind of the point. It's maybe an hour of work, and it turns "the index is green but nothing works" into a specific list of files to look at.
If you've built something similar or found other ways a document pipeline fails silently, I'd love to hear about it in the comments.